我对 swift 有点陌生。有人可以帮我解决我的问题。 我想从服务器下载图像。问题是并不是每个用户都上传了个人资料照片(例如,如果他在应用程序上注册了自己的新照片)。 现在,在我在应用程序上下载个人资料图片之前,我想检查服务器上是否存在该图片。 我怎么做? 这就是我所拥有的:
if let imageUrl = NSURL(string: "http://tes-soft.de/AppUserImages/\(Variablen.CurrentUser)_ProfilePic.jpg") {
let imageRequest: NSURLRequest = NSURLRequest(URL: imageUrl)
let queue: NSOperationQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(imageRequest, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if data != nil {
self.image = UIImage(data: data)!
let destinationPath = documentsPath.stringByAppendingPathComponent("ProfilePic.jpg")
UIImageJPEGRepresentation(self.image,1.0).writeToFile(destinationPath, atomically: true)
}
})
}
这里的问题是数据每次都不是空的,因为它会发回整个网站(如果不存在则为 404 页面)。 它适用于现有图像。
最佳答案
首先,我会切换到使用 NSURLSession。它为您提供了更多选项,例如后台下载,并且 NSURLConnection 已被弃用。
对于图像问题,您只是检查完成处理程序中的数据。由于 HTTP 是基于文本的,因此即使出现错误也会返回数据。您应该检查响应 header ,而不是查看您的请求是否以 404 或您的 Web 服务返回的任何错误代码响应。然后您知道是否应该继续下载图像。
关于ios - 快速下载图像(如果服务器上存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32668628/