Convert AVPlayerItem to NSData - ios

I am trying to achieve a simple task like converting a UIImage to NSData, for AVPlayerItem that is returned to me when I select a video from the PHImageManager. What might be an equivalent of the UIImagePNGRepresentation to convert video in data:
PHVideoRequestOptions *videoRequestOptions = [[PHVideoRequestOptions alloc] init];
videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
videoRequestOptions.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:videoRequestOptions resultHandler:^(AVPlayerItem *item, NSDictionary *info)
{
//?
}];
Whereas the UIImage goes like this:
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:imageRequestOptions resultHandler:^(UIImage *result, NSDictionary *info)
{
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(result)]; //<==THIS
}

The solution is to get the URL from the AVPlayerItem asset, then create NSData from that URL:
PHAsset *asset = ...
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
[[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
NSURL *fileURL = [(AVURLAsset *)playerItem.asset URL];
NSData *videoData = [NSData dataWithContentsOfURL:fileURL];
NSLog(#"tmpData Size: %lu",tmpData.length);
}];
and another way is to use 'requestAVAssetForVideo:asset' ....
PHFetchOptions *fetchOption = [[PHFetchOptions alloc]init];
if ([fetchOption respondsToSelector:#selector(setFetchLimit:)]) {
[fetchOption setFetchLimit:1];
}
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:#[#"<Video-localIdentifier>"] options:fetchOption].firstObject;
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc]init];
options.version = PHVideoRequestOptionsVersionOriginal;
options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset
options:options
resultHandler:
^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
AVURLAsset *urlAsset = (AVURLAsset *)asset;
NSData *videoData = [NSData dataWithContentsOfURL:urlAsset.URL];
if (videoData) {
NSLog(#"videoData Size: %lu", videoData.length);
}
}];

Related

How can i load image from Media Library using UIImagePicker results URL and PHAsset on IOS 9

PHImageManager *manager = [PHImageManager defaultManager];
for (PHAsset *asset in result) {
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
_profileImageView.image = image;
//[images addObject:_profileImageView];
}];
}
its not work for me
First make requestoptions like,
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
self.requestOptions.synchronous = true;
and if there are multiple assets in an array filled with PHAsset objects, then add this code:
self.assets = [NSMutableArray arrayWithArray:assets];
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[assets count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in self.assets) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
and now the images array contains all the images in uiimage format.
Hope this will help :)

Can't read some files from camera roll

I wrote simple library to get photos from camera roll. Unfortunately can't read some of them. I can't preview or convert to NSData
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary;
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
requestOptionForPhotos.networkAccessAllowed = YES;
for(PHAsset *asset in allPhotosResult) {
[[PHImageManager defaultManager]
requestImageForAsset:asset
targetSize:CGSizeMake(100, 100)
contentMode:PHImageContentModeAspectFill
options:requestOptionForPhotos
resultHandler:^(UIImage *result, NSDictionary *info) {
NSData *data = UIImagePNGRepresentation(result);
NSString *base = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; // for some of photos there is nil
}];
}

Can't read PHAsset content asynchronous

I want to read specified file (photo from camera roll) asynchronous, but it does not work for me.
Variable tempData gets nil untill I change config requestOptionForPhotos.synchronous to YES, then everything is ok, but I don't want to perform this code synchronous.
Is it possible that I'm blocking access to photo by requesting to the same file in other thread? I'm newbie in objective-c and iOS programming and I don't know how does it works.
NSURL *assetUrl = [[NSURL alloc] initWithString:filepath];
PHFetchResult *collection = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:assetUrl] options:nil];
PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
requestOptionForPhotos.networkAccessAllowed = YES;
requestOptionForPhotos.synchronous = NO;
__block BOOL isFinished = NO;
__block NSData * tempData = nil;
for(PHAsset *asset in collection) {
[[PHImageManager defaultManager]
requestImageForAsset:asset
targetSize:CGSizeMake(80, 80)
contentMode:PHImageContentModeAspectFill
options:requestOptionForPhotos
resultHandler:^(UIImage *result, NSDictionary *info) {
tempData = UIImagePNGRepresentation(result);
isFinished = YES;
}];
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
NSURL *assetUrl = [[NSURL alloc] initWithString:filepath];
PHFetchResult *collection = [PHAsset fetchAssetsWithALAssetURLs:[NSArray arrayWithObject:assetUrl] options:nil];
PHImageRequestOptions *requestOptionForPhotos = [[PHImageRequestOptions alloc] init];
requestOptionForPhotos.networkAccessAllowed = YES;
requestOptionForPhotos.synchronous = NO;
__block BOOL isFinished = NO;
__block NSData * tempData = nil;
for (PHAsset *asset in collection) {
[[PHImageManager defaultManager]
requestImageForAsset:asset
targetSize:CGSizeMake(80, 80)
contentMode:PHImageContentModeAspectFill
options:requestOptionForPhotos
resultHandler:^(UIImage *result, NSDictionary *info) {
tempData = UIImagePNGRepresentation(result);
isFinished = YES;
}];
}
});
try this code to get asynchronusly image and put breakpoint on result handdler to check weather you are getting image or not.

