gpt4 book ai didi

ios - NSURLSession dataTaskWithRequest Swift

转载 作者:行者123 更新时间:2023-11-28 09:19:22 25 4
gpt4 key购买 nike

我有以下代码:

var resultData:NSData?

task = session!.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in

if ((error) != nil) {
println("Error")
return
}
resultData = data
}

task!.resume()

但是,执行后结果数据为nil。如何获取请求返回的数据?

最佳答案

检查你的数据是否为nil然后就可以使用了

这是一个 Swift 3 示例:

let url = NSURL(string: "https://itunes.apple.com/search?term=jack+johnson&limit=2")!
let request = NSMutableURLRequest(url: url as URL)
let session = URLSession.shared

let task = session.dataTask(with: request as URLRequest) { data, response, error in
if error != nil {
print("error: \(error!.localizedDescription): \(String(describing: error))")
}
else if data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print("Received data:\n\(str)")
}
else {
print("unable to convert data to text")
}
}

}
task.resume()

关于ios - NSURLSession dataTaskWithRequest Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019133/

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