我正在尝试创建一个通用类,它将从URL读取JSON数据,并使用从JSON数据创建的NSDictionary执行回调。 我已经创建了一个静态类来执行该功能,但似乎它在dataTaskWithRequest之后不起作用。
[我的代码]
import Foundation
class LoadJsonFromNetwork {
static func LoadJsonFromNetwork(url:NSURL, completion:((NSDictionary) -> ())) {
print("Creating request")
let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
print("Creating session")
let session = NSURLSession.sharedSession()
print("Send request")
session.dataTaskWithRequest(urlRequest) {
(data: NSData?, response: NSURLResponse?, error: NSError?) in
print("Checking error and nil data")
if (error == nil && data != nil) {
print("Request json dictionary from nsdata")
if let result = self.NSDataToJson(data!) {
print("Dispatching to main queue")
dispatch_async(dispatch_get_main_queue()) {
print("Calling callback")
completion(result)
}
}
} else {
print(error!.description)
}
}
}
private static func NSDataToJson(data:NSData) -> NSDictionary? {
do {
print("Serializing JSON")
let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print("Cretaing NSDictionary")
let result = json as? NSDictionary
print("Returning result")
return result
} catch {
return nil
}
}
}
[我在控制台中的结果]
Creating request
Creating session
Send request
答案 0 :(得分:2)
你忘记了resume()
任务。请找到以下编辑过的代码!
static func LoadJsonFromNetwork(url:NSURL, completion:((NSDictionary) -> ())) {
print("Creating request")
let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
print("Creating session")
let session = NSURLSession.sharedSession()
print("Send request")
let task = session.dataTaskWithRequest(urlRequest) {
(data: NSData?, response: NSURLResponse?, error: NSError?) in
print("Checking error and nil data")
if (error == nil && data != nil) {
print("Request json dictionary from nsdata")
if let result = self.NSDataToJson(data!) {
print("Dispatching to main queue")
dispatch_async(dispatch_get_main_queue()) {
print("Calling callback")
completion(result)
}
}
} else {
print(error!.description)
}
}
task.resume() //you need to call this
}