【问题标题】:How to use NSURLSession to determine if a redirected link is broken?如何使用 NSURLSession 确定重定向链接是否损坏?
【发布时间】:2015-12-30 15:38:44
【问题描述】:

我正在尝试使用 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 的地方,我可以通过在此处添加错误块来获取网址吗?

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

                                    })

【问题讨论】:

标签: ios swift nsurlsession


【解决方案1】:

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

来源:Apple Documentation

【讨论】:

  • 谢谢!但是我如何在loadDataTask.currentRequest 访问该属性,它将是在它自己的初始值中使用的变量?
  • @PSUSabes 将loadDataTask 设为可选变量并使用nil 对其进行初始化。然后你可以在完成闭包中访问它。
  • loadDataTask.currentRequest 返回初始 url,而不是重定向结束的“源”url
  • 也许是因为重定向 URL 失败?!您现在可以添加委托方法URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) 以调查此问题。代理将在执行重定向之前 被调用。如果事实证明 currentRequest 仅在 成功 时才设置,我会认为它是 NSULRSession 中的错误。
  • 我认为问题在于我传入了一个可选的,它是几个层次的展开,所以我没有注意到。 currentRequest.url 现在告诉我重定向的 URL...感谢您的帮助!
猜你喜欢
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
相关资源
最近更新 更多