iphone: NSDATA dataWithContentsOfURL returning null - iphone

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) {
}];

Related

How to send UIImage in JSON format, by filling a NSDictionary

I'm trying to send data to a server with JSON.
I am able to create my NSDictionary with my objects and key parameters.
But I want to send my picture, and the picture is UIImage.
NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:
#"John",
#"First_Name",
#"McCintosh",
#"Last_name",
<HERE I WANT PICTURE>,
#"Profile_picture",
nil];
// Here I convert to NSDATA
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mainJSON options:NSJSONWritingPrettyPrinted error:&error];
// Sending operation :
dispatch_async(kBgQueue, ^
{
NSData * data = [NSData dataWithContentsOfURL:#"addresSERVER"];
[self performSelectorOnMainThread:#selector(receivedResponseFromServer:)
withObject:data
waitUntilDone:YES];
}
);
So I'm wondering how can I add my picture in my NSDictionary?
Because I want to send the content of my picture. If I add my object UIImage... I'll send the whole object right?
Thanks
You should convert the UIImage to NSString. Use the category of NSData called NSDataAdditions.You can find here:
NSDataAdditions category
How to Use:
//Convert an Image to String
UIImage *anImage;
NSString imageString = [UIImagePNGRepresentation(anImage) base64Encoding];
//To retrieve
NSData *data = [NSData dataWithBase64EncodedString:imageString];
UIImage *recoverImage = [[UIImage imageWithData:data];
I wouldn't typically post an image using JSON. Although it is technically possible to encode an image into text, I don't think that's how JSON is intended to be used and I would personally avoid the practice.
Deal with images as NSData. That's what they are. There are tons of examples online that illustrate how to do this.
One common approach is to upload an image to a web server, then take the URL of the uploaded image and add that to your JSON dictionary, such that your submitted JSON dictionary carries a string representing the URL of the image to download -- not the image itself.
You can try send UIImage with NSString like this:
Swift 3:
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
var encodedString = jpegData.base64EncodedString()
var mainJSON = [
"First_Name" : "John",
"Last_name" : "McCintosh",
"Profile_picture" : encodedString
]
}
Objective-c:
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64Encoding];
NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:
#"John",
#"First_Name",
#"McCintosh",
#"Last_name",
encodedString,
#"Profile_picture",
nil];
This is Base64 format so you can decode this in any language
Okay, Thansk to #tolgamorf and #isaac, I tried using AFNetwork.
I could do what I want. It's powerful and simple.
NSURL *url = [NSURL URLWithString:#"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"avatar" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
I took the code from official documentation from here .
Enjoy

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

How to save video from assets url

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)

help needed with adding picture from url!

i've managed to incorporate the twitter api into my app and i can call all the data and put it into my app, except for the image.
i've managed to find tuts on how to get the picture if you provide the url, but i want to get the addy from my dictionary to then be put into my uiimageview.
Any help would be appreciated, here is what i have sourced
NSData *imageData =
[[NSData alloc] initWithContentsOfUrl:
[NSString
stringWithContentsOfUrl:
[NSURL URLWithString:#"http://mydomain.com"]
encoding: NSUTF8StringEncoding
error: nil
]
];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[marcaBackground setImage:image];
[imageData release];
[image release];
this is what i have already set up`-(NSString*)author {
return [[contents objectForKey:#"user"] objectForKey:#"screen_name"];
`
NSString *author=[(Tweet*)[auth objectAtIndex:indexPath.row] author];
could someone please advise me on what needs changing for it to work??
NSData *imageData = [[NSData alloc] initWithContentsOfUrl: [NSURL URLWithString:#"http://..."]];
The rest is correct.

how can i display image from url?

I have a string variable tmpImgURLStr which contains URL like www.abc.com/img.png. i want to display that image in my imageView for that i have use some code but it's not working which is given below:
NSLog(#"Img URL === %#",tmpImgURLStr);
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",tmpImgURLStr]]];
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
[logoImg setImage:myimage];
As far as I can tell from your url - you have pdf, not an image. Usually WebViews are used for displaying this sort of data.
Update
Your NSData initiation is kinda too long. You can actually initiate a URL without supplying formatted string:
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:tmpImgURLStr]];
Also I've noticed that your URL is without protocol. You may want to try adding http:// or https:// to it and then see what happens. And just in case check if your logoImg is actually wired to the NSImageView in your NIB.
Try this
NSURL *imageurl = [NSURL URLWithString:#"http://www.chakrainteractive.com/mob/ImageUpoad/pic2-2.png"];
NSData *imagedata = [[NSData alloc]initWithContentsOfURL:imageurl];
UIImage *image = [UIImage imageWithData: imagedata];
[logoImg setImage: image];
Try this code instead of yours .. May be it will work..
logoImg=[[IUImageView alloc]initWithFrame:CGRectMake(10,10,300,460)];
NSLog(#"Img URL === %#",tmpImgURLStr);
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:tmpImgURLStr]]];
UIImage *myimage = [[UIImage alloc] initWithData:mydata];
[logoImg setImage:myimage];
-Happy coding....