我正在尝试使用NSURLSession
来确定传入一系列网址后链接是否已损坏。以下代码的问题是行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
我可以通过在此处添加错误块来获取网址吗?
MySession.getDataFromServerWithSuccess(urlAsString, noRedirect: false, success:
{ (response: String!) -> Void in
})