0

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

}
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
Adrian
  • 352
  • 1
  • 11
  • Your `print` statement is being called because the `if (response as? HTTPURLResponse) != nil` test came up false. This can mean that either the response was `nil`, or that it wasn't an `HTTPURLResponse`. The most likely case is that it was `nil`, in which the `error` variable should be populated with an error explaining what went wrong. This information, to put it lightly, will be needed to figure out why your code is failing. Please add it to your log, and post the results. – Charles Srstka Sep 24 '17 at 17:29

1 Answers1

1

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.

Adrian
  • 352
  • 1
  • 11