Swift 3使用AFNetworking

Not*_*Bot 3 ios afnetworking swift swift3

我正在使用AFNetworking和Swift 3.0,我被困在一个代码上.

func getJSON()
    {


        let manager = AFHTTPSessionManager()
        manager.get(
            url,
            parameters: nil,
            success:
            {
                (operation: URLSessionTask!, responseObject: Any?) in

                 print("JSON: " + responseObject!.description)
                 self.matchesArray = responseObject!.object(forKey: "matches")! as? NSMutableArray
                 self.tollBothPlazaTableView.reloadData()
            },

            failure:
            {
                (operation: URLSessionTask!, error: NSError)  in
                print("Error: " + error.localizedDescription)
            }
        )
    }
Run Code Online (Sandbox Code Playgroud)

它显示failure块上的错误.

无法将类型'(URLSessionTask!,NSError) - >()'的值转换为预期的参数类型'((URLSessionDataTask?,Error) - > Void)?'`

有人可以解释我的代码中的错误.还有使用闭包的正确方法吗?(我是swift的新手).

Nir*_*v D 10

错误显然是说使用Error而不是NSError,在Swift 3中你需要使用Error而不是NSError.所以改变你的代码如下.

func getJSON() {

    let manager = AFHTTPSessionManager()
    manager.get(
        url,
        parameters: nil,
        success:
        {
            (operation, responseObject) in

             if let dic = responseObject as? [String: Any], let matches = dic["matches"] as? [[String: Any]] {
                  print(matches)
             }
             DispatchQueue.main.async {                          
                 self.tollBothPlazaTableView.reloadData()
             }
        },
        failure:
        {
            (operation, error) in
             print("Error: " + error.localizedDescription)
    })
}
Run Code Online (Sandbox Code Playgroud)

注意:当你在后台线程时,总是在主线程上执行UI更改,所以tableView像我一样重新加载你的主线程,也使用Swift native ArrayDictionary不是NSArrayNSDictionary.