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
I Allowed Arbitrary Loads from info.plist by marking it as YES.
Assuming you did allow the usage of http
corectly. There is more going on here:
The link you provided redirects to https://upload.wikimedia.org/wikipedia/commons/6/64/Flag_of_Montenegro.svg. Data(contentsOf:
is not for this purpose. It is best suited for loading data from a bundle file url and not complex redirecting or cookies or header..... . Use a proper URLSesssion
.
Even if you get your data it will not work this way. UIImage doesn´t support SVG
format. See this SO question for more info
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.