How to save video from assets url - iphone

I want to save video to my app document from asset url. My asset url is as follows:-
"assets-library://asset/asset.MOV?id=1000000394&ext=MOV"
I tried this:-
NSString *str=#"assets-library://asset/asset.MOV?id=1000000394&ext=MOV";
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[videoData writeToFile:mypath atomically:YES];
but on the second line [NSData dataWithContentsOfURL:[NSURL URLWithString:str]] i got program crash with this reason:-
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL length]: unrecognized selector sent to instance
I want to know how to access asset video url.
Thanx for any help.

I think your best bet is to use the method
getBytes:fromOffset:length:error:
of
ALAssetRepresentation
You can get the default representation of an asset like so
ALAssetRepresentation *representation = [someVideoAsset defaultRepresentation];
So off the top of my head it should go something like this (I'm away from my Mac so this hasn't been tested)
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:videoUrl resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
[data writeToFile:filePath atomically:YES];
} errorBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
}];
Where videoUrl is the asset url of the video you're trying to copy, and filePath is the path where you're trying to save it to.

thanks for this.. all i needed to change was
errorBlock:^(NSError *err)
to this:
failureBlock :^(NSError *err)

Related

UIImage gets corrupted while Downloading

I have developed iOS App, in which i am downloading image from server and saving it in my Document directory.
But problem which i am facing is, sometimes my images getting corrupted when i download, even if the server response isSuccessful.
Here is my code snippet,
urlFile is path of UIImage which is on server e.g: www.abcd.com/images/pqr.jpg
fileName which i am using for saving image name in my DocDirectory.
- (void)downloadFile:(NSString *)urlFile withName:(NSString *)fileName
{
NSString *trimmedString = [urlFile stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"trimmedString=%#",trimmedString);
if ([trimmedString length]>0)
{
HTTPEaterResponse *response = [HTTPEater get:[NSString stringWithFormat:#"%#",trimmedString]];
if ([response isSuccessful])
{
NSLog(#"isSuccessful");
[self saveImage:[[UIImage alloc] initWithData:[response body]] withName:fileName];
} else {
NSLog(#"Url response failed %#", [response description]);
}
}
}
- (void)saveImage:(UIImage *)image withName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *data = UIImagePNGRepresentation(image);
NSLog(#"image =%#",image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
When i see my Log, it shows:
trimmedString= www.abcd.com/images/pqr.jpg
isSuccessful
image =null
Thanks in advance.
I use the following code and it works for me.
NSData *thumbImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]];
[thumbImageData writeToFile:cachedThumbnailFileName atomically:YES];
UIImage * image = [UIImage imageWithContentsOfFile:cachedThumbnailFileName];
imageView.image = image;
Hope it helps you. :)
To save image on directory use:
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.jpg"];
[UIImagePNGRepresentation(selectedImage) writeToFile:pngPath atomically:YES];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
have you logged the response [response body]?
Just try to convert that response as NSData and then save as image.
Using Base64Encoding class,you can convert the response as base64Data
NSData *imageData = [NSString base64DataFromString:[response body]];
[self saveImage:[[UIImage alloc] initWithData:imageData] withName:fileName];
i suggest yo use SDWebimage Class SDWebimage download.. i think its very helpful to you even i always prefer SDWebimage Library.
this are the some things.
An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
instead u can use, "NSURLRequest" and "NSURLConnection"
for example if u get image URL then,
NSURL* aURL = [NSURL URLWithString:trimmedString];//get the url of string
NSURLRequest *aReq = [NSURLRequest requestWithURL:aURL];
NSURLConnection *aConnection = [NSURLConnection connectionWithRequest:aReq delegate:self]; //get a connection to url , since it confirms to delegate u need to implement delegate methods
if(aConnection == nil) //if it is nil then cancel and close the request
{
aConnection = nil;
[aConnection cancel];
}
// after this implement this delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)received_data
{
if(image_data == nil) //if data is not initialised initialise it
{
image_data = [[NSMutableData alloc]init];
}
[self.image_data appendData:received_data];//append the received data
}
//this method is called after successful download of the image
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
// UIImage* sampleImage = [UIImage imageWithData:self.image_data];
// self.image = sampleImage; //convert the data to image
//since u hav complete downloaded date in "self.image_data"
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"/myImage.png"];//set the name of the image and path may it saving in application directory check it out
[self.image_data writeToFile:imagePath atomically:YES]; //saving the data with name
}
Hope this helps u :)

image retrieving in sqlite

