
Swift如何请求数据
作者: boyyang
分类: Swift
发布: 2024-09-17 08:35:05
更新: 2025-03-23 12:35:52
浏览: 161
这两天正在学习ios应用开发,其实有很多第三方跨端开发框架可以直接使用,而且开发效率也会非常快速,能够实现多端发布。但是为了学习,所以我最近在看相关的资料。
网上关于swift的学习资料感觉非常少,特别是中文文档更加的少。
UI视图参考SwiftUi组件,UI组件其实都还好,其实就是组件拼凑,把页面拼出来就好了,只是说和vue react这种前端框架不同,会html,css就可以直接安装自己想要的写样式就行了。swift ui 则完全不同,一个组件有各种方法,各种参数配置,得去看文档等等,反正就是开发体验非常差,经常不知道问题出在哪里。网上资源也很少,所以开发也是非常有难度的。
在对swift以及swift ui有过一些简单的了解后,接下来就是如何将数据和视图进行结合了,下面是一个简单的使用, 一般来说把视图与数据分开,让结构更加具有可维护性
视图:
//
// Home.swift
// Unsplash
//
// Created by boyyang on 2024/9/15.
//
import SwiftUI
struct Home: View {
@State private var gridColumns = Array(repeating: GridItem(.flexible()), count: 3)
@StateObject var imgList: ImageList = ImageList()
var body: some View {
LazyVGrid(columns: gridColumns) {
ForEach(imgList.list, id: \.self){image in
NavigationLink(destination: ImagePreview()) {
Rectangle()
.overlay {
AsyncImage(url:URL(string:"https://minio.boyyang.cn/boyyang/\(image.file_path)")){image in
image.image?.resizable()
.aspectRatio(contentMode: .fill)
}
}
}
.cornerRadius(8.0)
.aspectRatio(1, contentMode: .fit)
}
}
}
}
#Preview {
Home()
}
数据:
//
// ImageList.swift
// Unsplash
//
// Created by boyyang on 2024/9/17.
//
import Foundation
struct ImageListRes: Decodable, Hashable {
var code: Int
var msg: String
var data: ImageInfos
}
struct ImageInfos: Decodable, Hashable {
var count: Int
var infos: [ImageInfo]
}
struct ImageInfo: Decodable, Hashable {
var id: Int
var file_name: String
var file_path: String
var status: Bool
var w: Int
var h: Int
}
class ImageList: ObservableObject {
@Published var list: [ImageInfo] = []
@Published var isLoading: Bool = true
init(){
isLoading = true
guard let url = URL(string: "http://localhost:9527/file/list/public?page=1&limit=10&id=1") else {return}
URLSession.shared.dataTask(with: url){(data, response, error) in
guard let data = data else{return}
let res = try! JSONDecoder().decode(ImageListRes.self, from: data)
DispatchQueue.main.async{
self.isLoading = false
self.list = res.data.infos
}
}.resume()
}
}