天天看點

swiftui_從swiftui中的api擷取資料 SwiftUI (SwiftUI) 蜜蜂 (APIs)

swiftui

SwiftUI (SwiftUI)

SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. — Wikipedia. The best part is, you can integrate your views with components from UIKit, AppKit and WatchKit framework. SwiftUI has made building user interface straightforward.

SwiftUI是一種創新的,非常簡單的方法,可以借助Swift跨所有Apple平台建構使用者界面。 僅使用一組工具和API為任何Apple裝置建構使用者界面。 —維基百科。 最好的部分是,您可以将視圖與UIKit,AppKit和WatchKit架構中的元件內建在一起。 SwiftUI使建構使用者界面變得簡單明了。

蜜蜂 (APIs)

API stands for Application Programming Interface. At some point, you would have built or will build APIs for your app. API allows your application to communicate to the server. One most important point to note is, API is just an interface between your application and the server/database. It is not a database or server itself. It just allows all these entities to talk to each other. In simple words, API is an access point to your job that can access different entities such as a server or a database etc. For example, the weather has an API that you could use, that does not mean you have access to their database and can query everything. You only have access to an access point that has access to the database. I get this question a lot and figured I would spend 2–3 lines specifically addressing this.

API代表應用程式程式設計接口。 在某個時候,您将為您的應用程式建構或将建構API。 API允許您的應用程式與伺服器進行通信。 需要注意的最重要一點是,API隻是應用程式與伺服器/資料庫之間的接口。 它本身不是資料庫或伺服器。 它隻允許所有這些實體互相交談。 簡而言之,API是您可以通路不同實體(例如伺服器或資料庫等)的工作的通路點。例如,天氣具有您可以使用的API,這并不意味着您可以通路其資料庫和可以查詢一切。 您隻能通路有權通路資料庫的通路點。 我經常聽到這個問題,并認為我将花2-3行專門解決這個問題。

In this article, we will talk about how you could fetch data in SwiftUI from an API. Let us get started by creating a new project.

在本文中,我們将讨論如何從API中在SwiftUI中擷取資料。 讓我們開始建立一個新項目 。

  1. Open Xcode

    開啟Xcode

  2. Create a new project (Single View Application is alright)

    建立一個新項目(單視圖應用程式可以)

  3. Make sure Use SwiftUI is selected under languages

    確定在語言下選擇了使用SwiftUI

Alright! Now we have a project setup, you could see ContentView.swift in your project structure. Try running your code, you should be able to see “Hello World” string printed on your iPhone

好的! 現在我們有了一個項目設定,您可以在項目結構中看到ContentView.swift。 嘗試運作代碼,您應該可以在iPhone上看到“ Hello World”字元串

Model: Create a new Swift file and name it Model.swift. We need a struct “TaskEntry” to store fetched data into and another TaskList to Store fetchedResponse. Let’s create a simple model

模型:建立一個新的Swift檔案并将其命名為Model.swift。 我們需要一個結構“ TaskEntry”來将擷取的資料存儲到其中,并需要另一個TaskList來存儲fetchedResponse。 讓我們建立一個簡單的模型

import Foundationstruct TaskEntry: Codable  {
    let id: Int
    let title: String
}
           

Codable: Usually APIs return a JSON and you would need to decode and encode using JSONEncoder and JSONDecoder, therefore, we need to make sure our model can be coded and decoded. Therefore, we have added “Codable” string to make the Model codable.

可編碼:通常,API傳回JSON,您需要使用JSONEncoder和JSONDecoder進行解碼和編碼,是以,我們需要確定可以對模型進行編碼和解碼。 是以,我們添加了“ Codable”字元串以使Model可編碼。

Service: Go back to your Content View and add a new State variable,

服務:傳回您的内容視圖并添加一個新的State變量,

//Since the response is an array of TaskEntry object
@State var results = [TaskEntry]()
           

In your ContentView.swift, create a new Function to load data

在您的ContentView.swift中,建立一個新函數以加載資料

func loadData() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)


        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
                    DispatchQueue.main.async {
                        self.results = response
                    }
                    return
                }
            }
        }.resume()
    }
           

This function will load our data into our struct. If at this point, you would print your data in init(), you should be able to see your API response. Run your program and you should be able to see all the data from your API printed in the console. Alright! Milestone 1 completed. Your service is hitting your end-point correctly and encoding decoding is working perfectly too while reading data from your API.

此函數會将我們的資料加載到我們的結構中。 如果此時要在init()中列印資料,則應該可以看到API響應。 運作您的程式,您應該能夠看到控制台中列印的API中的所有資料。 好的! 裡程碑1已完成。 您的服務正确地到達了終點,并且在從API讀取資料時,編碼解碼也可以正常工作。

Now let us render this data on the screen. To do that, we need to call the function loadData(). One thing I love about SwiftUI is the built-in modifiers, such as “.onAppear”. Lets’ go ahead and add a modifier to our list so as our list appears, we call loadData() and create our View.

現在,讓我們在螢幕上呈現此資料。 為此,我們需要調用函數loadData()。 我喜歡SwiftUI的一件事是内置的修飾符,例如“ .onAppear”。 讓我們繼續,向清單中添加一個修飾符,以便在清單出現時,我們調用loadData()并建立我們的View。

import SwiftUI


struct ContentView: View {
    
    @State var results = [TaskEntry]()
  
    var body: some View {
        List(results, id: \.id) { item in
            VStack(alignment: .leading) {
                Text(item.title)
            }
        }.onAppear(perform: loadData)
    }
    
  
    func loadData() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
            print("Your API end point is Invalid")
            return
        }
        let request = URLRequest(url: url)


        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
                    DispatchQueue.main.async {
                        self.results = response
                    }
                    return
                }
            }
        }.resume()
    }
    
}
           

Go ahead and run your app. You should be able to see the fetched data from your API. That is it! Your SwiftUI app is now communicating with your API. You can find the boiler-plate to start with on my Github. Thank you !

繼續運作您的應用程式。 您應該能夠看到從API提取的資料。 這就對了! 您的SwiftUI應用現在正在與您的API通信。 您可以在我的Github上找到開始的樣闆。 謝謝 !

翻譯自: https://medium.com/swlh/fetch-data-from-apis-in-swiftui-74b4b50f20e9

swiftui