LoginSignup
2
1

【swift:】'async' call in a function that does not support concurrency エラー

Last updated at Posted at 2024-01-07

問題

以下のコードで 'async' call in a function that does not support concurrency というエラーが出ました。

do {
	// ここでエラー発生
	let (data , _) = try await URLSession.shared.data(from: req_url)
	let decoder = JSONDecoder()
	let json = try decoder.decode(ResultJson.self, from: data)
	
	print(json)
} catch {
	print("error")
}

解決

どうやらawaitは非同期コンテンツから呼び出す必要があるらしいです。そこでTask{}で囲むことで、ブロック内の処理を非同期でひとまとまりに実行できます。以下のように変更するとエラーは消えてくれました。

Task{
	do {
		let (data , _) = try await URLSession.shared.data(from: req_url)
		let decoder = JSONDecoder()
		let json = try decoder.decode(ResultJson.self, from: data)
		
		print(json)  
	} catch {
		print("error")
	}
}
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1