从未调用过URL会话下载任务完成块

时间:2018-11-20 23:40:26

标签: ios swift google-places-api nsurlsession nsurlsessiondownloadtask

我正在向Google Places API发出网络请求,以根据特定坐标获取附近的地点,然后运行任务以获取这些地点的照片。

我能够通过第一个任务成功获取地点详细信息,而在第二个检索照片的任务运行时,由于我观察到放置断点,因此它的完成区从未输入,因此没有照片。

urlString是正确的,我的apiKey可以正常工作,因为第一个任务再次返回正确的响应,并且我具有可以执行Web请求的位置的图片引用。任何指导将不胜感激,因为我很迷路-如果需要,可以提供更多详细信息。

下面是网络呼叫,该网络呼叫是根据ray wenderlich的guide改编的。

typealias PlacesCompletion = ([Place]) -> Void
typealias PhotoCompletion = (UIImage?) -> Void

class DataProvider {
    private var photoCache: [String: UIImage] = [:]
    private var placesTask: URLSessionDataTask?
    private var session: URLSession {
        return URLSession.shared
    }

//FIRST WEB REQUEST
func fetchPlacesNearCoordinate(_ coordinate: CLLocationCoordinate2D, radius: Double, types: [String], completion: @escaping PlacesCompletion) -> Void {
    var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true&key=\(googleApiKey)"
    let typesString = "restaurant"
    urlString += "&type=\(typesString)"
    urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? urlString

    guard let url = URL(string: urlString) else {
        completion([])
        return
    }

    if let task = placesTask, task.taskIdentifier > 0 && task.state == .running {
        task.cancel()
    }

    DispatchQueue.main.async {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    placesTask = session.dataTask(with: url) { data, response, error in
        var placesArray: [Place] = []
        defer {
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                completion(placesArray)
            }
        }
        guard let data = data,
            let json = try? JSON(data: data, options: .mutableContainers),
            let results = json["results"].arrayObject as? [[String: Any]] else {
                return
        }
        results.forEach {
            let place = Place(dictionary: $0, acceptedTypes: types)
            placesArray.append(place)                

            if let reference = place.photoReference {
                //SECOND WEB REQUEST CALL
                self.fetchPhotoFromReference(reference) { image in
                    place.photo = image
                }
            }
        }
    }
    placesTask?.resume()
}



//SECOND WEB REQUEST
func fetchPhotoFromReference(_ reference: String, completion: @escaping PhotoCompletion) -> Void {
    if let photo = photoCache[reference] {
        completion(photo)
    } else {
        let urlString = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=200&maxheight=200&photoreference=\(reference)&key=\(googleApiKey)"
        guard let url = URL(string: urlString) else {
            completion(nil)
            return
        }

        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        }

        session.downloadTask(with: url) { url, response, error in                
            var downloadedPhoto: UIImage? = nil
            defer {
                DispatchQueue.main.async {
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false
                    completion(downloadedPhoto)
                }
            }
            guard let url = url else {
                return
            }
            guard let imageData = try? Data(contentsOf: url) else {
                return
            }
            downloadedPhoto = UIImage(data: imageData)
            self.photoCache[reference] = downloadedPhoto
            }
            .resume()
    }
}
}

1 个答案:

答案 0 :(得分:0)

尝试删除session.download(with: url)块。为了从url下载数据,您只需要let imageData = try? Data(contentsOf: url)

此外,您没有给let imageData = try? Data(contentsOf: url)时间来执行。您拨打电话,然后立即尝试在downloadedPhoto = UIImage(data: imageData)行中使用结果。