iosswiftfacebook-ios-sdkalassetfbsdk

How to convert a video NSURL to an ALAsset?


Facebook sharing requires an ALAsset such as the following:

let content = FBSDKShareVideoContent()

//The videos must be less than 12MB in size.

let bundle = NSBundle.mainBundle()
let path = bundle.URLForResource("a", withExtension: "mp4")

let video = FBSDKShareVideo()
// doesn't work; needs to be an "asset url" (ALAsset)
//video.videoURL = path

content.video = video

let dialog = FBSDKShareDialog()
dialog.shareContent = content
dialog.show()

How is it possible to take a local bundle document, or an NSData object, and convert it to an ALAsset?

(My initial thinking was saving the video to the local camera roll, and then loading the list and selecting it, but that is unnecessary interface steps)


Solution

  • The documentation for an ALAsset states that

    An ALAsset object represents a photo or a video managed by the Photo application.

    so I'm pretty sure that you have to write the video to the camera roll before using it as an ALAsset. However, you don't need to open the camera roll and have a user pick the asset in order to use it. When writing to the ALAssetLibrary using

    library.writeVideoAtPathToSavedPhotosAlbum(movieURL, completionBlock: { (newURL, error) -> Void
    

    you get the asset url in that newUrl completion block variable. Use it in the Facebook sharing call

    let content = FBSDKShareVideoContent()
    content.video = FBSDKShareVideo(videoURL: newURL)
    
    FBSDKShareAPI.shareWithContent(content, delegate: self)
    NSLog("Facebook content shared \(content.video.videoURL)")
    

    You can do this sharing inside the completion block if you so desire, or you can save the newUrl from the completion block and use it somewhere else.