直接将图像下载到相册

时间:2016-05-25 07:32:12

标签: ios networking alamofire nsurlsession

目前,我正在使用Alamofire进行网络请求。如何使用PHPhotoLibrary中的Photos.framework将图像直接下载到已存在的相册?

P.S。:我不介意单独使用NSURLSession解决方案。

注意事项:该文件暂时无法存储在磁盘中。我希望内存中的数据使用Photos.framework将其保存到磁盘中。

1 个答案:

答案 0 :(得分:0)

我自己弄清楚了。我使用dataTaskWithRequest中的NSURLSession实现了它。

最初我认为使用NSData(contentsOfURL:)contentsOfURL方法在整个文件传输之前不会返回。它应仅用于本地文件而不用于远程文件,因为如果您正在加载大型内容且设备连接速度较慢,则UI将被阻止。

// Avoid this!
let originalPhotoData = NSData(contentsOfURL: NSURL(string: "http://photo.jpg")!)

因此,可以使用数据任务将内容加载到NSData中。一种解决方案可以是:

let request = NSMutableURLRequest(URL: NSURL(string: urlString.URLString)!)
request.allHTTPHeaderFields = [
    "Content-Type": "image/jpeg"
]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    if let e = error {
        print(e.description)
        return
    }
    guard let image = UIImage(data: data) else {
        print("No image")
        return
    }
    // Success
    // Note: does not save into an album. I removed that code to be more concise.
    PHPhotoLibrary.sharedPhotoLibrary().performChanges {
        let creationRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
    }, completionHandler: { (success : Bool, error : NSError?) -> Void in
        if success == false, let e = error){
            print(e)
        }
    }
}
task.resume()

数据仅在最后阶段提供,但您可以使用会话代理访问数据并查看进度。

class Session: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate {

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let queue = NSOperationQueue.mainQueue()
    var session = NSURLSession()

    var buffer = NSMutableData()
    var expectedContentLength = 0

    override init() {
        super.init()
        session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: queue)
    }

    func dataTaskWithRequest(request: NSURLRequest) -> NSURLSessionDataTask {
        // The delegate is only called if you do not specify a completion block!
        return session.dataTaskWithRequest(request)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        buffer = NSMutableData()
        expectedContentLength = Int(response.expectedContentLength)
        print("Expected content length:", expectedContentLength)
        completionHandler(NSURLSessionResponseDisposition.Allow)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        buffer.appendData(data)
        let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)
        print("Progress: ", percentageDownloaded)
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        print("Finished with/without error \(error)")
        // Use the buffer to create the UIImage
    }

}