从assets-library URL获取NSData

我正试图从设备库中获取mp4文件中的NSData。

此链接如下所示:

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

我试过这段代码:

 ALAssetRepresentation *rep = [asset defaultRepresentation]; Byte *buffer = (Byte*)malloc((NSUInteger)rep.size); NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil]; NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; 

但是在iOS 9中不推荐使用defaultRepresentation

我也试过[NSData dataWithContentsOfFile:url]; 但它返回零。

在iOS 9中不推荐使用整个ALAsset类。您现在应该考虑使用PHAsset 。 有一个API可以从旧资产URL ALAsset 。 请参阅以下内容 :

资产库框架在iOS 8.0及更高版本中已弃用,取而代之的是Photos框架。 如果您的应用程序先前已存储来自ALAsset对象的URL,并且您需要检索相应的Photos框架对象,请使用此方法。

 + (PHFetchResult *)fetchAssetsWithALAssetURLs:(NSArray *)assetURLs options:(PHFetchOptions *)options 

然后你可以在PHImageManager使用以下方法来获取PHImageManagerNSData

 - (PHImageRequestID)requestImageDataForAsset:(PHAsset *)asset options:(PHImageRequestOptions *)options resultHandler:(void (^)(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info))resultHandler 

Swift 3:1。从照片库中请求资产2.从资产3请求数据。返回块

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

示例使用:

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