UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 33 : error while using synchronous code suggesting asynchronous code!

Forums > 100 Days of Swift

Synchronous URL loading of "https://www.hackingwithswift.com/samples/petitions-1.json" should not occur on this application's main thread as it may lead to UI unresponsiveness. Please switch to an asynchronous networking API such as URLSession.

got the above error while writing

override func viewDidLoad() {
    super.viewDidLoad()

    var urlString = "https://www.hackingwithswift.com/samples/petitions-1.json"

    if let url = URL(string: urlString) {
        if let data = try? Data(contentsOf: url) {
            parse(json: data)
            return
        }
    }
}

2      

This code is synchronous, meaning UI may become unresponsive while fetching data from web. One of many options to do that as an example (you may use any other similar using async code) like so:

create

struct DataLoader {
    func downloadData(url: URL) async -> Data? {
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            return data
        } catch let error {
            print(error)
        }
        return nil
    }
}

then use for fetching the data

func downloadData(from url: String) {
        guard let url = URL(string: url) else { return }

        Task {
            let dataLoader = DataLoader()
            let receviedData = await dataLoader.downloadData(url: url)
            if let data = receviedData {
                parse(json: data)
            } else {
                showError()
            }
        }
    }

the "main part" is this try await URLSession.shared.data(from: url) - this runs asyncly. To put other part of synch code in async environment you can ust Task { // your async code here }

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.