【问题标题】:Download image directly to a photo album直接下载图片到相册
【发布时间】:2016-05-25 07:32:12
【问题描述】:

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

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

注意事项:该文件暂时不能存储在磁盘中。我想要内存中的数据并使用Photos.framework将其保存到磁盘中一次。

【问题讨论】:

    标签: ios networking alamofire nsurlsession


    【解决方案1】:

    我自己想办法。我用来自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
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多