Swift async await 使用介绍

//
//  ViewController.swift
//  AsynWait
//
//  Created by shengjie on 2022/2/9.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        /// 老方法
        async {
            let data = await getImage()
            DispatchQueue.main.async {
                self.imageView.image = UIImage(data: data)
            }
        }
        /// 新方法
        Task(priority: .low) {
            let data = await getImage()
            DispatchQueue.main.async {
                self.imageView.image = UIImage(data: data)
            }
        }

        // Do any additional setup after loading the view.
    }

    func getImage() async -> Data {
        do {
            let (d, _) = try await URLSession.shared.data(for: URLRequest(url: URL(string: "https://raw.githubusercontent.com/1401788197/VideoSliderCrop/master/VideoPlayDemo/IMG_0950.jpg")!))
            return d
        } catch {
            return Data()
        }
    }
}

 

上一篇:iostat工具


下一篇:【前端面试必读】setTimeout 、 promise、async await 的执行顺序?宏任务、微任务,分别包含哪些?