WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Variables in URL string not working for AsyncImage

Forums > SwiftUI

Good morning

Doing a little macOS app to generate posting barcode labels....where it takes inputs from textfields and generates the required GET method URL string like:

https://mybarcodeserver.ch/label.php?name1=Richard&name2=&pobox=&street=Mainstreet&number=1a&street2=&zip=9999&city=Hometown

This works fine...but as soon I want to use variables inside the string with (name) and so on...the URL isn't even called...nor a warning/error is thrown....

Is there a better way to load images via URL GET method? Downside of AsyncImage is that I can't force a refresh with a button in the same view....

thanks in advance richard

   

Please show the code where you are performing the string interpolation.

   

This is the AsyncImage part:

AsyncImage(url: URL(string: "https://mybarcodeserver.ch/label.php?name1=\(name)&name2=\(name2)&pobox=&street=\(street)&number=\(number)&zip=\(zip)&city=\(city)&fragile=f&economy=f&signature=f")) { phase in
                    switch phase {
                        case .empty:
                            ProgressView()
                        case .success(let image):
                            image.resizable()
                                 .aspectRatio(contentMode: .fit)
//                                 .frame(maxWidth: 500, maxHeight: 350)
                        case .failure:
                            Image(systemName: "photo")
                        @unknown default:
                            EmptyView()
                        }
                }

   

So basic debugging technique. Did you try creating a standalone string and populating the URL with this string?

// Paste into Playgrounds to verify your URL. Hope you did this?
// Did you skip the pobox for a reason? 
// If you missed the pobox, does this become an invalid URL ?

let name     = "Tim"
let name2    = "Cook"
let street   = "Infinite Loop"
let number   = "1"
let zip      = "90210"  // Probably Beverly Hills
let city     = "Cupertino"
let myURL: String  { 
  "https://mybarcodeserver.ch/label.php?"
+ "name1="   + name
+ "&name2="  + name2
+ "&pobox="  + ""      // This is empty in your code?
+ "&street"  + street
+ "&number=" + number
+ "&zip="    + zip
+ "&city="   + city
+ "&fragile=f&economy=f&signature=f"
}

myURL  // <-- Verify your URL

// When verified, insert into the Async
AsyncImage(url: URL(string: myURL)) { phase in   // .... snip .....

   

Good morning (o;

My fault.....forgot about URL encoding (o;

Using this function now to supply the URL string:

  func getUrlString () -> String {
      var components = URLComponents()
      components.scheme = "https"
      components.host = "mybarcodeserver.ch"
      components.path = "/label.php"
      components.queryItems = [
          URLQueryItem(name: "name1", value: name),
          URLQueryItem(name: "name2", value: name2),
          URLQueryItem(name: "pobox", value: postfach),
          URLQueryItem(name: "street", value: strasse),
          URLQueryItem(name: "street2", value: zusatz),
          URLQueryItem(name: "zip", value: plz),
          URLQueryItem(name: "city", value: ort)
      ]
      return components.string ?? ""
  }

AsyncImage(url: URL(string: getUrlString() )) { phase in

Only annoying is that for every key press in a TextField AsyncImage is called....have to think about another solution to only show AsyncImage on demand....

   

Richard is annoyed and maps a path for learning a new technique:

Only annoying [thing] is that for every key press in a TextField AsyncImage is called....have to think about another solution to only show AsyncImage on demand..

Are ye familiar with debounce and throttle?

No?

Hang on tight, this is your opportunity to learn from another brilliant SwiftUI developer!

Debouncing is the process of accepting user input from a TextField, then executing some code. The debounce technique, however, only executes the code after a predetermined delay from the last time it executed the code.

So, if your user is entering the city Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch into the ort textfield, your code won't execute as each letter is typed! You can configure the debounce code to only execute when the user pauses for a predetermined delay. Ausgezeichnet!

Come back and let us know how you implemented your solution!

See-> Debouncing User Input <- The other brilliant developer. (Not me!!)

See-> Visit Beautiful Wales

   

Never said I was annoyed ;-)

Okay..just watched the video...and seems "debounce" is the way to go....

One drawback though with AsyncImage:

Loading a new image doesn't show ProgressView() anymore in phase .empty when an image has been loaded before...as it isn't "empty" anymore of course (o;

Is there a way to clear the loaded image?

   

Did you edit your post?

I am almost quite sure that I quoted you directly:

Only annoying [thing] is that for every key press in a TextField AsyncImage is called....have to think about another solution to only show AsyncImage on demand..

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, 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!

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.