Search code examples
jsonios-simulatorhttprequestwatchos-2

Swift HTTP request works on the simulator but not in a real device


i created a watchOS app that request a value from an API and show it on a label. It is working perfectly in the simulator but when I execute it on my Apple Watch it crashes with the following error:

[ERROR] There is an unspecified error with the connection
fatal error: unexpectedly found nil while unwrapping an Optional value

The first error is generated by my code.

The code I wrote is:

func price_request() -> NSData? {

    guard let url = NSURL(string: "https://api.xxxxx.com/xxx.php") else {
        return nil
    }

    guard let data = NSData(contentsOfURL: url) else {
        print("[ERROR] There is an unspecified error with the connection")
        return nil
    }

    print("[CONNECTION] OK, data correctly downloaded")
    return data
}

func json_parseData(data: NSData) -> NSDictionary? {
    do {
        let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<String, AnyObject>
        print("[JSON] OK!")

        return (json as? NSDictionary)

    } catch _ {
        print("[ERROR] An error has happened with parsing of json data")
        return nil
    }
}

I tried also to add the App Transport Security bypass also if it is not needed because of a request to an HTTPS URL but it does not works.

Can you please help me?

Thank you


Solution

  • Try using NSURLSession to get data...

    //declare data task
    var task: URLSessionDataTask?
    
    //setup the session
    let url = URL(string:"https://url.here")!
    let session = URLSession(configuration: URLSessionConfiguration.default)
    
     task = session.dataTask(with: url){ (data, res, error) -> Void in
            if let e = error {
                print("dataTaskWithURL fail: \(e.localizedDescription)")
                return
            }
            if let d = data {
               //do something
            }
        }
        task!.resume()