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

时间:2015-12-30 15:38:45

标签: ios swift nsurlsession

我正在尝试使用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

                                    })

1 个答案:

答案 0 :(得分:1)

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

来源:Apple Documentation