gpt4 book ai didi

json - NSURLSession.dataTaskWithRequest 不工作

转载 作者:行者123 更新时间:2023-11-28 12:52:18 24 4
gpt4 key购买 nike

我正在尝试制作一个通用类,该类将从 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

最佳答案

您忘记了 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
}

关于json - NSURLSession.dataTaskWithRequest 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com