QiitaのAPIでタイトルを表示

2020/09/26確認

f:id:fedora9:20200926160316p:plain

 

SwiftでQiitaのAPIを表示させる。 - Qiita

 

【1】最初のタイトルをprint文で表示

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

の下に変数articlesを追加します。

  var articles: [[String: Any]] =

 

super.viewDidLoad()

の下に追加します。

    let qiitaUrl:String = "https://qiita.com/api/v2/items"

    let url: URL = URL(string: qiitaUrl)!

    let task: URLSessionTask  = URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in

      do {

        if(data != nil)

        {

          let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [Any]

          

          let articles = json.map { (article) -> [String: Any] in

              return article as! [String: Any]

          }

          //print(json)

          print(articles[0]["title"]!)

        }

      }

      catch {

          //print(error)

      }

    })

    

    task.resume() //実行する

 

実行すると、最初のタイトルが表示されます。

f:id:fedora9:20200926153445p:plain

【2】 table Viewにタイトルを表示

Table ViewのCellの個数を設定、中身を表示 - Swift5入門(はてな)

 

画面のtable Viewを、右クリックで

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

の下にドラッグして紐つけます。名前はtableにします。

  @IBOutlet weak var table: UITableView!

が追加されます。

 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

の下に変数articlesを追加します。

  var articles: [[String: Any]] =

 

super.viewDidLoad()

の下に処理を追加します。

    let qiitaUrl:String = "https://qiita.com/api/v2/items"

    let url: URL = URL(string: qiitaUrl)!

    let task: URLSessionTask  = URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in

      do {

        let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [Any]

        let articles = json.map { (article) -> [String: Any] in

            return article as! [String: Any]

        }

        self.articles = articles

        

        DispatchQueue.main.async {

          self.table.reloadData()

        }

      }

      catch {

          //print(error)

      }

    })

    task.resume() //実行する

 

Cellの個数を設定する処理を追加します。

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return articles.count

  }

 

Cellの中身を表示する処理を追加します。

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let article = articles[indexPath.row]

    cell.textLabel!.text = article["title"] as? String

    return cell

  }

 

実行すると、table Viewにタイトルが表示されます。

f:id:fedora9:20200926160316p:plain

 【Codable】

SwiftでQiitaのAPIを表示させる。 - Qiita

Codableを使ってJSONを変換させる

import UIKit

の下に追加

struct QiitaStruct: Codable {

  var title: String

  var user: User

  struct User: Codable {

    var name: String

  }

}

 

func fetchArticle(completion: @escaping ([QiitaStruct]) -> Swift.Void) {

  let url = "https://qiita.com/api/v2/items"

  guard let urlComponents = URLComponents(string: url) else {

    return

  }

//  urlComponents.queryItems = [

//    URLQueryItem(name: "page", value: String(displayPage)),

//  ]

  let task = URLSession.shared.dataTask(with: urlComponents.url!) { data, response, error in

    guard let jsonData = data else {

      return

    }

    do {

      let articles = try JSONDecoder().decode([QiitaStruct].self, from: jsonData)

      completion(articles)

    } catch {

      //print(error.localizedDescription)

    }

  }

  task.resume()

}

 

 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

の下を変更

  //  var articles: String: Any =

  var articles: [QiitaStruct] =   // Codable

 

    //myload(page: 1)

    

    fetchArticle(completion: { (articles) in

      self.articles = articles

      DispatchQueue.main.async {

        self.table.reloadData()

      }

    })

 

func myload(page: Int)

コメントアウト。articlesの型を変更したため。

 

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->

の下を変更。

    //cell.textLabel!.text = articles[indexPath.row]["title"]! as? String

    cell.textLabel?.text = articles[indexPath.row].title  // Codable

    //cell.detailTextLabel!.text = articles[indexPath.row]["created_at"]! as? String

    cell.detailTextLabel?.text = articles[indexPath.row].user.name  // Codable

 

[Swift 1.1] swiftで api を叩いて、JSONをパースして、表示させる方法 (xcodeは6.1, iOSは8.1) - Qiita

 

SwiftでAlamofireを使ってみた。QiitaのSwiftに関する投稿をパースしてみたよ。 - Qiita

 

画像とテキストを表示

Xcode のキーバインドを Visual Studio 風にする – SHIN-ICHI の技術ブログ

 

SwiftでQiitaのAPIを表示させる。 - Qiita

 

Qiita API v2 documentation - Qiita:Developer