Swift async/await关键字
在日常项目开发中,一般耗时的操作我们不可能全部让主线程去做完,会导致app的卡顿。我们一般都是异步执行的。
以图片渲染为例子。
闭包
从前我们经常是异步下载了图片,然后闭包为回调触发使用。
异步下载图片闭包回调
private func blockGetImage(completionHandler: @escaping(Data) -> Void) {
DispatchQueue.global().async {
let url : URL = URL(string: "http://i8-static.jjwxc.net/tmp/backend/authorspace/s1/28/27087/2708639/20220518224228.jpg")!
let data : Data = try! Data(contentsOf: url)
DispatchQueue.main.async {
completionHandler(data)
}
}
}}
闭包使用
SwiftUI
var body: some View {
VStack
{
Image(uiImage: UIImage(data: data) ?? UIImage())
.resizable()
}
.onAppear {
print("name = \(self)")
blockGetImage {
data = $0
}
}
.navigationTitle("async和await")
}
Swift
override func viewDidLoad() {
super.viewDidLoad()
self.img = UIImageView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 100))
self.view.addSubview(self.img)
blockGetImage {
self.img.image = UIImage(data: $0)
}
}
async/await
async是异步请求
await是将async异步转为同步
// async方式得到图片的Data
private func asyncGetImage() async -> Data {
do {
let (d, _) = try await URLSession.shared.data(for: URLRequest(url: URL(string: "http://i8-static.jjwxc.net/tmp/backend/authorspace/s1/28/27087/2708639/20220518224228.jpg")!))
return d
} catch {
return Data()
}
}
SwiftUI使用
var body: some View {
VStack
{
Image(uiImage: UIImage(data: data) ?? UIImage())
.resizable()
}
.onAppear {
print("name = \(self)")
}
.task {
data = await asyncGetImage()
}
.navigationTitle("async和await")
}
Swift使用
override func viewDidLoad() {
super.viewDidLoad()
self.img = UIImageView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 100))
self.view.addSubview(self.img)
Task {
self.img.image = await UIImage(data: asyncGetImage())
}
}
Github地址
懒得打的可以直接打开项目查看 Github地址 https://github.com/HahnLoving/iOS_Study