I'm using Swift 4 and trying to get images from my server. Using ipconfig
in terminal, I know my localhost's ip is 10.43.229.215
.
the following code is to retrieve the image data and turn it into UIImage
:
func GetImage(url:String) {
let image = String(localIP + url).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let url = URL(string: image)
print(image)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print("Client error!")
return
}
guard let data = data else {
print("Error: did not receive data")
return
}
DispatchQueue.main.async {
self.LensImageView.image = UIImage(data: data)
}
}).resume()
}
What I don't understand is that, the image
string did show the image I want if I copy/paste the string to my browser
(http://10.43.229.215:3000/lensPic/%E5%A4%AA%E5%A6%83%E7%B3%96%E6%9D%8F.png)
However, error appears at the line self.LensImageView.image = UIImage(data: data)
saying Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
.
I'm really confused about:
nil
if there is already a guard let
method?Any help is highly appreciated!
The problem lies in making a false assumption about what is nil. It has nothing to do with the image or the data. What’s nil is self.LensImageView
, the outlet property.