从斯威夫特函数异步调用返回的数据 [英] Returning data from async call in Swift function
问题描述
我已经创建了我的雨燕项目的实用程序类来处理所有的REST请求和响应。我建立了一个简单的REST API,所以我可以测试我的code。我创建了需要返回一个NSArray但由于API调用是异步I需要从异步调用里面的方法返回一个类的方法。问题是异步返回void。
如果我在节点这样做我会用JS承诺,但我想不通,在斯威夫特的解决方案。
进口基金会类书店{
类FUNC getGenres() - GT; NSArray的{
的println(你好内getGenres)
让urlPath =http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list
的println(urlPath)
让网址:NSURL = NSURL(字符串:urlPath)
让会话= NSURLSession.sharedSession()
VAR resultsArray:NSArray的!
让任务= session.dataTaskWithURL(URL,completionHandler:{数据,回应,误差 - >无效的
的println(任务已完成)
如果(错误){
的println(error.localizedDescription)
}
VAR错误:NSError?
VAR选项:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
VAR jsonResult = NSJSONSerialization.JSONObjectWithData(数据,选项:选项错误:&放大器; ERR)作为NSDictionary的
如果(ERR!=无){
的println(JSON错误\\(ERR!.localizedDescription))
}
//的NSLog(jsonResults%@,jsonResult)
让结果:NSArray的= jsonResult [流派]作为NSArray中
的NSLog(jsonResults%@,结果)
resultsArray =结果
返回resultsArray //错误[anyObject]不是的子类型无效
})
task.resume()
//返回的Hello World!
//我要返回NSArray中...
}
}
您可以通过回调,并调用异步调用内部的回调
是这样的:
类FUNC getGenres(completionHandler:(类型:NSArray中) - GT;()){
...
让任务= session.dataTaskWithURL(URL){
数据,响应,错误
...
resultsArray =结果
completionHandler(类型:resultsArray)
}
...
task.resume()
}
,然后调用此方法:
覆盖FUNC viewDidLoad中(){
Bookshop.getGenres {
在流派
的println(视图控制器:\\(风格))
}
}
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...
}
}
You can pass callback, and call callback inside async call
something like:
class func getGenres(completionHandler: (genres: NSArray) -> ()) {
...
let task = session.dataTaskWithURL(url) {
data, response, error in
...
resultsArray = results
completionHandler(genres: resultsArray)
}
...
task.resume()
}
and then call this method:
override func viewDidLoad() {
Bookshop.getGenres {
genres in
println("View Controller: \(genres)")
}
}
这篇关于从斯威夫特函数异步调用返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!