Xcode UIView.init(frame:) must be used from main thread only Xcode UIView.init(frame:) must be used from main thread only ios ios

Xcode UIView.init(frame:) must be used from main thread only


Xcode 9 has a new runtime Main Thread Checker that detects call to UIKit from a background thread and generate warnings.

I know its meant to generate warnings and not crash the app, but you can try disabling Main Thread Checker for your test target.

enter image description here

I tried this code in a sample project, the debugger paused at the issue (as it is supposed to), but the app didn't crash.

override func viewDidLoad() {    super.viewDidLoad()    DispatchQueue.global().async {        let v = UIView(frame: .zero)    }}


Main Thread Entry

You can enter the main thread as follows

DispatchQueue.main.async {     // UIView usage}


You can use this function

func downloadImage(urlstr: String, imageView: UIImageView) {    let url = URL(string: urlstr)!    let task = URLSession.shared.dataTask(with: url) { data, _, _ in        guard let data = data else { return }        DispatchQueue.main.async { // Make sure you're on the main thread here            imageview.image = UIImage(data: data)        }    }    task.resume()}

How to use this function?

downloadImage(urlstr: "imageUrl", imageView: self.myImageView)