我有一个使用 SwiftyJSON 从 Web 服务中获取信息的函数。当我使用我的 DataManager 类调用该服务时,我能够成功地填充我的数组,当我将它打印出来时,它给了我想要的东西。但是,我无法从我的函数返回填充的数组,因为我认为它在函数结束时超出了范围。谁能告诉我如何让我的函数返回填充的数组而不超出范围?如果我做错了什么,任何帮助将不胜感激。
func getEarthquakeInfo()->NSArray {
var info = [AppModel]()
DataManager.getEarthquakeDataFromFileWithSuccess {
(data) -> Void in
let json = JSON(data: data)
if let JsonArray = json.array {
for appDict in JsonArray {
var ids: String? = appDict["id"].stringValue
var title: String? = appDict["title"].stringValue
var time: String? = appDict["time"].stringValue
var information = AppModel(idEarth: ids, title: title, time: time)
info.append(information)
}
}
println("\(info)") // will print the results that I need
}
return info // This is an empty array
}
这是我打印应用程序时得到的示例:ID:146052,TITLE:M 1.7 Explosion - 0km E of Granite Falls,华盛顿,时间:2015-04-13 21:29:40 UTC,DataManager4.swift 文件:
let earthquakeURL = "http://www.kuakes.com/json/"
class DataManager {
class func getEarthquakeDataFromFileWithSuccess(success: ((websiteData: NSData) -> Void)) {
//1
loadDataFromURL(NSURL(string: earthquakeURL)!, completion:{(data, error) -> Void in
//2
if let urlData = data {
//3
success(websiteData: urlData)
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.kuakes", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
}