Search code examples
iosswifturldata-conversion

How to convert Data to URL()?


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?'


Solution

  • 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 !