获取新创建资产的 URL,iOS 9 风格
Posted
技术标签:
【中文标题】获取新创建资产的 URL,iOS 9 风格【英文标题】:Get URL of a newly created asset, iOS 9 style 【发布时间】:2016-01-13 18:53:27 【问题描述】:ALAssetsLibrary
这些天已被弃用,但实际上所有关于 SO 的示例仍在使用它。为了我的目标,我需要知道添加到照片库的视频的 URL,以便我可以将视频分享到 Instagram 应用程序(这是 Instagram 接受视频的唯一方式)。 URL 应该以“assets-library://...”开头
这很简单ALAssetsLibrary
:
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?
)
【问题讨论】:
为什么不先将视频保存在本地,然后再分享? @LeoDabus 分享视频的方式,Instagram 将无法从我的应用程序的沙箱中读取视频 【参考方案1】:这是我最终得到的结果:
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
)
【讨论】:
效果很好。【参考方案2】:很好的答案和伪,谢谢德斯蒙德。
这是一个更新的答案:
斯威夫特 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/...”网址
【讨论】:
以上是关于获取新创建资产的 URL,iOS 9 风格的主要内容,如果未能解决你的问题,请参考以下文章
IOS - UIWebview - 获取点击链接的 URL 并编辑 url