Get NSData from assets-library URL

后端 未结 2 1356
广开言路
广开言路 2021-01-06 18:42

I\'m trying to get NSData from mp4 file from device library.

This link look like this:

assets-library://asset/asset.mp4?id=32515720-939A-456F-958F-0B         


        
相关标签:
2条回答
  • 2021-01-06 18:56

    Swift 3: 1. Request Asset from Photos Library 2. Request Data from Asset 3. Return block

       func getDataFromAssetAtUrl( assetUrl: URL, success: @escaping (_ data: NSData) -> ()){
        let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [assetUrl], options: nil)
        if let phAsset = fetchResult.firstObject {
            PHImageManager.default().requestImageData(for: phAsset, options: nil) {
                (imageData, dataURI, orientation, info) -> Void in
                if let imageDataExists = imageData {
                    success(imageDataExists as NSData)
                }
            }
        }
    }
    

    example use:

    import Photos //this on top of your file
    
    open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
            dismiss(animated: true, completion: nil)
            let assetUrl = assetDataFromMediaInfo(info: info)!
            getDataFromAssetAtUrl(assetUrl: assetUrl) { (dataOfAsset) in
                //TODO do something with NSData
            }
        }
    
    0 讨论(0)
  • 2021-01-06 19:09

    The entire class of of ALAsset is deprecated in iOS 9. You should now consider using PHAsset instead. There is a API to get the PHAsset from the old asset url ALAsset. See the following:

    The Assets Library framework is deprecated in iOS 8.0 and later, replaced by the Photos framework. Use this method if your app has previously stored URLs from ALAsset objects and you need to retrieve the corresponding Photos framework objects.

    + (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs
                                                     options:(PHFetchOptions *)options
    

    And then you could use the following method in PHImageManager to get the NSData of the PHAsset:

    - (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset
                                         options:(PHImageRequestOptions *)options
                                   resultHandler:(void (^)(NSData *imageData,
                                                           NSString *dataUTI,
                                                           UIImageOrientation orientation,
                                                           NSDictionary *info))resultHandler
    
    0 讨论(0)
提交回复
热议问题