「Swift Sample」の版間の差分
ナビゲーションに移動
検索に移動
| 40行目: | 40行目: | ||
*上記で、バックグラウンドから、observableobj.contentを操作すると、UIはメインスレッドから触るように怒られる。 | *上記で、バックグラウンドから、observableobj.contentを操作すると、UIはメインスレッドから触るように怒られる。 | ||
<blockquote>Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.</blockquote> | <blockquote>Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.</blockquote> | ||
| + | *DispatchQueue.main.syncで囲む | ||
<pre> | <pre> | ||
DispatchQueue.main.sync { | DispatchQueue.main.sync { | ||
2021年3月22日 (月) 10:06時点における版
| Swift | SwiftUI |Xcode | Mac |
Swift Sample
Network
データ取得
let url = URL(string: "https://www.typea.info/blog/")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("\(error)\n")
return
}
guard let data = data, let response = response as? HTTPURLResponse else {
print("no data or no response.")
return
}
if response.statusCode == 200 {
if let text = String(bytes: data, encoding: .utf8) {
print(text)
}
}
}
task.resume()
MacOSでエラーの場合
Error Domain=NSURLErrorDomain Code=-1003
- https://www.poly-rhythm.com/hostname-could-not-be-found/
- https://developer.apple.com/documentation/xcode/adding_capabilities_to_your_app
UI
バックグラウンドからUIを操作する
- observableobj が、ObservableObject の派生クラス
- contentフィールドに、@Published アノテーション
- Viewで、@ObservedObjectを付与しインスタンスを生成
- 上記で、バックグラウンドから、observableobj.contentを操作すると、UIはメインスレッドから触るように怒られる。
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
- DispatchQueue.main.syncで囲む
DispatchQueue.main.sync {
observableobj.content = text
}
© 2006 矢木浩人