【问题标题】:Swift: NSURL Session not working with watchOSSwift:NSURL 会话不适用于 watchOS
【发布时间】:2018-03-05 15:55:57
【问题描述】:

我正在使用 NSURL 会话来获取特定网站的 HTML 代码。以下代码在 iOS(在 ViewController.swift 中)中运行良好,但在 watchOS(在 InterfaceController.swift 中)总是失败。代码总是打印 else 语句: print("apple watch: error with loading nsurlsession").

谁能解释一下(为什么会失败以及)我该如何改变?我很感激每一个回复!

(我在 iOS 11 和 watchOS 4.0 上使用 swift 4.0 - 在模拟器和 iPhone 7 上与配对的 Apple Watch 系列 2 进行了测试)

代码:

func authorizeBase() {
    let loginString = NSString(format: "%@:%@", username, password)
    let loginData: NSData = loginString.data(using: String.Encoding.utf8.rawValue)! as NSData
    let base64LoginString = loginData.base64EncodedString(options: [])

    let url: NSURL = NSURL(string: urlPath)!

    let request: NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"

    let config = URLSessionConfiguration.default

    config.requestCachePolicy = .reloadIgnoringLocalCacheData //deactivate cache
    config.urlCache = nil

    let authString = "Basic \(base64LoginString)"
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    session.dataTask(with: url as URL) {
        ( data, response, error) in
        if (response as? HTTPURLResponse) != nil {
            _ = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            let contents = String(data: data!, encoding: .ascii)

            print("apple watch: Content:", contents!)
            self.parseHTMLOverview(content: contents!)

            self.updateTable() //!!!

        }
        else {
            print("apple watch: error with loading nsurlsession")
        }

    }.resume()

}

【问题讨论】:

  • 您的print 语句被调用,因为if (response as? HTTPURLResponse) != nil 测试出现错误。这可能意味着响应是nil,或者不是HTTPURLResponse。最可能的情况是nil,其中error 变量应该填充一个错误,解释出了什么问题。简单地说,需要这些信息来找出您的代码失败的原因。请将其添加到您的日志中,然后发布结果。

标签: ios swift nsurlsession nsurl watchos


【解决方案1】:

非常感谢您的提示 Srstka!

经过几个小时的思考,我想通了。我只是忘记在 WatchKit 扩展的 Info.plist 中添加“允许任意加载”。

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2017-07-30
    • 2011-11-16
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2017-03-01
    相关资源
    最近更新 更多