2015-11-23 79 views
3

我想從設備庫的mp4文件中獲取NSData。從資產庫URL獲取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]; 

defaultRepresentation在iOS版9

棄用我也試過[NSData dataWithContentsOfFile:url];但它返回零。

+2

棄用=不存在的! – Lefteris

回答

1

ALAsset的整個等級在iOS 9中已棄用。現在應該考慮使用PHAsset來代替。有一個API可以從舊資產網址ALAsset中獲取PHAsset。請參閱following

資產庫框架在iOS 8.0及更高版本中被棄用,取而代之的是照片框架。如果您的應用程序以前存儲過ALAsset對象的URL,並且您需要檢索相應的照片框架對象,請使用此方法。

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

然後你可以使用下面的PHImageManagermethod得到PHAssetNSData:從照片庫 2.請求數據 1.請求資產:

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

斯威夫特3來自資產 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 
     } 
    }