【问题标题】:Include a return handler in async call in Swift在 Swift 的异步调用中包含返回处理程序
【发布时间】:2016-04-05 02:37:07
【问题描述】:

我正在尝试异步调用,但我有点迷茫。 viewDidLoad 中的 print(json) 输出一个空字典,但函数中的字典打印正确。这不足为奇。它在异步完成之前打印。我不知道如何解决它;我尝试将返回值放在完成处理程序中,但出现Unexpected non-void return value in void function 的错误。我尝试更改完成处理程序以期望返回值,但这不是正确的方法,或者我做错了。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let json = getJson("https://maps.googleapis.com/maps/api/geocode/json?address=WashingtonDC&sensor=false")
        print(json)
    }

    func getJson(url: String) -> AnyObject {
        var json:AnyObject = [:]
        let urlPath = NSURL(string: url)
        let urlRequest = NSURLRequest(URL: urlPath!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
        let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
            (data, response, error) in
            if error != nil {
                print("Error")
            } else {
                do {
                    json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                    print(json)
                } catch {
                    print("json error")
                }

            }
        })
        task.resume()
        return json
    }
}

【问题讨论】:

  • 旁注:我觉得我并没有真正正确地构造 json 变量的设置,所以那里的任何反馈也很有帮助!

标签: ios swift


【解决方案1】:

您需要有一个基于完成处理程序的异步 API 接口。

func getJson(url: String, completion : (success: Bool, json: AnyObject? ) ->Void ) -> Void {
        var json:AnyObject = [:]
        let urlPath = NSURL(string: url)
        let urlRequest = NSURLRequest(URL: urlPath!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
        let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
            (data, response, error) in
            if error != nil {
                print("Error")
            } else {
                do {
                    json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                    print(json)
//Call the completion handler here:
completion(success : true, json :json )
                  } catch {
                    print("json error")
completion(success : false, json :nil )

                }

            }
        })
        task.resume()
    }
}

现在你调用这个API如下-

 override func viewDidLoad() {
        super.viewDidLoad()
       getJson("https://maps.googleapis.com/maps/api/geocode/json?address=WashingtonDC&sensor=false") { (success, json) -> Void in 
        if success {
          if let json = json {
            print(json)
         }
        }
     }
  }

【讨论】:

  • 我尝试自己编辑,但被拒绝:在您的第一行中,完成处理程序说“结果”,但后来您使用“成功”。这是故意的还是错误的?在其他新闻中,您的代码运行良好,但我无法理解它。我查找了完成处理程序,但比以前更加困惑(仅语法就让我很困惑)。您(或任何人)可以提供的任何澄清都会有很大帮助!
  • 另外:completion(success : false, son :nil ) 应该是 json: nil。编辑太小,我无法修复错字。
  • @thumbtackthief 感谢您的指点,我已编辑。当我自发地输入答案时,它们都是拼写错误。希望现在一切都好。
猜你喜欢
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
相关资源
最近更新 更多