2016-05-25 43 views
0

當前我正在使用Alamofire來處理網絡請求。我如何使用PHPhotoLibraryPhotos.framework直接將圖像下載到已存在的相冊中?將圖像直接下載到相冊

P.S .:我不介意使用NSURLSession本身的解決方案。

注意事項:文件暫時不能存儲在磁盤中。我想要內存中的數據並使用Photos.framework將其保存一次到磁盤中。

回答

0

我自己弄明白了。我使用NSURLSessiondataTaskWithRequest來實現它。

最初我以爲使用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 
    } 

}