Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios For循环即使在条件完成后也会不断迭代解析JSON_Ios_Swift_Google Places Api - Fatal编程技术网

Ios For循环即使在条件完成后也会不断迭代解析JSON

Ios For循环即使在条件完成后也会不断迭代解析JSON,ios,swift,google-places-api,Ios,Swift,Google Places Api,我将JSON数据放入表视图中,并尝试使用for循环解析数据。但是,当循环通过JSON数据完成解析并将20个项目放入表视图时,它会重新启动流程,再次解析JSON,相同的数据再次出现在表视图中。这个过程也会重复很长时间 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. locationManager.delegate =

我将JSON数据放入表视图中,并尝试使用for循环解析数据。但是,当循环通过JSON数据完成解析并将20个项目放入表视图时,它会重新启动流程,再次解析JSON,相同的数据再次出现在表视图中。这个过程也会重复很长时间

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else{ return }

    var searchURL = NSString(format: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=50000&types=night_club&key=MY_API_KEY", (location.coordinate.latitude),(location.coordinate.longitude)) as? String

    var cityInfo = NSString(format: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=50000&types=locality&key=MY_API_KEY", (location.coordinate.latitude),(location.coordinate.longitude)) as? String

    manager.stopUpdatingLocation()
    getCityInfo(url: cityInfo!)
    callAlamo(url: searchURL!)
}

func getCityInfo(url:String){

    Alamofire.request(url).responseJSON(completionHandler: { response in

        self.parseJSON(JSONData: response.data!)
    })
}

func parseJSON(JSONData:Data){

    do{

        var readableJSON = try JSONSerialization.jsonObject(with: JSONData) as! JSONStandard

        // PARSING THROUGH JSON DATA TO GET CITY NAME

        if let results = readableJSON["results"] as? [JSONStandard]{
            for i in 0..<results.count{

                let item = results[i]
                let cityInfo = item["name"] as! String
                cityName.append(cityInfo)

                // GETTING PHOTO URL WITH photo_reference AND PUTTING THEM INTO imageURL ARRAY

                if let photos = item["photos"] as? [JSONStandard]{

                    for j in 0..<photos.count{

                        let photo = photos[j] as JSONStandard

                        let photoRef = photo["photo_reference"] as! String

                        let photoURL = NSString(format: "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%@&key=MY_API_KEY", photoRef) as? String
                        cityURL.append(photoURL!)
                    }
                }
            }
        }
        cityLabel.text = cityName[0]
        cityImage.sd_setImage(with: URL(string:cityURL[0]), placeholderImage: #imageLiteral(resourceName: "cityOfCalgary"))
    }
    catch{
        print(error)
    }
}

 func callAlamo(url:String){

    Alamofire.request(url).responseJSON(completionHandler: { response in

        self.parseData(JSONData: response.data!)
    })
}
 func parseData(JSONData:Data){

    do{
        var myReadableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard

        // PARSING THROUGH JSON DATA TO GET NAMES AND PICTURES OF PLACES, THEN PUTTING 
        // THEM INTO AN ARRAY AND OUTPUTTING THEM ONTO TABLE VIEW CELL

        if let results = myReadableJSON["results"] as? [JSONStandard]{

            for i in 0..<results.count{ //results.count = 20

                let item = results[i]
                let names = item["name"] as! String

                placeNames.append(names)

                // GETTING PHOTO URL WITH photo_reference AND PUTTING THEM INTO imageURL ARRAY

                if let photos = item["photos"] as? [JSONStandard]{

                    let photoRef = photos[0]
                    let photoReference = photoRef["photo_reference"] as! String


                    let photoURL = NSString(format: "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%@&key=MY_API_KEY", photoReference) as? String

                    imageURL.append(photoURL!)

                }

                if let geometry = item["geometry"] as? JSONStandard{
                    if let location = geometry["location"] as? [String : Any]{

                            let latitude = location["lat"] as? Double
                            let longitude = location["lng"] as? Double
                    }
                }
            }
        }
                // SHOULD BE PLACED AT THE END OF GATHERING DATA
                locationManager.stopUpdatingLocation()
                self.tableView.reloadData()
    }
    catch{
        print(error)
    }
}
`


此后,其他一切都保持不变。

因为我怀疑您多次调用了
parseData
。一种解决方案是停止监视委托方法中的位置

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else { return }

    let searchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(location.coordinate.latitude),\(location.coordinate.longitude)&radius=50000&types=night_club&key=AIzaSyA2LQsGK_I1ETnKPGbjWgFW9onZlHog6dg"

    // var cityInfo = NSString(format: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=50000&types=locality&key=AIzaSyA2LQsGK_I1ETnKPGbjWgFW9onZlHog6dg", (location?.coordinate.latitude)!,(location?.coordinate.longitude)!) as? String
    manager.stopUpdatingLocation()
    callAlamo(url: searchURL)
}
我对方法的主体进行了一些编辑,以避免使用所有的问号和感叹号


旁注:基本上注释编译器可以推断的类型

我猜
parseData
调用了两次,代码在方法中不会重复。一如既往,
.mutableContainers
在Swift中毫无意义,请省略
选项
参数,并对结果中的项使用快速枚举
。PS:并且不要在循环的每次迭代中重新加载表视图。在重复循环后放置行以及
stopUpdatengLocation()
。感谢您的评论和提示。我已经更新了我的代码,以反映您提出的一些建议,并显示哪个方法正在调用parseData。不幸的是,我仍然面临同样的问题。如果您有任何建议可以帮助我,请告诉我…您正在didUpdateLocations中调用callAlamo(url:searchURL!)。这是多次调用CallAlamoriiIlight的潜在客户。您建议我在哪里调用该方法?因此,我实现了您建议的方法,但同样的问题仍然存在=(我已经更新了代码)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else { return }

    let searchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(location.coordinate.latitude),\(location.coordinate.longitude)&radius=50000&types=night_club&key=AIzaSyA2LQsGK_I1ETnKPGbjWgFW9onZlHog6dg"

    // var cityInfo = NSString(format: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=50000&types=locality&key=AIzaSyA2LQsGK_I1ETnKPGbjWgFW9onZlHog6dg", (location?.coordinate.latitude)!,(location?.coordinate.longitude)!) as? String
    manager.stopUpdatingLocation()
    callAlamo(url: searchURL)
}