swiftuiimageviewurinsurlconnection

How Can I get Image data from specific URI in Swift?


I have a function called downloadImage. I'm trying to get image data and set an imageView. But it prints "no data".

image link: http://commons.wikimedia.org/wiki/Special:FilePath/Flag%20of%20Montenegro.svg

Here is my code:

func downloadImage() {
    
    let uri = "Special:FilePath/Flag%20of%20Montenegro.svg"
    let baseURL = URL(string: "http://commons.wikimedia.org/wiki/")!
    let imageURL = URL(string: uri, relativeTo: baseURL)!
    if let data = try? Data(contentsOf: imageURL){
        if let image = UIImage(data: data){
            DispatchQueue.main.async {
                self.flagImageView.image = image
            }
        }
        else{
            print("image cannot be taken")
        }
    }else{
        print("no data")
    }
}

Here is console output:

2022-09-03 21:21:56.426579+0300 CountryBook[5242:197393] nil host used in call to 
allowsSpecificHTTPSCertificateForHost
2022-09-03 21:21:56.426913+0300 CountryBook[5242:197393] nil host used in call to allowsAnyHTTPSCertificateForHost:
2022-09-03 21:21:56.427580+0300 CountryBook[5242:197905] NSURLConnection finished with error - code -1002
no data

Note:

I Allowed Arbitrary Loads from info.plist by marking it as YES.


Solution

  • Assuming you did allow the usage of http corectly. There is more going on here:

    Remarks:

    Just use https. It´s de facto standard. And your link to wikipedia would support it. Falling back to http should be the last resort while developing and never in production.