TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.