Des*_*ume 12 ios alassetslibrary swift photokit
ALAssetsLibrary这些天已被弃用,但几乎所有关于SO的例子仍在使用它.为了我的目标,我需要知道添加到照片库的视频的URL,以便我可以将视频分享到Instagram应用程序(这是Instagram接受视频的唯一方式).URL应该以"assets-library:// ..."开头
这很简单ALAssetsLibrary:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) { // ...
Run Code Online (Sandbox Code Playgroud)
在上面,URL作为参数传递给完成块.但是iOS 9与PHPhotoLibrary类和performChanges方法的兼容方式呢?
var videoAssetPlaceholder:PHObjectPlaceholder! // property
// ...
let videoURL = NSBundle.mainBundle().URLForResource("Video_.mp4", withExtension: nil)!
let photoLibrary = PHPhotoLibrary.sharedPhotoLibrary()
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL)
self.videoAssetPlaceholder = request?.placeholderForCreatedAsset
},
completionHandler: { success, error in
if success
{
// The URL of the video asset?
}
})
Run Code Online (Sandbox Code Playgroud)
Des*_*ume 23
这就是我最终得到的结果:
let videoURL = NSBundle.mainBundle().URLForResource("Video_.mp4", withExtension: nil)!
let photoLibrary = PHPhotoLibrary.sharedPhotoLibrary()
var videoAssetPlaceholder:PHObjectPlaceholder!
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL)
videoAssetPlaceholder = request!.placeholderForCreatedAsset
},
completionHandler: { success, error in
if success {
let localID = videoAssetPlaceholder.localIdentifier
let assetID =
localID.stringByReplacingOccurrencesOfString(
"/.*", withString: "",
options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
let ext = "mp4"
let assetURLStr =
"assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
// Do something with assetURLStr
}
})
Run Code Online (Sandbox Code Playgroud)
小智 5
很好的答案和伪,谢谢德斯蒙德。
这是更新的答案:
雨燕3
var assetPlaceholder: PHObjectPlaceholder!
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL as URL!)
assetPlaceholder = assetRequest?.placeholderForCreatedAsset
}, completionHandler: { (success, error) in
if success {
let localID = assetPlaceholder.localIdentifier
let assetID = localID.replacingOccurrences(of: "/.*", with: "", options: NSString.CompareOptions.regularExpression, range: nil)
let ext = "mp4"
let assetURLStr = "assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
// Do what you want with your assetURLStr
} else {
if let errorMessage = error?.localizedDescription {
print(errorMessage)
}
}
})
Run Code Online (Sandbox Code Playgroud)
更进一步
虽然目前这工作得很好,但如果没有这个“手动”解决方案,有人知道一种“更干净”的方式来获取这个“资产库”URL吗?
我发现这个有趣的线程,但它只提供了一个“file:///var/...” URL