2016-01-13 16 views
6

ALAssetsLibrary這些日子已被棄用,但幾乎所有的例子都在使用它。對於我的目標,我需要知道添加到照片庫的視頻的URL,以便我可以將視頻分享到Instagram應用(這是Instagram接受視頻的唯一方式)。該URL或許應該開始「資產庫:// ...」獲取新創建的資產的URL,iOS 9風格

這是ALAssetsLibrary簡單:

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

上面,URL作爲參數來完成塊傳遞。但是iOS9兼容方式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? 
    } 
}) 
+0

爲什麼你不只是在本地保存你的視頻分享之前? –

+0

@LeoDabus視頻共享的方式,Instagram無法從我的應用程序的沙箱中讀取視頻 –

回答

16

這裏是我已經結束了:

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

精美的作品。 – 209135

4

尼斯的答案,僞,感謝德斯蒙德。

這裏是一個更新的答案:

斯威夫特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,沒有這個「手動」的解決方案?

我發現這個interesting thread,但它只是提供了一個「文件:/// VAR/......」 URL