天天看点

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