Swift:NSURL Session不能与watchOS一起使用
问题描述:
我使用NSURL会话来获取特定网站的HTML代码。下面的代码对于iOS(在ViewController.swift中)工作得很好,但在watchOS(在InterfaceController.swift中)总是失败。代码总是打印else语句:print(“apple watch:error with loading nsurlsession”)。Swift:NSURL Session不能与watchOS一起使用
有人可以解释我(为什么它失败了)我怎么能改变这个?我很感激每一个回应!
(我使用SWIFT 4.0与iOS 11和watchOS 4.0 - 在模拟器和iPhone上的7配对的Apple腕表系列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()
}
答
感谢的很多关于您的提示Srstka!
经过几个小时的思考,我明白了。我忘了添加“允许任意负载”到WatchKit扩展中的Info.plist。
您的'print'语句被调用,因为'if(response as?HTTPURLResponse)!= nil'测试出现错误。这可能意味着响应是'nil',或者它不是'HTTPURLResponse'。最有可能的情况是它是'nil',其中'error'变量应该填充一个错误来解释错误。这些信息,轻描淡写,将需要弄清楚为什么你的代码失败。请将其添加到您的日志中,并发布结果。 –