[英]Swift: NSURL Session not working with watchOS
I'am using a NSURL Session to get the HTML code of a specific website. 我正在使用NSURL会话来获取特定网站的HTML代码。 The following code works perfectly fine with iOS (in ViewController.swift) but it always fails in watchOS (in InterfaceController.swift).
以下代码在iOS上运行正常(在ViewController.swift中),但在watchOS(在InterfaceController.swift中)始终失败。 The code always print the else statement: print("apple watch: error with loading nsurlsession").
代码始终打印else语句:print(“ apple watch:加载nsurlsession时出错”)。
Could anybody explain me (why it fails and) how I could change this? 谁能解释给我(为什么会失败,以及)我该如何改变呢? I'm grateful for every response!
感谢您的每一个回应!
(I'm using swift 4.0 with iOS 11 and watchOS 4.0 - tested in simulator and on iPhone 7 with paired Apple Watch series 2) (我在iOS 11和watchOS 4.0上使用了swift 4.0-已在模拟器中以及与配对的Apple Watch系列2在iPhone 7上进行测试)
Code: 码:
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()
}
Thank's a lot for your hint Srstka! 非常感谢您的提示Srstka!
After hours of thinking I figured it out. 经过数小时的思考,我终于明白了。 I just forgot to add "Allow Arbitrary Loads" to the Info.plist in the WatchKit Extension.
我只是忘记在WatchKit扩展的Info.plist中添加“允许任意加载”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.