1
自分のAPIからデータを取得しようとしています。 「それはにISNので データを読み取ることができませんでした。私は私のiOSアプリを通じてAPIにアクセスしようとしました。このiOSでJSONシリアライゼーションを実行すると失敗しましたが、ブラウザからアクセスするとAPIが正常に動作します。
{"id":"52","username":"aasad23","fullname":"aasad laksana","email":"[email protected]","avatar":"/Applications/XAMPP/xamppfiles/htdocs/Twitter/Avatar/52/avatar.jpg"}
しかし、のように、それは、JSONのシリアル化を行っている間、それはエラーを与えるエラーが発生します正しい形式のt
正しい形式はどういう意味ですか?
私はcatch
エラーが活性化し、そのエラーメッセージを与えているThatsなぜこの行のコードのエラー
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
ことを確認しています。ここ
は、このタスクの完全なコード
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()
}