2014-12-05 159 views
-2

我是iOS編程新手,我正在嘗試使用Swift新語言。 我有一個問題/我不知道如何解析與iOS的Swift的JSON使用。我已經使用JSON在Android的,所以我知道,JSON和鏈接是正確的,但是當我嘗試下面的代碼(在教程中看到的)的應用程序似乎崩潰,並強調這一行:JSON解析Swift錯誤

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary 

的控制檯給我回這個錯誤:

The operation couldn’t be completed. (NSURLErrorDomain error -1005.) fatal error: unexpectedly found nil while unwrapping an Optional value 

這裏是按鈕的操作的全部代碼:

let urlAsString = "http://xxxxxxxxxx.altervista.org/App/_DD_/downloadutenti.php?email="+campoEmail.text+"&password="+campoPassword.text 
    let url = NSURL(string: urlAsString)! 
    let urlSession = NSURLSession.sharedSession() 

    println(url) 
    println(urlSession) 
    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in 
     if (error != nil) { 
      println(error.localizedDescription) 
     } 
     var err: NSError? 

     if(data != nil){ 
      var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary 


     if (err != nil) { 
      println("JSON Error \(err!.localizedDescription)") 
     } 

      var jsonEmail = "" 
      if var jsonEmail: String! = jsonResult["email"] as? NSString{ 

      } 
      else{ 
       println("PROBLEM 1") 
      } 

      var jsonPassword = "" 
      if var jsonPassword: String! = jsonResult["pass"] as? NSString{ 

      } 
      else{ 
       println("PROBLEM 2") 
      } 

     dispatch_async(dispatch_get_main_queue(), { 
      self.scritta2.text = "Email: " + jsonEmail + " - Password: " + jsonPassword 
     }) 
    } 
    }) 
    jsonQuery.resume() 

NB 我使用xcode6模擬器,我知道肯定的「變量」campoEmail.text和campoPassword.text採取了一個好方法。

JSON它應該給予回覆:

[{"id":"1","email":"[email protected]","password":"pass","permessi":"1","stato":"Italia","citta":"Palermo","via":"Via Lincoln, 29","cap":"90100","telefono":"091xxxxxx"}] 

編輯@ neo的幫助: 我編輯喜歡這個按鈕的所有動作,但代碼進入到數據的空檢查..

let curURL: NSURL = NSURL(string: "http://fantacharleston.altervista.org/App/_DD_/[email protected]&password=pass")! 
     let curRequest: NSURLRequest = NSURLRequest(URL: curURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60) 
     NSURLConnection.sendAsynchronousRequest(curRequest, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData?, error: NSError!) -> Void in 

      if (data != nil) { 
       if let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray? { 

        let jsonObject: NSDictionary? = jsonArray.objectAtIndex(0) as? NSDictionary 
        if (jsonObject != nil) { 
         NSLog("object: %@", jsonObject!) 
         let email: NSString? = jsonObject?.objectForKey("email") as? NSString 
         let password: NSString? = jsonObject?.objectForKey("password") as? NSString 

         if (email != nil && password != nil) { 
          dispatch_async(dispatch_get_main_queue(), {() -> Void in 
           self.scritta2.text = "Email: " + email! + " - Password: " + password! 
          }) 
         } 


        } 

       } 
      } 
      else{ 
       println("null") 
      } 
     } 
+0

你能否爲我提供JSON的一部分解析? – 2014-12-05 21:12:06

+1

當然,您應該收到您收到的全部錯誤消息。 – 2014-12-05 21:41:21

+0

我添加了它應該回饋的內容。 @Neo – 2014-12-05 21:44:53

回答

2

是的我想我知道你的問題在哪裏......你正在試圖把一個JSONArray放到一個NSDictionary中...那不能去...它就像試圖把它放到Java中的JSONObject中。

只需與NSArray交換NSDictionary,並確保獲得像array [0] [「key」]這樣的屬性,而不是像array [「key」],因爲您正在處理數組,而不是使用字典。 (其如ArrayList,和HashMap在Java中)

試試這個,請...

if let jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray? { 

let jsonEmail: NSString? = jsonResult.objectAtIndex(0).objectForKey("email") 

} 

編輯與代碼,你需要

這是......我寫了一點就像我會用Android的Java編寫的那樣...我想你會變成eas ily得到它......你評論的問題可能是你的JSON沒有「pass」標籤......它的「密碼」...

let curURL: NSURL = NSURL(string: "http://fantacharleston.altervista.org/App/_DD_/[email protected]&password=pass")! 
     let curRequest: NSURLRequest = NSURLRequest(URL: curURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60) 
     NSURLConnection.sendAsynchronousRequest(curRequest, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData?, error: NSError!) -> Void in 

      if (data != nil) { 
       if let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray? { 

        let jsonObject: NSDictionary? = jsonArray.objectAtIndex(0) as? NSDictionary 
        if (jsonObject != nil) { 
         NSLog("object: %@", jsonObject!) 
         let email: NSString? = jsonObject?.objectForKey("email") as? NSString 
         let password: NSString? = jsonObject?.objectForKey("password") as? NSString 

         if (email != nil && password != nil) { 
          dispatch_async(dispatch_get_main_queue(), {() -> Void in 
           self.scritta2.text = "Email: " + email + " - Password: " + password 
          }) 
         } 


        } 

       } 
      } 
     } 
+0

謝謝@Neo! 那麼這是一個veeeeeery很好的幫助,因爲該應用程序現在沒有崩潰,但它返回空值。 返回JSON的鏈接是: http://fantacharleston.altervista.org/App/_DD_/[email protected]&password=pass 你能幫助我嗎? 「array [0] [」key「]」/「array [」key「]」有問題嗎? P.S. 調試告訴我:「JSON錯誤無法完成操作(可可錯誤3840.)」 – 2014-12-05 22:43:05

+0

好吧,給我十分鐘,我會「連線」你的東西在一起,這將解決你的問題... – 2014-12-05 22:56:59

+0

好吧非常感謝你 – 2014-12-05 23:01:58