ALAssetsLibrary
这些天已被弃用,但几乎所有关于SO的例子仍在使用它。为了我的目标,我需要知道添加到照片库的视频的URL,以便我可以将视频分享到Instagram应用程序(这是Instagram接受视频的唯一方式)。 URL应该以" assets-library://..."
ALAssetsLibrary
:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) { // ...
在上面,URL作为参数传递给完成块。但是使用PHPhotoLibrary
类和performChanges
方法与iOS 9兼容的方式呢?
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?
}
})
答案 0 :(得分: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
}
})
答案 1 :(得分:4)
很好的答案和伪,谢谢戴斯蒙德。
以下是更新的答案:
Swift 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)
}
}
})
更进一步
虽然目前这种情况完美无缺,但如果没有这种“手动”解决方案,有人会知道“更清洁”的方式来获取这个“资产库”网址吗?
我找到了这个interesting thread,但它只提供了一个“file:/// var / ...”网址