Just My Life & My Work

[SwiftUI] Call RESTful API

在 SwiftUI 中,我們想呼叫 API,回傳 JSON 資料,可以怎麼做呢?

此範例將可以持續點擊 Fetch Joke,來呼叫回傳隨機的某笑話。

提供笑話的 API: https://api.chucknorris.io/jokes/random

// 20220509000756
// https://api.chucknorris.io/jokes/random

{
  "categories": [
    
  ],
  "created_at": "2020-01-05 13:42:29.296379",
  "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
  "id": "wBq7IOiXSwOuZScaevFxwg",
  "updated_at": "2020-01-05 13:42:29.296379",
  "url": "https://api.chucknorris.io/jokes/wBq7IOiXSwOuZScaevFxwg",
  "value": "Chuck Norris didnt dial the wrong number......you just answered the wrong phone"
}

直接來看程式碼,就知道如何使用!

使用 URLSession 帶入 url 執行任務。

使用 JSONDecoder 來解析 JSON 資料,並以 Joke Class 封裝。

// Theme: Call RESTful API
// Language: SwiftUI
// IDE: Xcode 13.3.1
// OS: iOS 15
// Date: 2022-05-01
// Author: HappyMan

import SwiftUI

struct JokeView: View {
    @State private var joke: String = ""
    @State private var url: String = ""
    @State private var imageUrl: String = ""

    var body: some View {
        Text(joke)
            .padding()
        Text(url)
            .padding()
        AsyncImage(url: URL(string: "https://secure.gravatar.com/avatar/9971a01c3246b3b12a0f8dacc012b378"))
        Button {
            Task {
                let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.chucknorris.io/jokes/random")!)
                let decodedResponse = try? JSONDecoder().decode(Joke.self, from: data)
                joke = decodedResponse?.value ?? ""
                url = decodedResponse?.url ?? ""
                imageUrl = decodedResponse?.icon_url ?? ""
            }
        } label: {
            Text("Fetch Joke")
        }
    }
}

struct JokeView_Previews: PreviewProvider {
    static var previews: some View {
        JokeView()
    }
}

struct Joke: Codable {
    let value: String
    let url: String
    let created_at: String
    let updated_at: String
    let id: String
    let icon_url: String
}

其中 Task 是 Adds an asynchronous task to perform when this view appears.

因為變數是 @State,所以一設定值,就會刷新畫面。

參考:

隨意留個言吧:)~

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

標籤雲

%d 位部落客按了讚: