2016-03-08 121 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

相關問題