0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コンソール アプリ向け、簡易版 Web サイト読み込み

Last updated at Posted at 2021-01-28

極端な例ですが、コンソール アプリで、様々な問題は無視して

let ws = MyWebLoader("https://www.example.com/")
print(ws.data!)  // データを表示

として、サイトのデータを取得したいときの、MyWebLoader クラスです。

注意: サイトが応答するまで処理がブロックされます

class MyWebLoader {
    var sem = DispatchSemaphore(value: 0)
    var error: Error?
    var response: HTTPURLResponse?
    var data: Data?
    init(_ string: String) {
        let url = URL(string: string)!
        let req = URLRequest(url: url)
        let task = URLSession.shared.dataTask(with: req) { dat, res, err in
            self.error = err
            self.response = res as? HTTPURLResponse
            self.data = dat
            self.sem.signal()
        }
        task.resume()
        sem.wait()
    }
}
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?