gpt4 book ai didi

ios - 如何使用 NSURLSession 确定重定向链接是否已损坏?

转载 作者:可可西里 更新时间:2023-11-01 02:18:12 24 4
gpt4 key购买 nike

我正在尝试使用 NSURLSession 来确定在传入一组 URL 后链接是否断开。以下代码的问题在于 else { print("no data back from getDataFromSErverWithSuccess and this is the problem:\(myURL)")} 行中的 myURL 返回 nil。如何获取损坏的 URL 的值?

class MySession: NSObject, NSURLSessionDelegate {


func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {


if let checkedURL = request.URL {

if UIApplication.sharedApplication().canOpenURL(checkedURL) {
print("\(checkedURL) works")

} else {
print("\(checkedURL) IS BROKE!")
}
}


}

// fetch data from URL with NSURLSession
class func getDataFromServerWithSuccess(myURL: String, noRedirect: Bool, success: (response: String!) -> Void) {
var myDelegate: MySession? = nil
if noRedirect {
myDelegate = MySession()
}
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: myDelegate, delegateQueue: nil)
let loadDataTask = session.dataTaskWithURL(NSURL(string: myURL)!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

if let checkedData = data {

success(response: NSString(data: checkedData, encoding: NSASCIIStringEncoding) as! String)
} else { print("no data back from getDataFromSErverWithSuccess and this is the problem: \(myURL)")}
}
loadDataTask.resume()
}

编辑:这是我调用 getDataFromServerWithSuccess 的地方 我可以通过在此处添加错误 block 来获取 url 吗?

MySession.getDataFromServerWithSuccess(urlAsString, noRedirect: false, success:
{ (response: String!) -> Void in

})

最佳答案

您可以从 session 任务中获取带有属性 currentRequest 的重定向请求。

来源:Apple Documentation

关于ios - 如何使用 NSURLSession 确定重定向链接是否已损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34532498/

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