Home > Software engineering >  How to send a URL via .success completion in Swift?
How to send a URL via .success completion in Swift?

Time:04-30

I have a StorageManager.swift singleton class which is a class for manage FireBase storage and a function in it:

public func downloadURL(for path: String, completion: @escaping (Result<String, Error>) -> Void)
{
    let reference = storage.child(path)
    reference.downloadURL(completion: {url, error in
        guard let url = url, error == nil else
        {
            completion(.failure(StorageErrors.failedToGetDownload))
            return
        }
        
        completion(.success(url))
       
    })
}

Compiler giving an error like: "Cannot convert value of type 'URL' to expected argument type 'String' "

By using this public function I want to download an image in another class. Here is code:

StorageManager.shared.downloadURL(for: path, completion: {[weak self] result in
        switch result
        {
        case .success(let url):
            self?.downloadImage(imageView: imageView, url: url)
        
        case .failure(let error):
            print("error when fetching url download\(error)")
        }
    })

In this side error is : "Cannot convert value of type 'String' to expected argument type 'URL' "

I tried to send it like:

completion(.success(url.absoluteString))

and cast it as an URL again:

 self?.downloadImage(imageView: imageView, url: url as! URL)

but failed. How can I pass the URL correctly?

CodePudding user response:

Your downloadURL() function declares that the result is a String:

Change it to return a Result with an URL instead:

public func downloadURL(for path: String, completion: @escaping (Result<URL, Error>) -> Void)
  • Related