Novice SwiftUI developer can't make network call

I'm trying to use URL structure in the foundation framework and it is failing to build, returning a nil value. Could it be trying to evaluate the string I am giving it as a variable for its argument at build time? Is there a test argument I can give URL to see if it can return a non-nil value? (of URL type)?

Answered by DTS Engineer in 857889022

Thank you for the post regarding the issue you are experiencing with the URL structure in the Foundation framework.

Based on your description, it is possible that the string you are using as an argument is evaluated at build time, particularly if it involves compile-time constants or conditions that are not resolved correctly.

Could you please provide the code you are using? Is it something like this and returns nil?

let testURL = URL(string: "https://www.example.com")
print(testURL)

The more information you can provide, the better I can assist you. Please share the code you are using to construct the URL. Thank you.

Albert Pascual
  Worldwide Developer Relations.

It totally depends on what your app is supposed to do, and when.

If you want it to run when the app starts, put it inside the @main app, i.e.:

// This is defined at the 'top level' because it's not within a function, struct, class etc.
let myString = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=AAPL&apikey= *********"

func doNetworkCall() {
  if let banjo = URL(string: myString) {
    let Lulah = URLSession.shared.dataTask(with:banjo ) { myDatastring , response , error in}
      Lulah.resume()
  } else {
    myDatastring="nil url"
  }
}

@main
struct MyApp: App {
  doNetworkCall()  // This will be executed first
}

If you want it to be executed when the user presses a button, then add a View struct with the Button in it that calls the doNetworkCall() function.

You've stated you're a novice developer, and that's fine; I just can't go into much more detail as this isn't the place for that, and Apple has perfectly useful sample code and coding exercises you can follow. It looks like you've jumped in and missed a few fundamentals. Try the tutorials here: https://developer.apple.com/tutorials/develop-in-swift/welcome-to-develop-in-swift-tutorials

I have been through that tutorial. But I guess I'm not retaining knowledge that is needed. Thank you for your help.

Novice SwiftUI developer can't make network call
 
 
Q