2017-12-18 138 views
1

我試圖從我自己的API中檢索數據,如果我嘗試使用Chrome瀏覽器連接到我的API,它會返回JSON數據這樣在iOS中執行JSON序列化時失敗,但通過瀏覽器訪問API時確定無誤

{"id":"52","username":"aasad23","fullname":"aasad laksana","email":"[email protected]","avatar":"/Applications/XAMPP/xamppfiles/htdocs/Twitter/Avatar/52/avatar.jpg"}

,但是,當我試圖通過我的iOS應用程序來訪問API,它提供了一個錯誤,而這樣做JSON序列化,它給出一個錯誤: 數據無法讀取,因爲它不是」 t格式正確

這是什麼意思是正確的格式?

我已籤,在這條線

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

這就是爲什麼catch錯誤被激活,並給予該錯誤消息的代碼錯誤。

這裏是這個任務的完整代碼

URLSession.shared.dataTask(with: request) { data, response, error in 




      DispatchQueue.main.async(execute: { 

       if error == nil { 



        do { 

         // json containes $returnArray from php 
         let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

         // declare new parseJSON to store json 
         guard let parsedJSON = json else { 
          print("Error while parsing") 
          return 
         } 


         print(parsedJSON) 

         // get id from $returnArray["id"] in PHP - parseJSON["id"] 
         let id = parsedJSON["id"] 

         // successfully uploaded 
         if id != nil { 

          // save user information yang berasal dari server 
          UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON") 



         } else { 

          // get main queue to communicate back to user 
          DispatchQueue.main.async(execute: { 
           let message = parsedJSON["message"] as! String 
           self.showAlert(alertTitle: "opppps", alertMessage: message, actionTitle: "OK") 
          }) 

         } 



         // JSON serialization error 
        } catch { 

         // get main queue to communicate back to user 
         DispatchQueue.main.async(execute: { 
          let message = error.localizedDescription 
          self.showAlert(alertTitle: "Sorry", alertMessage: message, actionTitle: "OK") 
         }) 

        } 

        // error when connecting to server 
       } else { 

        // get main queue to communicate back to user 
        DispatchQueue.main.async(execute: { 
         let message = error!.localizedDescription 
         self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK") 
        }) 

       } 


      }) 

      }.resume() 


    } 

回答

1

嘗試

let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject] 

而不是

try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 
相關問題