BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.