How to get the image from the base64encodedstring ? - json

I am using base64encoding for sending an UIImage to the server and then on the other end i am getting it back, converting the base64encodedstring in to NSData then trying to get my image back on an UIImageView.
Everything working fine sending the Base64encodedString and receiving it but when i am converting the NSData back in to UIImage it is throwing the following exception
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
this is the code i am using for posting the image:
img=mainImage.image;
NSData *imgdata=UIImagePNGRepresentation(img);
NSString *imgstring=[imgdata base64EncodedString];
NSString *post =[[NSString alloc] initWithFormat:#"gid=%#&image=%#",[lblgid text],imgstring];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.abcd/updategameimage.php"];
And following is the code at receiving end
NSString *imgStr=[abc valueForKey:#"image"];
NSLog(#"%#",imgStr);
NSData *imgdata=[NSData dataWithBase64EncodedString:imgStr];
imge = [UIImage imageWithData:imgdata];
[imgview setImage:imge];
Here abc is NSMutableArray

Are you sure abc is a mutableArray?
Because you are sending it a valueForKey: method. This is a KVC method implemented by NSObject and it doesn't make sense to send it this message.
If you meant to send it the objectForKey: method instead - then that would be a message that you send to dictionaries, not arrays.
And, the error that you are getting:
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
is telling you that an NSArray does not respond to dataUsingEncoding:allowsLossyConversion: messages - which is a method for NSString objects.
I think you are getting confused with your object types and need to get a better handle on what is what.

Related

Parsing JSON which contains html data

I want to parse json data which contains html but there is a problem
I made a parser with this lines but always I got this error: The operation couldn’t be completed. (Cocoa error 3840.)
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];
You need to fix the incoming JSON object. You will need to encode that HTML in your web-service (whatever that may be). You should be able to see the issue when you run your JSON through a validator like JSONViewer or JSONLint.

Converting URLWithString to NSURLConnection

I am new to iOS development and I am trying to retrieve some data from server.
I have used:
NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding];
which is freezing my app's UI. I put it dispatch but this causes other issues.
How to convert this one to NSRULConnection which will reply NSData like URLWithString?
Thank you
I found the solution. I was dispatching [self function1[self function2[self function3]]]; where the function3 was the json request. After dispatching only function3 the result was fine

ios5: Sending JSON data from the iPhone to REST using POST

I am trying to send data in the JSON format to the REST api. When sending a parameter the web service does not return any data but instead gives the following error:Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)
This is because the parameter cannot be read by the web service.
But if I add this parameter directly to the URL the correct results are returned Eg:http://localhost:8080/de.vogella.jersey.final/rest/notes/63056
The following is the code for sending the parameters:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost:8080/de.vogella.jersey.final/rest/notes/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *postString = #"{\"notes\":\"63056\"}";
NSLog(#"Request: %#", postString);
// NSString *postString = #"";
[request setValue:[NSString stringWithFormat:#"%d",[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSLog(#"Return Data%#",returnData);
//Getting the task types from the JSON array received
NSMutableArray *jsonArray =[NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
NSLog(#"jsonArray is %#",jsonArray);
taskTypes =[[NSMutableArray alloc]init ];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#",error);
} else {
for(NSDictionary *taskType in jsonArray) {
[taskTypes addObject:[taskType objectForKey:#"TaskName"]];
}
}
Any suggestions?
Your error "JSON text did not start with array or object and option to allow fragments not set" could mean two things:
You're specifying that you expect the response object to be in JSON format and it is not (for example, this would happen if you're using an AFJSONRequestOperation and the server returns something other than JSON)
Fix: Get a hold of the server code and make sure it returns a valid JSON object
You have not specified that you're okay with receiving something other than JSON
Fix: If you're using AFNetworking, pass in NSJSONReadingAllowFragments to [NSJSONSerialization JSONObjectWithData:options:error:] on your subclass of AFHTTPClient (Shout out to Cocoa error 3840 using JSON (iOS) for this answer).

objective-c: creating a server method

Currently I am able to retrieve data from a MySQL db by using HTTP GET and an NSURL connection, but I need to know how to encapsulate this action into a method. Could somebody inform me of how to put the following code into a method so that I can call it throughout my app, and also so that I can show a UIActivityIndicator while the process is underway?
//somethign like this?
-(void)getDataFromServer:(NSString *)url{
//enter code here
}
My current server request: I am using this in didselectrowforindexpath, so that the following stuff is done whenever somebody selects a cell. The issue is that I keep re-using this same code in several different methods, so I assume that it is bad practice to keep copying/pasting this code rather than having a method.
// retrieve data
NSString *buildURL = [[NSString alloc] initWithFormat:#"http://myurl.com"];
// begin query
NSURL *url = [NSURL URLWithString:buildURL];
NSError *e;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&e];
NSLog(#"jsonreturn: %#",jsonreturn);
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
EDIT:
Much better way to do this, which I just implemented, is to use ASIHTTPRequest. The library provides for all the needs which I was trying to accomplish with the method above.
Just take your whole second code block and put it inside the {} of the first code block. You probably want to return that jsonData variable instead of void, though.

How do you parse a JSON array with TouchJSON?

I'm using TouchJSON. Made a call to my Rails app to fetch all "posts" at localhost:3000/posts.json. This returns a JSON array, surrounded by square brackets. I'm currently set up to convert the jsonString into an NSDictionary, but that fails due to the square brackets.
NSString *jsonString=[self jsonFromURLString:#"http://localhost:3000/posts.json"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
self.dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
What's the best way to turn this result into an NSArray using the TouchJSON library?
Error Domain=kJSONScannerErrorDomain Code=-101 "Could not scan dictionary. Dictionary that does not start with '{' character."
Why don't you just use the -deserialize: method and then figure out what kind of object you have after its done?
Or to answer your specific question, use -deserializeAsArray:
I think most parsers frown with array data. You'll have to return a hash:
{'result': [Your array data]}