2

I have an image in the form of Data obtained from firebase:

if let img = selectedPost.media[numberMedia + 1].image {
    let data = (img.pngData() as Data?)!//here

I need to convert this value into a URL. How can I do that?

I have tried:

let imageUrl = URL(dataRepresentation: data, relativeTo: "https://URL")

but get

Cannot convert value of type 'String' to expected argument type 'URL?'

  • You have an image in the form of data? So it’s a byte? I’d have the data in one column and the URL link in another and reference the data from the URL column – traveler3468 Apr 16 '19 at 22:51
  • If you already have the image data in memory you just need to write it to disk (documents directory or library) and use that local file URL – Leo Dabus Apr 16 '19 at 22:58
  • 1
    FYI - `let data = (img.pngData() as Data?)!` should just be `if let data = img.pngData() { // do something }` – rmaddy Apr 17 '19 at 00:05

1 Answers1

3

No you can't create a URL from data , only if this url is pointing to a local storage such as file url in documents / library , So you have

  • Remote url - > read data from it

  • local data -> write to local url

  • local data -> upload to server and get a remote url referring to it

  • X local data -> get remote url locally without uploading X > can't be

Also use

guard let data = img.pngData() else { return } 

instead of the un safe !

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • if you have the url in Firebase , you can only pull the data from it , and save it locally in documents as said to get a local url , to upload to firebase storage you need data and call the method `.putData` that points to the correct child may be same child that you read from to overwrite the new data – Shehata Gamal Apr 17 '19 at 09:46