I am using using sqlite in my project
Previously I had saved image in data but now I am saving image in bytes like following code
NSUInteger len = [entObject.photoImageData length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [entObject.photoImageData bytes], len);
insertString = [NSString stringWithFormat:#"INSERT INTO TBL_COUNTDOWN (DAIRYID,EVENTID,DESCRIPTION,EVENTIMAGE) VALUES (\"%#\",\"%d\",\"No Data\",\"%s\")",self.dairyId,self.eventId,byteData];
For retrieving image I am using following code
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 3) length: sqlite3_column_bytes(statement, 3)];
NSLog(#"dataForCachedImage/getAllEvents is %#",dataForCachedImage);
UIImage *cachedImage = [UIImage imageWithData:dataForCachedImage];
NSLog(#"cachedImage/getAllEvents is %#",cachedImage);
For dataForCachedImage in NSLog I am getting data but for cachedImage I getting null
I dont no whats wrong in my code. Please help me
Thanks in advance
You can save image to document directory and store its path to sqlite database
save Image code is as follows
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]
// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
NSString *filePath= [NSString stringWithFormat:#"%#/%#.jpg", DOCUMENTS_FOLDER,caldate];
NSURL *url = [NSURL fileURLWithPath:filePath];
UIImage *image = [UIImage imageNamed:#"name.jpg"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
anytime you want to retrieve Image then get it then use following method to getImage
- (UIImage*)getImage
{
NSString *imagePath = [DOCUMENTS_FOLDER stringByAppendingPathComponent:#"imagename.jpg"];
UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
return img;
}
deleting file
NSFileManager *fileManager=[NSFileManager defaultManager];
[fileManager removeItemAtPath:savedFilePath error:nil];
may this will help you..

Getting NSData from an NSURL

I am trying to upload a photo from my app into a web service.
The flow I am attempting to create is as follows:
User takes photo with camera
Photo is saved to camera roll under a custom album
URL of the saved photo is given to my store
Store attempts to upload the photo to a web service.
I am trying to use NSData *data = [NSData dataWithContentsOfURL:[item assetURL]] where item is a model that contains the URL concerned. But this line is not producing a data when I log it even if it produces a URL: "assets-library://asset/asset.PNG?id=28DBC0AC-21FF-4560-A9D6-5F4BCA190BDB&ext=PNG"
The code snippets are as follows:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^(void){
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:image.imageOrientation completionBlock:^(NSURL* assetURL, NSError* error) {
BCard *card = [[BCard alloc]init];
//error handling
if (error!=nil) {
NSLog(#"[ERROR] - %#",error);
return;
}
//add the asset to the custom photo album
[library addAssetURL: assetURL
toAlbum:#"Business Cards"
withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"Custom Album Error: %#", [error description]);
}
}];
[card setAssetURL:assetURL];
[[BCardStore sharedStore]addToQueue:card];
int index = [[[BCardStore sharedStore]getQueue]count]-1;
[[BCardStore sharedStore]uploadItemAtIndex:index withProgressBlock:nil withExitBlock:nil];
}];
}];
}
and
-(void)uploadItemAtIndex:(NSUInteger)index withProgressBlock:(progressBlock)pBlock withExitBlock:(exitBlock)eBlock
{
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
NSData *data = [NSData dataWithContentsOfURL:[item assetURL]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
NSLog(#"%#",[item assetURL]);
//upload data using AFNetworking here
}
The snippet [library addAssetUrl:NSUrl toAlbum:NSString withCompletionBlock:^(NSError *error)] came from the category I found here.
Am I really getting the right URL here or am I using dataWithContentsOfURL incorrectly?
The only way is You can retrieve the UIImage from Photo-Library using ALAsset URL and convert in to NSData.
Add ALAssetLibrary
Import ALAssetLibrary header file
-(void)uploadItemAtIndex:(NSUInteger)index
withProgressBlock:(progressBlock)pBlock
withExitBlock:(exitBlock)eBlock
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep;
if([myasset defaultRepresentation] == nil) {
return;
} else {
rep = [myasset defaultRepresentation];
}
CGImageRef iref = [rep fullResolutionImage];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *myImage = [UIImage imageWithCGImage:iref];
NSData *data = //convert the myImage to NSData
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
//upload data using AFNetworking here
});//end block
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Cant get image - %#",[myerror localizedDescription]);
};
NSURL *asseturl =
[NSURL URLWithString:[self.photoPath objectAtIndex:[arrayIndex intValue] ]];
//using ARC , you have to declare ALAssetsLibrary as member variable
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL
resultBlock:resultblock
failureBlock:failureblock];
}

Get photo file with metadata from album photo

It is possible to retrieve photo file from the album photo with metadata (IPTC)?
I've tried UIImagePickerController to get UIImage and when I save it to a file, it doesn't contain any metadata information.
There is a way to get the original photo file with ALAsset library?
I found a solution with AssetsLibrary:
- (void)savePhoto:(NSURL*) url <br
{
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
NSString* originalFileName = [[asset defaultRepresentation] filename];
NSString *path = [applicationDocumentsDir stringByAppendingPathComponent:originalFileName];
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
//NSLog(#"%#",data);
[data writeToFile:path atomically:YES];
} failureBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
}];
}

iphone: NSDATA dataWithContentsOfURL returning null

I have a problem of getting NSData via [NSData dataWithContentsOfURL: url] and giving me an null object where the url is the NSURL got it from defaultRepresentation of the asset.. The url in the NSURL is :
assets-library://asset/asset.JPG?id=1000000366&ext=JPG
I went to other forum, they talked about something like file url... Do I have to convert the url to file path ?
But i can have the thumbnail of the ALAsset on a view.
Does anyone know why i get null NSData object?
from what I know these URLs are just for identification or so - you cannot actually access them.
maybe this helps ?
ALAsset , send a photo to a web service including its exif data
If what you're after is the image, you could do something like this...
ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
NSURL *yourAssetUrl = ;//Insert Your ALAsset's URL here
[library assetForURL:yourAssetUrl resultBlock:^(ALAsset *asset) {
if (asset) {
ALAssetRepresentation *imgRepresentation = [asset defaultRepresentation];
CGImageRef imgRef = [imgRepresentation fullScreenImage];
UIImage *img = [UIImage imageWithCGImage:imgRef];
CGImageRelease(imgRef);
[self doSomethingWithImage:img];
}
} failureBlock:^(NSError *error) {
}];