获取新创建的资源的URL,iOS 9样式
获取新创建的资源的URL,iOS 9样式,ios,swift,alassetslibrary,photokit,Ios,Swift,Alassetslibrary,Photokit,ALAssetsLibrary近来已被弃用,但几乎所有的示例都在使用它。为了实现我的目标,我需要知道添加到照片库中的视频的URL,以便我可以将视频共享到Instagram应用程序(这是Instagram接受视频的唯一方式)。URL可能应该以“资产”开头-library://..." 使用库,这很简单: ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosA
ALAssetsLibrary
近来已被弃用,但几乎所有的示例都在使用它。为了实现我的目标,我需要知道添加到照片库中的视频的URL,以便我可以将视频共享到Instagram应用程序(这是Instagram接受视频的唯一方式)。URL可能应该以“资产”开头-library://..."
使用库
,这很简单:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) { // ...
在上面,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?
}
})
以下是我的结论:
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
}
})
很好的回答和伪,谢谢Desmond 以下是最新的答案: 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)
}
}
})
更进一步
尽管目前这种方法非常有效,但如果没有这种“手动”解决方案,有人知道一种“更干净”的方法来获取“资产库”URL吗
我找到了这个,但它只提供了一个“file:///var/...“URL为什么不先将视频保存在本地,然后再共享?@LeoDabus视频共享的方式,Instagram无法从我的应用程序的沙盒中读取视频。