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 of Montenegro.svg
Here is my code:
func downloadImage() {
let uri = "Special:FilePath/Flag of Montenegro.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.
CodePudding user response:
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 properURLSesssion
.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.
CodePudding user response:
this is actually due to the fact that apple no longer allows http
urls by default, it wants them to be https
When using a https url, you also shouldn't need to allowArbitraryLoads
From what I suspect though, wikipedia is https, so I think you can just change your url to have https like so: https://commons.wikimedia.org/wiki/Special:FilePath/Flag of Montenegro.svg