从 Swift 函数中的异步调用返回数据 [英] Returning data from async call in Swift function
问题描述
我在我的 Swift 项目中创建了一个实用程序类,用于处理所有 REST 请求和响应.我已经构建了一个简单的 REST API,所以我可以测试我的代码.我创建了一个需要返回 NSArray 的类方法,但是因为 API 调用是异步的,所以我需要从异步调用中的方法返回.问题是异步返回无效.如果我在 Node 中执行此操作,我会使用 JS 承诺,但我无法找出适用于 Swift 的解决方案.
I have created a utility class in my Swift project that handles all the REST requests and responses. I have built a simple REST API so I can test my code. I have created a class method that needs to return an NSArray but because the API call is async I need to return from the method inside the async call. The problem is the async returns void. If I were doing this in Node I would use JS promises but I can't figure out a solution that works in Swift.
import Foundation
class Bookshop {
class func getGenres() -> NSArray {
println("Hello inside getGenres")
let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
println(urlPath)
let url: NSURL = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
var resultsArray:NSArray!
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
println(error.localizedDescription)
}
var err: NSError?
var options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error (err!.localizedDescription)")
}
//NSLog("jsonResults %@", jsonResult)
let results: NSArray = jsonResult["genres"] as NSArray
NSLog("jsonResults %@", results)
resultsArray = results
return resultsArray // error [anyObject] is not a subType of 'Void'
})
task.resume()
//return "Hello World!"
// I want to return the NSArray...
}
}
推荐答案
可以通过callback,在async call里面调用callback
You can pass callback, and call callback inside async call
类似:
class func getGenres(completionHandler: (genres: NSArray) -> ()) {
...
let task = session.dataTaskWithURL(url) {
data, response, error in
...
resultsArray = results
completionHandler(genres: resultsArray)
}
...
task.resume()
}
然后调用这个方法:
override func viewDidLoad() {
Bookshop.getGenres {
genres in
println("View Controller: (genres)")
}
}
这篇关于从 Swift 函数中的异步调用返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!