Can't read NSData for some photos

I want to get list of thumbnails of all my camera roll photos, but for some photos I can't read NSData.
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
for(PHAsset *asset in allPhotosResult) {
[[PHImageManager defaultManager]
requestImageForAsset:asset
targetSize:CGSizeMake(80, 80)
contentMode:PHImageContentModeAspectFill
options:nil
resultHandler:^(UIImage *result, NSDictionary *info) {
NSData *data = UIImagePNGRepresentation(result); // nil for some photos
NSString *base = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}];
}

How to save multiple videos into application document directory?

I am using GMImagePicker to fetch assets of camera roll.
After selecting single or multiple videos i got PHAsset in arrayArray.
assetArray data in this formate
"<PHAsset: 0x7fe0e8f21130> 40D4733D-4C7B-443D-8093-C28E39ACA45E/L0/001 mediaType=2/0, sourceType=1, (720x480), creationDate=2016-02-14 09:50:58 +0000, location=0, hidden=0, favorite=0 "
How can i store this video into my application document directory?
The code i did to store video is
for (PHAsset *asset in assetArray) {
if (asset.mediaType==PHAssetMediaTypeVideo) {
NSLog(#"Video found");
}
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *URL = [(AVURLAsset *)asset URL];
NSMutableData *responseData=[[NSMutableData alloc] init];
responseData = [NSMutableData dataWithContentsOfURL:URL];
if (responseData.length>0) {
NSString * lastPath = [URL.absoluteString lastPathComponent];//videoname.mp4
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirPath,lastPath];
[responseData writeToFile:filePath atomically:YES];
}
}];
}
I also checked filepath where video is saved. Video is available but i get this error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
Please help me to solve this.
According to me use NSMutableData instead of NSData it's accept Nullable value
self.responseData = [NSMutableData dataWithContentsOfURL:location];
if (self.responseData.length>0) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString * lastPath = [url.absoluteString lastPathComponent];//videoname.mp4
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirPath,lastPath];
[self.responseData writeToFile:filePath atomically:YES];
}
});
hope this help you.
For storing both Images And Video
for (PHAsset *asset in assetArray) {
if (asset.mediaType==PHAssetMediaTypeVideo) {
NSLog(#"Video found");
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *URL = [(AVURLAsset *)asset URL];
[Albumvideos addObject:URL];
NSData *videoData = [NSData dataWithContentsOfURL:URL];
if (videoData.length>0) {
NSString *lastPath = [URL.absoluteString lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#-%#",TimeStamp,lastPath]];
[fileManager createFileAtPath:fullPath contents:videoData attributes:nil];
}
}
}];
}
else{
self.requestOptions = [[PHImageRequestOptions alloc] init];
self.requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
self.requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
// this one is key
self.requestOptions.synchronous = true;
// self.assets = [NSMutableArray arrayWithArray:assets];
PHImageManager *manager = [PHImageManager defaultManager];
// assets contains PHAsset objects.
__block UIImage *ima;
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:self.requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[Albumimages addObject:ima];
}];
}
}
Albumvideos is mutable array which contain video URL and Albumimages contain selected images.

Resources