Search code examples
iosswift

Converting string of an Image URL of API to UIImage


I'm trying to convert an URL string that I get from the API. I'm getting the URL for the API in my modelView as below:

class DetailViewModel {

var countryCode : String?

public func getImageURL(with completion: @escaping (String) -> Void) {
    APIHandler.getDataForCountryImage(for: countryCode!) { result in
        print("result is \(result)")
        completion(result.data.flagImageUri)
    }
  }
}

The print statement above successfully prints the URL as string. So no problem about getting the URL as string.

I'm initializing my viewController with the viewModel as below:

private var viewModel: DetailViewModel

//MARK: - LifeCycle

init(with viewModel: DetailViewModel) {
    self.viewModel = viewModel
    super.init(nibName: nil, bundle: nil)
    
}

and trying to convert he image url String I got from the modelView to UIImage with the code below:

 private func setCountryFlagImage() {
    self.viewModel.getImageURL { [weak self] imageURL in
        print("image url is \(imageURL)")
        let url = URL(string: imageURL)
        DispatchQueue.main.async {
            self?.countryImage.load(url: url!)
        }
    }
}

this function also prints the print("image url is (imageURL)") statement with the related url as string.

Inside the dispatchque, I'm basically using the UIImageView extension I wrote below. countryImage is the UIImageView that I want to update the image of.

extension UIImageView {
func load(url: URL) {
    URLSession.shared.dataTask(with: url) { data, response, error in
        if error == nil {
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data) else { return }
            DispatchQueue.main.async { [weak self] in
                print("dispatch")
                self?.image = image
            }
        }
        else {
            print("error is \(error)")
        }
        
    }.resume()
}
}

When I run the code, I can see the print statement of setCountryFlagImage in terminal, but additionally there is a warning says "[boringssl] boringssl_metrics_log_metric_block_invoke(144)" but I guess this might be irrelevant with my problem.

On the extension block of the code, I never see the print("dispatch") statement and this is happening because I can not guard let image = UIImage(data: data)

What am I missing here?


Solution

  • The problem was the image coming from the api is in type of .svg, which can not be converted to UIImage directly. In order to change it to UIImage we need to use a third party frame work called SwiftSVG. Github repository for that framework is as below. Thank you all.

    https://github.com/mchoe/SwiftSVG