获取新创build的资产的URL,iOS 9样式

ALAssetsLibrary这些日子已被弃用,但实际上所有的例子仍在使用它。 对于我的目标,我需要知道添加到照片库中的video的URL,以便我可以将video分享到Instagram应用(这是Instagram接受video的唯一方式)。 该URL可能应该以“assets-library:// …”开头

ALAssetsLibrary很简单:

 ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) { // ... 

以上,URL作为parameter passing给完成块。 但是,与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? } }) 

以下是我最后的结果:

 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 } }) 

好的回答和伪,谢谢德斯蒙德。

这是一个更新的答案:

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) } } }) 

走得更远

尽pipe目前这种做法是完美的,但是没有这种“手动”的解决scheme,谁能知道一个“更干净”的方式来获得这个“资产库”的URL?

我发现这个有趣的线程 ,但它只给出一个“file:/// var / …”的URL