URLSessionでJSON形式のデータを受信しようとしたのですが,
The data couldn’t be read because it isn’t in the correct format.
というエラーが出てしまい修正できないでいます。
データのフォーマットの形式が違うため読み込みすることができないらしいのですが、修正点が見つけられないでいます。
どなたかご教授お願いいたします。
ATSはinfo.plistから無効にしています。
Swift
1import UIKit 2import Foundation 3 4class ViewController: UIViewController { 5 6 struct FAQ: Codable { 7 var path: [String] 8 var type: [String] 9 var question: [String] 10 var choices: [String] 11 } 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 16 let urlSessionGetClient = URLSessionGetClient() 17 let queryItems = [URLQueryItem(name: "choice", value: "/")] 18 urlSessionGetClient.get(url: "http://172.17.240.25:8080/ta2/bot/select", queryItems: queryItems) 19 20 } 21 22 override func didReceiveMemoryWarning() { 23 super.didReceiveMemoryWarning() 24 25 } 26 27 class URLSessionGetClient { 28 29 func get(url urlString: String, queryItems: [URLQueryItem]? = nil) { 30 var compnents = URLComponents(string: urlString) 31 compnents?.queryItems = queryItems 32 let url = compnents?.url 33 let semaphore = DispatchSemaphore(value: 0) 34 let task = URLSession.shared.dataTask(with: url!) { 35 data, response, error in 36 if let jsonString = data { 37 let decoder: JSONDecoder = JSONDecoder() 38 do { 39 let faq: FAQ = try decoder.decode(FAQ.self, from: jsonString) 40 print(faq) 41 } catch { 42 print("error:", error.localizedDescription) 43 } 44 45 } else { 46 print(error ?? "Error") 47 } 48 semaphore.signal() 49 } 50 task.resume() 51 _ = semaphore.wait(timeout: DispatchTime.distantFuture) 52 } 53 } 54}
修正
JSONデータを消去しました。
「ヘディングのテキスト」ってなんですか?
質問に書いてあるJSONは、実際に受け取ったJSONなのでしょうか?それとも受信が出来ないという質問なのでしょうか?
ヘディングのテキストは修正時に誤って入力してしまったものなので関係ありませんでした。
また、このコードではjsonを受信するだけの予定でしたので、記述されたJSONは関係ありませんでした。
受信がうまくいかないということで質問しました。
エラーはどこで出ているのでしょうか?
ビルドは成功するのですが、デバックエリアにて
error:The data couldn’t be read because it isn’t in the correct format.
と表示されています
if let jsonString = data {
の下に、
jsonString.enumerated().forEach {print(String(format: "%02x", $0.1), terminator: $0.0 % 16 == 15 ? "\n" : " ")}
を追加して、出力を教えてください。
あと、エラーがどのタイミングで出ているか分かりますか?
追加して出力した結果
7b 22 70 61 74 68 22 3a 22 2f 22 2c 22 74 79 70
65 22 3a 22 73 65 6c 65 63 74 22 2c 22 71 75 65
73 74 69 6f 6e 22 3a 22 e3 81 94 e8 b3 aa e5 95
8f e3 81 ae e8 a8 80 e8 aa 9e e3 81 af e4 bd 95
e3 81 a7 e3 81 97 e3 82 87 e3 81 86 e3 81 8b 3f
22 2c 22 63 68 6f 69 63 65 73 22 3a 5b 22 4a 61
76 61 22 2c 22 4a 53 50 22 2c 22 48 54 4d 4c 22
2c 22 43 22 5d 7d error: The data couldn’t be read because it isn’t in the correct format.
と出ました。
また、エラーのタイミングはシミュレーターが立ち上がり白い画面が出た後しばらくしてから出力されました。
受信は正しく出来ているようですが、
>>受信がうまくいかないということで質問しました
というのはどういうことでしょうか?
というか、エラーって
print("error:", error.localizedDescription)
ここで出ているんじゃないんですか?
回答2件
あなたの回答
tips
プレビュー