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

Trouble with Await and Task

Forums > Swift

Just learning SwiftUI as a hobby and could use some help with Task/Await/Async. I am creating an app that scrapes a webpage. I imagine I want to have my webpage fetching func be async. Done. Then in ContentView I am calling that func (inside a Do/Catch) to return a String "webpageContent". But then I get the error "Cannot find 'webpageContent' in scope" when I try to use that String. That error goes away when I take the fetching call out of Do/Catch, but then I get two errors on the fetching call: "'async' call in a function that does not support concurrency" and "Errors thrown from here are not handled". Help please!

Here's the relevant code:

struct ContentView: View {
    @State private var url: String = "https://baseball5.onroto.com/baseball/webnew/display_live_scoring.pl?Rotorooters+4&session_id=4ouuH2UfoQR5tT9LSMos4ZC0zNIn&which_team=4"

    var body: some View {
        do {
            let webpageContent = try await fetchWebPageContent(from: url)
        } catch {
            fatalError()
        }

        let scrapedContent = docScrape(from: webpageContent)

lots of code then:

               }
                .padding()
                .navigationTitle("Live Stats for My Team")
                .navigationBarTitleDisplayMode(.inline)
                .task {
                    await fetchWebPageContent(from: url)
                }

And the fetching func:


func fetchWebPageContent(from urlString: String) async throws -> String {
    guard let url = URL(string: urlString) else {
        throw URLError(.badURL)
    }

    let (data, response) = try await URLSession.shared.data(from: url)

    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        throw URLError(.badServerResponse)
    }

    guard let webpageContent = String(data: data, encoding: .utf8) else {
        throw URLError(.cannotParseResponse)
    }
    print(webpageContent)
    return webpageContent
}

   

Hi! You may want to use similar to this approach depending on what you are going to do with your response. I just used Text() to make sure it is recevied as string...

struct ContentView: View {
    @State private var url: String = "https://baseball5.onroto.com/baseball/webnew/display_live_scoring.pl?Rotorooters+4&session_id=4ouuH2UfoQR5tT9LSMos4ZC0zNIn&which_team=4"

    @State private var webConent: String = ""

    var body: some View {
        Text(webConent)
        .task {
            do {
                webConent = try await fetchWebPageContent(from: url)
            } catch {
                print(error)
            }
        }
    }
}

func fetchWebPageContent(from urlString: String) async throws -> String {
    guard let url = URL(string: urlString) else {
        throw URLError(.badURL)
    }

    let (data, response) = try await URLSession.shared.data(from: url)

    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        throw URLError(.badServerResponse)
    }

    guard let webpageContent = String(data: data, encoding: .utf8) else {
        throw URLError(.cannotParseResponse)
    }
    print(webpageContent)
    return webpageContent
}

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.