Ios Swift:NSURL会话不与watchOS一起工作

Ios Swift:NSURL会话不与watchOS一起工作,ios,swift,nsurlsession,nsurl,watchos,Ios,Swift,Nsurlsession,Nsurl,Watchos,我正在使用NSURL会话获取特定网站的HTML代码。以下代码在iOS(在ViewController.swift中)中运行得非常好,但在watchOS(在InterfaceController.swift中)中总是失败。代码总是打印else语句:print(“apple watch:加载nsurlsession时出错”) 有人能解释我(为什么失败)以及我如何能改变这一点吗?我很感谢每一个回复 (我在iOS 11和watchOS 4.0上使用swift 4.0——在模拟器上测试,在iPhone7上

我正在使用NSURL会话获取特定网站的HTML代码。以下代码在iOS(在ViewController.swift中)中运行得非常好,但在watchOS(在InterfaceController.swift中)中总是失败。代码总是打印else语句:print(“apple watch:加载nsurlsession时出错”)

有人能解释我(为什么失败)以及我如何能改变这一点吗?我很感谢每一个回复

(我在iOS 11和watchOS 4.0上使用swift 4.0——在模拟器上测试,在iPhone7上与苹果手表系列2配对)

代码:


非常感谢您的提示,Srstka


经过几个小时的思考,我终于明白了。我忘了在WatchKit扩展名的Info.plist中添加“Allow Arbitral Loads”(允许任意加载)。

正在调用您的
print
语句,因为
if(响应为?HTTPURLResponse)!=无
测试结果为假。这可能意味着响应是
nil
,或者不是
httpurresponse
。最有可能的情况是
nil
,其中
error
变量应填充一个错误,以解释出错原因。简单地说,需要这些信息来找出代码失败的原因。请将其添加到日志中,并发布结果。
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()

}