gpt4 book ai didi

ios - 应用程序突然崩溃加载网址

转载 作者:行者123 更新时间:2023-11-28 15:55:08 25 4
gpt4 key购买 nike

我有以下功能来加载数据。直到几天前,该功能都运行良好。该应用程序在尝试加载任何 url 时崩溃,请参阅下面的代码和屏幕截图。一年只有几天编写 ios/swift 代码,很难找出问题所在......

enter image description here

class func loadDataFromURL(_ url: URL, completion:@escaping (_ data: Data?, _ error: NSError?) -> Void) {
let session = URLSession.shared

// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
if let responseError = error {
completion(nil, responseError)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(nil, statusError)
} else {
completion(data, nil)
}
}
} as! (Data?, URLResponse?, Error?) -> Void)

loadDataTask.resume()
}

最佳答案

在 Xcode 8.2 上使用最新的 Swift 3.0 语法使用下面的代码:-

func loadDataFromURL(_ url: URL, completion:@escaping (_ data: Data?, _ error: NSError?) -> Void) {
let session = URLSession.shared

// Use NSURLSession to get data from an NSURL

let loadDataTask = session.dataTask(with: url) { (data, response, error) in
if let responseError = error {
completion(nil, responseError as NSError?)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain:"com.xyz", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(nil, statusError)
} else {
completion(data, nil)
}
}
}
loadDataTask.resume()

}

关于ios - 应用程序突然崩溃加载网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892802/

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