Search code examples
iosswiftnsurlsessionnsurlwatchos

Swift: NSURL Session not working with watchOS


I'am using a NSURL Session to get the HTML code of a specific website. The following code works perfectly fine with iOS (in ViewController.swift) but it always fails in watchOS (in InterfaceController.swift). The code always print the else statement: print("apple watch: error with loading 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)

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()

}

Solution

  • Thank's a lot for your hint 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.