iphonealassetslibraryalasset

Getting video from ALAsset


Using the new asset library framework available in iOS 4 i see that I can get the url for a given video using the UIImagePickerControllerReferenceURL. The url returned is in the following format:

assets-library://asset/asset.M4V?id=1000000004&ext=M4V

I am trying to upload this video to a website so as a quick proof of concept I am trying the following

NSData *data = [NSData dataWithContentsOfURL:videourl];
[data writeToFile:tmpfile atomically:NO];

Data is never initialized in this case. Has anyone managed to access the url directly via the new assets library? Thanks for your help.


Solution

  • Here is a clean swift solution to get videos as NSData. It uses the Photos framework as ALAssetLibrary is deprecated as of iOS9:

    IMPORTANT

    The Assets Library framework is deprecated as of iOS 9.0. Instead, use the Photos framework instead, which in iOS 8.0 and later provides more features and better performance for working with a user’s photo library. For more information, see Photos Framework Reference.

    import Photos
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        self.dismissViewControllerAnimated(true, completion: nil)
        
        if let referenceURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
            let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([referenceURL], options: nil)
            if let phAsset = fetchResult.firstObject as? PHAsset {
                PHImageManager.defaultManager().requestAVAssetForVideo(phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
                    if let asset = asset as? AVURLAsset {
                        let videoData = NSData(contentsOfURL: asset.URL)
                        
                        // optionally, write the video to the temp directory
                        let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV"
                        let videoURL = NSURL(fileURLWithPath: videoPath)
                        let writeResult = videoData?.writeToURL(videoURL, atomically: true)
                        
                        if let writeResult = writeResult where writeResult {
                            print("success")
                        }
                        else {
                            print("failure")
                        }
                    }
                })
            }
        }
    }