我目前正在尝试创建一个渐进式JPG加载器。当一个大图像传递到我的NSURLConnection时,它似乎会将图像的一半切掉。
这是我的didReceiveData
方法和数据分配给的图像:
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
if let img: UIImage = UIImage(data: data){
imageView.image = img
}
print("didReceiveData")
}
似乎跳过最后一块数据来完成图像。示例图像是:
此图片已完成传递给connectionDidFinishLoading
,但显然不是。任何人都有任何关于为什么会发生这种情况的想法?
答案 0 :(得分:0)
委托optional public func connection(connection: NSURLConnection, didReceiveData data: NSData)
假设是回调以递增方式加载数据。每次调用时,您都会收到新的可用数据。因此,如果您尝试使用接收的数据设置创建图像,则不会是已完成的图像。相反,你应该尝试这个
@IBOutlet weak var imageView: UIImageView!
var receivedData = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let imageURL = "https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/leisa_christmas_false_color.png?itok=75o-jlD5";
let request = NSURLRequest(URL: NSURL(string: imageURL)!)
let urlConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)
urlConnection?.start()
}
extension ViewController: NSURLConnectionDelegate, NSURLConnectionDataDelegate {
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.receivedData.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection) {
self.imageView.image = UIImage(data: receivedData)
}
}
我希望这会对你有所帮助。