如何使用NSURlConnection从Url下载图像以保存在手机缓存中

时间:2016-11-04 09:41:34

标签: ios swift xcode nsurlconnection

我正在使用NSUrlconnection来调用api,但现在我也从api接收图像所以我不知道如何加载图像&保存到手机本地内存,因为这些图像在应用程序中进一步使用。请帮我。如何使用&从本地保存显示图像。我使用下面的函数来加载图像,但是NSURLSession.sharedSession()不会进入队列。

 func saveImage(url:NSString,image_name1:NSString)
    {
        NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url as String)!, completionHandler: { (data, response, error) -> Void in

                        if error != nil {
                            print(error)
                            return
                        }
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            let image = UIImage(data: data!)
                            var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
                            let documentsDirectory = paths[0]
                            let path = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent(image_name1 as String)!.absoluteString
                            print(" file path is \(path)")
                            let data = UIImagePNGRepresentation(image!)
                            data!.writeToFile(path!, atomically: true)

                        })

                    }).resume()



   }

2 个答案:

答案 0 :(得分:0)

用于保存

var image = ....  // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)

现金

https://github.com/onevcat/Kingfisher

pod'Gingfisher'

let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)

这是自动现金图片

答案 1 :(得分:0)

试试这个:

let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageView.image = UIImage(data: data!)

来自:https://stackoverflow.com/a/27517280/3901620