2017-09-24 83 views
0

我使用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() 

} 
+0

您的'print'語句被調用,因爲'if(response as?HTTPURLResponse)!= nil'測試出現錯誤。這可能意味着響應是'nil',或者它不是'HTTPURLResponse'。最有可能的情況是它是'nil',其中'error'變量應該填充一個錯誤來解釋錯誤。這些信息,輕描淡寫,將需要弄清楚爲什麼你的代碼失敗。請將其添加到您的日誌中,併發布結果。 –

回答

0

感謝的很多關於您的提示Srstka!

經過幾個小時的思考,我明白了。我忘了添加「允許任意負載」到WatchKit擴展中的Info.plist。

相關問題