其他分享
首页 > 其他分享> > Swift async await 使用介绍

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()
        }
    }
}

 

标签:data,await,let,imageView,async,getImage,Swift
来源: https://www.cnblogs.com/ZhangShengjie/p/15875441.html