![](/img/trans.png)
[英]How to download(save) an image from url into our photo album using angularjs?
[英]Download image directly to a photo album
目前,我正在使用Alamofire进行网络请求。 如何使用PHPhotoLibrary
的Photos.framework
将图像直接下载到已经存在的Photos.framework
?
PS:我不介意使用NSURLSession
本身解决方案。
注意事项:该文件不能暂时存储在磁盘中。 我想要将数据存储在内存中,然后使用Photos.framework
将其保存到磁盘一次。
我自己弄清楚。 我用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.