从类型'(_, _, _) throws -> ()' 到非抛出函数类型'(URLResponse?, Data?, Error?) -> Void 的无效转换

Invalid conversion from throwing function of type '(_, _, _) throws -> ()' to non-throwing function type '(URLResponse?, Data?, Error?) -> Void

我正在尝试按照 Ray Wenderlich 网站上的教程学习使用 Instruments。示例代码写的是 Swift 2 我相信在允许 运行 之前,我必须将代码迁移到最新的 Swift 版本。我已经完成了转换错误的一半,但我对以下代码区域感到困惑:

class Flickr {

  let processingQueue = OperationQueue()

  func searchFlickrForTerm(_ searchTerm: String, completion : @escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){

    let searchURL = flickrSearchURLForSearchTerm(searchTerm)
    let searchRequest = URLRequest(url: searchURL)

    NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
      if error != nil {
        completion(nil,error as! NSError)
        return
      }

      var JSONError : NSError?


        let resultsDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

      if JSONError != nil {
        completion(nil, JSONError)
        return
      }

      switch (resultsDictionary!["stat"] as! String) {
      case "ok":
        print("Results processed OK")
      case "fail":
        let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary!["message"]!])
        completion(results: nil, error: APIError)
        return
      default:
        let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"])
        completion(nil, APIError)
        return
      }

      let photosContainer = resultsDictionary!["photos"] as! NSDictionary
      let photosReceived = photosContainer["photo"] as! [NSDictionary]

      let flickrPhotos : [FlickrPhoto] = photosReceived.map {
        photoDictionary in

        let photoID = photoDictionary["id"] as? String ?? ""
        let title = photoDictionary["title"] as? String ?? ""
        let farm = photoDictionary["farm"] as? Int ?? 0
        let server = photoDictionary["server"] as? String ?? ""
        let secret = photoDictionary["secret"] as? String ?? ""

        let flickrPhoto = FlickrPhoto(photoID: photoID, title: title, farm: farm, server: server, secret: secret)

        return flickrPhoto
      }

      DispatchQueue.main.async(execute: {
        completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil)
      })
    }
  }

  fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL {
    let escapedTerm = searchTerm.addingPercentEscapes(using: String.Encoding.utf8)!
    let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=30&format=json&nojsoncallback=1"
    return URL(string: URLString)!
  }


}

我在以下代码行中收到错误:

NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
      if error != nil {
        completion(nil,error as! NSError)
        return
      }

我有点困惑应该如何使用 do、try、catch 来修改它,所以任何帮助将不胜感激,这样我就可以得到该应用程序 运行 与 Instruments 一起玩。

这里是 link 教程:https://www.raywenderlich.com/97886/instruments-tutorial-with-swift-getting-started

用这个替换你的 Flickr class。

class Flickr {

  let processingQueue = OperationQueue()

  func searchFlickrForTerm(_ searchTerm: String, completion : @escaping (_ results: FlickrSearchResults?, _ error : NSError?) -> Void){

let searchURL = flickrSearchURLForSearchTerm(searchTerm)
let searchRequest = URLRequest(url: searchURL)

NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in
    guard let data = data, error == nil else {
        completion(nil, error as NSError?)
        return
    }

    guard let jsonObject = try? JSONSerialization.jsonObject(with: data,
                                                                    options: JSONSerialization.ReadingOptions(rawValue: 0)),
    let resultsDictionary = jsonObject as? Dictionary<String, Any>
        else
    {
        return
    }


    switch (resultsDictionary["stat"] as! String) {
    case "ok":
        print("Results processed OK")
    case "fail":
        let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary["message"]!])
        completion(nil, APIError)
        return
    default:
        let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Unknown API response"])
        completion(nil, APIError)
        return
    }

    let photosContainer = resultsDictionary["photos"] as! NSDictionary
    let photosReceived = photosContainer["photo"] as! [NSDictionary]

    let flickrPhotos : [FlickrPhoto] = photosReceived.map {
        photoDictionary in

        let photoID = photoDictionary["id"] as? String ?? ""
        let title = photoDictionary["title"] as? String ?? ""
        let farm = photoDictionary["farm"] as? Int ?? 0
        let server = photoDictionary["server"] as? String ?? ""
        let secret = photoDictionary["secret"] as? String ?? ""

        let flickrPhoto = FlickrPhoto(photoID: photoID, title: title, farm: farm, server: server, secret: secret)

        return flickrPhoto
    }

    DispatchQueue.main.async(execute: {
        completion(FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), nil)
    })
}
  }

  fileprivate func flickrSearchURLForSearchTerm(_ searchTerm:String) -> URL {
let escapedTerm = searchTerm.addingPercentEscapes(using: String.Encoding.utf8)!
let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=30&format=json&nojsoncallback=1"
return URL(string: URLString)!
  }


}

抱歉,间距全乱了,但问题是您没有正确处理错误。当您执行 JSONSerialization 时,它可能会抛出异常,因此您必须将其包装在 do catch 块中,或者您可以使用 !如果抛出错误或?如果失败,则 return 为零。