Reputation: 1560
I'm trying to load multiple images from the web asynchronously. Looking I found this forum post "Loading/Downloading image from URL on Swift" but I still have some "issues".
I have this code:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let newCell = tableView.dequeueReusableCellWithIdentifier("userCell") as! UserCell_TableViewCell
let selectedUser = userArray[indexPath.row]
newCell.userDescription?.text = selectedUser.getFirstName() + " " + selectedUser.getLastName()
if let userImage = selectedUser.getImage()
{
// NO CODE
}
else
{
newCell.userImage.downloadedFrom(self.imageArray[arrayIndex])
}
return newCell
}
extension UIImageView {
func downloadedFrom(urlLink :String)
{
if let urlData = NSURL(string: urlLink) {
NSURLSession.sharedSession().dataTaskWithURL(urlData, completionHandler: { (data, response, error) in
if error == nil
{
print("Correct URL: " + "\(urlLink)")
}
else
{
print("Incorrect URL: " + "\(urlLink)")
}
}).resume()
}
}
}
PROBLEM
1) to test, I enter right and wrong directions, but always tells me to be correct.
QUESTIONS
1) It is possible that the image can return it for use elsewhere?
2) How do to detect that the URL is invalid and thus enter a default image?
EDIT
Optional( { URL: http://findicons.com/files/icons/1072/face_avatars/300/a03.png } { status code: 200, headers { "Accept-Ranges" = bytes; Connection = "keep-alive"; "Content-Length" = 32759; "Content-Type" = "image/png"; Date = "Fri, 23 Oct 2015 14:20:20 GMT"; "Last-Modified" = "Thu, 11 Feb 2010 10:49:27 GMT"; Server = "nginx/1.1.19"; } })
Optional( { URL: http://findicons.com/files/icons/1072/face_avatars/300/a01_BLABLABLA.png } { status code: 404, headers { Connection = "keep-alive"; "Content-Encoding" = gzip; "Content-Language" = en; "Content-Type" = "text/html; charset=utf-8"; Date = "Fri, 23 Oct 2015 18:01:11 GMT"; Server = "gunicorn/0.17.4"; "Set-Cookie" = "csrftoken=81phPal08h22q6d87lC85TqCCOniJhhJ; expires=Fri, 21-Oct-2016 18:01:11 GMT; Max-Age=31449600; Path=/"; "Transfer-Encoding" = Identity; Vary = "Accept-Encoding, Cookie, Accept-Language"; } })
Upvotes: 0
Views: 504
Reputation: 534893
The response
is an NSHTTPURLResponse. If its statusCode
is 404
you have no data and should go no further.
The reason you're not getting an error is that there was no error; this is a perfectly valid and complete communication back and forth across the network.
Upvotes: 1