| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「Swift Sample」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
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


データ取得


  1. let url = URL(string: "https://www.typea.info/blog/")!
  2. let task = URLSession.shared.dataTask(with: url) { data, response, error in
  3. if let error = error {
  4. print("\(error)\n")
  5. return
  6. }
  7. guard let data = data, let response = response as? HTTPURLResponse else {
  8. print("no data or no response.")
  9. return
  10. }
  11. if response.statusCode == 200 {
  12. if let text = String(bytes: data, encoding: .utf8) {
  13. print(text)
  14. }
  15. }
  16. }
  17. task.resume()
MacOSでエラーの場合

Error Domain=NSURLErrorDomain Code=-1003

Swift macos net error.png

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で囲む
  1. DispatchQueue.main.sync {
  2. observableobj.content = text
  3. }