2016-03-08 113 views
1

我创建了一个watchOS应用程序,该应用程序从API请求值并将其显示在标签上。 它是在模拟器上可以正常使用,但是当我执行它在我的苹果看它与下面的错误崩溃:由我的代码生成Swift HTTP请求适用于模拟器,但不适用于真实设备

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

的第一个错误。

我写的代码是:

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 
    } 
} 

我也尝试添加的应用程序传输安全旁路此外,如果不需要的话,因为到HTTPS URL的请求,但它不工作。

你能帮我吗?

谢谢

回答

1

尝试使用NSURLSession获取数据...

//declare data task 
var task: NSURLSessionDataTask? 

//setup the session 
let url = NSURL(string:"https://url.here")! 
let conf = NSURLSessionConfiguration.defaultSessionConfiguration() 
let session = NSURLSession(configuration: conf) 

task = session.dataTaskWithURL(url) { (data, res, error) -> Void in 
     if let e = error { 
      print("dataTaskWithURL fail: \(e.debugDescription)") 
      return 
     } 
     if let d = data { 
       //do whatever 
      }) 
     } 
    } 
    task!.resume() 
+0

谢谢,我会尝试在解决几个小时 – Gualty

+0

,谢谢! – Gualty

相关问题