0

我正在尝试从网络异步加载多个图像。看着我发现这个论坛帖子“从 Swift 上的 URL 加载/下载图像”,但我仍然有一些“问题”。

我有这个代码:

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()
        }
    }
}

问题

1)为了测试,我输入正确和错误的方向,但总是告诉我是正确的。 在此处输入图像描述

问题

1) 图像是否可以退回以供其他地方使用?

2) 如何检测 URL 无效并输入默认图片?

编辑

可选({ URL: http: //findicons.com/files/icons/1072/face_avatars/300/a03.png } {状态代码:200,标题 {“Accept-Ranges”=字节;连接=“keep-alive” ;“内容长度”= 32759;“内容类型”=“图像/png”;日期=“格林威治标准时间 2015 年 10 月 23 日星期五 14:20:20”;“上次修改时间”=“2010 年 2 月 11 日星期四 10 :49:27 GMT"; 服务器 = "nginx/1.1.19"; } })

可选({ URL: http: //findicons.com/files/icons/1072/face_avatars/300/a01_BLABLABLA.png } { 状态代码:404,标头 { Connection = "keep-alive"; "Content-Encoding" = gzip ;“内容语言”=en;“内容类型”=“文本/html;字符集=utf-8”;日期=“格林威治标准时间 2015 年 10 月 23 日星期五 18:01:11”;服务器 =“gunicorn/0.17. 4"; "Set-Cookie" = "csrftoken=81phPal08h22q6d87lC85TqCCOniJhhJ; expires=Fri, 21-Oct-2016 18:01:11 GMT; Max-Age=31449600; Path=/"; "Transfer-Encoding" = Identity; 变化= "接受编码、Cookie、接受语言"; } })

4

1 回答 1

1

response是一个 NSHTTPURLResponse。如果它statusCode404你没有数据,不应该再进一步。

您没有收到错误的原因是没有错误;这是通过网络来回完全有效且完整的通信。

于 2015-10-23T18:17:24.623 回答