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

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

Related

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

Iphone dev : how can I get a result from google currency converter?

Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.
I have already tried something like that :
-(IBAction)getResponse:(id) sender{
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil && data != ""){
NSString *response = [[[NSString alloc] initWithData:data]]
[label setText: response];
}
else [label setText:#"not working"];
}
But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.
Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract
<div id=currency_converter_result>1 USD = <span class=bld>0.6118 GBP</span>
Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR
This URL will return the JSON
{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}
Just parse it. :)
Try...
NSData *data = [[NSData alloc] init];
Then check you've got something in response
NSLog(#"%#", response);
Better yet, remove the NSData alloc/init
Replace with
 
NSData *data=[NSData dataWithContentsOfURL:myURL];
And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.
You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
[label setText: responseString];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error]; //you can log the error description
[label setText:#"not working"];
}
NSString *myURLString = #"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";
NSURL *myURL = [NSURL URLWithString: myURLString];
NSData *data = [NSData alloc];
data=[NSData dataWithContentsOfURL:myURL];
if(data!=nil){
NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
NSLog(#"%#",response);
}
Try this.
This API is giving HTML responce.

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.

HTTP Post using JSON for UIImage

I am attempting to leverage http POST to send a JSON object (UIImage is included in POST). Below is the code I am currently using, but for some reason the server is not receiving the POST. Can anyone provide insight as to why this may not be working?
NSString *userString = [[NSString alloc]init];
userString = [[NSUserDefaults standardUserDefaults]valueForKey:#"userId"];
//convert image to nsdata object
NSData *imageData = UIImageJPEGRepresentation(imageView.image, .9);
NSLog(#"User id is:%#", userString);
NSLog(#"The tag string:%#", myTagString);
NSLog(#"the question string is:%#", myQuestionString);
NSLog(#"the image data is:%#", imageData);
NSArray *keys = [NSArray arrayWithObjects:#"category", #"question", #"latitude", #"longitude", #"user_id", #"image",nil];
NSArray *objects = [NSArray arrayWithObjects:myTagString, myQuestionString, #"0.0", #"0.0", userString, imageData, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *theURL = [NSURL URLWithString:#"http://theserver.com/query"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json-rpc" forHTTPHeaderField:#"Content-Type"];
NSString *theBodyString = [[NSString alloc]init];
theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(#"body string: %#", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"body data: %#", theBodyData);
[theRequest setHTTPBody:theBodyData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"the response string:%#", theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseData error:nil];
NSLog(#"%#", theResponseDictionary);
This is my first post in a forum so I apologize if some of the formatting is wrong. Feel free to critique it so I can submit better posts in the future.
Take a look at the code in this project of mine in Github http://akos.ma/7qp where the Wrapper class sets a couple of headers in the request, so that the server can process the binary data being uploaded. Look at the uploadData:toUrl: method in line 118, which sets the required content type headers.

Continuous conversion of text to speech from json data

I am designing an app that needs text to speech. I am using the library that is posted here to convert text to speech. I have to retrieve text from Json url, and pass the values to text to speech. I am able to retrieve Json data and convert it to text to speech for the ObjectatIndex 0 using the following code...
SBJSON *json = [[SBJSON alloc]init];
fliteEngine = [[FliteTTS alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.sampleurl.txt"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *jsonstring = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
NSArray *asanasList = [json objectWithString:jsonstring error:nil];
NSArray *asanas =[asanasList objectForKey:#"yogagurubackpain"];
for(NSDictionary *test in asanas)
{
UrlValues *myasanas = [[UrlValues alloc]init];
myasanas.asanatitle = [test objectForKey:#"asanatitle"];
myasanas.asanatranscript = [test objectForKey:#"asanatranscript"];
myasanas.asanapicture = [test objectForKey:#"asanapicture"];
[data.yoga addObject:myasanas];
[myasanas release];
}
UrlValues *asana=[[data yoga]objectAtIndex:0];
self.AsanaName.text = [asana asanatitle];
self.AsanaTranscript.text = [asana asanatranscript];
NSString *imageUrl = [asana asanapicture];
NSString* mapUrl = [imageUrl stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mapUrl]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
self.AsanaImage.image = image;
NSString *speak = self.AsanaTranscript.text;
[fliteEngine setVoice:#"cmu_us_rms"];
[fliteEngine speakText:speak];
[fliteEngine setPitch:100.0 variance:11.0 speed:0.4];
[imageData release];
[image release];
[jsonstring release];
[json release];
Now my problem is how can i go to the next object automatically after completion of the playing of first one. The process must continue for all the objects. The corresponding images etc must load on the page after the text to speech is done for the first one... Plz help me...
Looking at the source of the linked library, it looks like you'll have to hack a method into FliteTTS.m. If you look at the source, it's using an AVAudioPlayer to play back a generated WAV file. It's also setting itself as the audio player's delegate. If you implement the audioPlayerDidFinishPlaying:successfully: delegate method and play the next chunk when it's called, you should be able to have a semi-continuous text-to-speech stream.