2

I have generated a URL with the following function below. I would like to save this to the local folder for use later on. However, when I save it to the local folder, and then retrieve it, the URL is truncated. Please can someone advise on how I would be able to save and extract the full URL?

func createPhotoURL() -> URL {
    
    let fileName = "tempImage_wb.jpg"
    
    let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectory = documentsDirectories.first!
    let pdfPageURL = documentDirectory.appendingPathComponent("\(fileName)")
    
    return pdfPageURL
}

When I call the function I get the full length URL:

let imageURL = createPhotoURL() // CORRECT URL FOR FILE UPLAOD
print("imageURL: \(imageURL)")

Console:

file:///var/mobile/Containers/Data/Application/CDDE2FED-5AAB-4960-9ACF-33E7B42D05AE/Documents/tempImage_wb.jpg

Save above URL to local folder and the retrieve it:

UserDefaults.standard.set(imageURL, forKey: "URL_IMAGE")
guard let retrievedURL = UserDefaults.standard.string(forKey: "URL_IMAGE") else{return}
print("retrievedURL: \(retrievedURL)")

Console:

retrievedURL: ~/Documents/tempImage_wb.jpg
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dean
  • 321
  • 3
  • 17

1 Answers1

0

To answer your question, use UserDefaults.standard.url instead of UserDefaults.standard.string

guard let retrievedURL = UserDefaults.standard.url(forKey: "URL_IMAGE") else{return}

But this will work only if you save the path and retrieve it in the same session. If you use the above code and run the app multiple times, you will get non-truncated urls (like you want). But if you check it properly you can see you are actually getting different urls in different sessions.

So you shouldn't save it as a URL, instead you should save it as string. For that you can use absoluteString property of URL

let imageURL = createPhotoURL()
print("imageURL: \(imageURL)")
UserDefaults.standard.set(imageURL.absoluteString, forKey: "URL_IMAGE")

And to retrieve, you will first retrieve the saved string from UserDefaults and then convert that into a URL

if let urlString = UserDefaults.standard.string(forKey: "URL_IMAGE"),
    let retrievedURL = URL(string: urlString) {

    print("retrievedURL: \(retrievedURL)")
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vincent Joy
  • 2,598
  • 15
  • 25