image getting for JSON not Working - objective-c

I tried to 1)POST image to URL and 2)get Image fro URL.
Posting worked :-
-(void)Send:(id)sender
{
NSData *imageData = UIImagePNGRepresentation(myImageView.image);
myString = [Base64 encode:imageData];
NSString *post =[NSString stringWithFormat:#"?&image=%#",
myString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.3.125:8090/SaveDollar/rest/classifieds/addTestImages"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{ webData3=[NSMutableData data];
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
}
But When I Get Image for JSON i got error:-
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{if (connection==con2)
{
al=[NSJSONSerialization JSONObjectWithData:webData2 options:0 error:nil];
for (NSDictionary *diction in al)
{
NSString *geting =[diction valueForKey:#"image"];
NSLog(#"geting is %#",geting);
getdata = [NSData dataFromBase64String:geting ];
//getdata = [Base64 decode:geting ];
NSLog(#"getdata is %#",getdata);
dataimages=[UIImage imageWithData:getdata];
NSLog(#"dataImaeg is %#",dataimages);
//[imagearray addObject:dataimages];
myImageView.image=dataimages;
}
}
}
but When i getting image on JSON Data it's not worked. I got This error
Nov 10 14:25:35 Sricharans-iMac.local onlyGeting[3729] : ImageIO: PNG Q[10]U[1E]: invalid chunk type
Nov 10 14:25:35 Sricharans-iMac.local onlyGeting[3729] : ImageIO: PNG Q[10]U[1E]: invalid chunk type
Please tell me What wrong in my code .And Give me any Idea about my problem, image not getting.
Thanks in Advanced.

Is your image getting uploaded? If it doesn't check out for codes of image posting, and also check out if the server backend is working properly

Related

JSON parsing is sending error message in iOS 7.1

I checked my code but not getting what is wrong with my code..I am working on JSON Parsing using post method.this same code is working in Xcode 5 but it is not working in Xcode 6.Getting Bellow error in my JSONSerialization.
parsingResultLogin = {
"error_code" = "-1";
"error_message" = "";
}
My code is -
-(void)loginFromServer
{
NSString *strURL = [NSString stringWithFormat:#"%#login",GLOBALURLDOMAIN];
NSLog(#"strURL =%#",strURL);
NSData *dataPostLogin = nil;
NSDictionary *dicPostDataLogin = [ NSDictionary dictionaryWithObjectsAndKeys:#"qwertyuiopwqq",#"username",#"qwertyuiop",#"password",#"1234567890987654",#"device_token",#"ios",#"device_type", nil];
NSLog(#"%#",[dicPostDataLogin description]);
dataPostLogin = [NSJSONSerialization dataWithJSONObject:dicPostDataLogin options:NSJSONWritingPrettyPrinted error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
NSLog(#"request = %#",request);
[request setHTTPBody:dataPostLogin];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu",(unsigned long)[dataPostLogin length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"JSON/application" forHTTPHeaderField:#"Content-Type"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"responsedata =%#",responseData);
if (responseData == NULL) {
AppDelegate *appdel = [[UIApplication sharedApplication]delegate];
[appdel alertError];
}
else
{
NSDictionary *parsingResultLogin = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"parsingResultLogin = %#",parsingResultLogin);
//NSString *strParseDataResult = [parsingResultLogin objectForKey:#""];
}
}
Key/values in JSON are separated by ":", not "=". And there should be no semicolon at the end. So this isn't valid JSON and isn't going to parse with a JSON parser.

iPhone POST request with JSON data

I am building my first iPhone application and have run into problems trying to POST json data to my MongoDB database.
This is my code thus far:
NSString *post = [NSString stringWithFormat:#"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://myURL/users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
I get this response in the console:
2014-06-10 16:07:09.758 SocialEyez[2226:70b] Reply: {
"_id": "5397656dd7ec395c1b808230"
}
So even though the POST seems to go through fine, there is something wrong with my formatting which prevents the JSON data from being entered.
I've tried to format the NSString a hundred different ways but nothing seems to work.
Please help me out!!
EDIT:
When I send this request over jQuery:
jQuery.post("http://site/users", { "name": "George Washington", "reputation": "pres", "phone_number": "1234" }, function (data, textStatus, jqXHR) { console.log("Post resposne:"); console.dir(data); console.log(textStatus); console.dir(jqXHR); });
I get the following response:
_id: "53978f4cd7ec395c1b808247"
name: "George Washington"
reputation: "pres"
phone_number: "1234"
This example assumes that the post data should be JSON.
Create the JSON from a dictionary, let NSJSONSerialization add the JSON syntax.
// #"{\"name\":\"blah\"&\"reputation\":\"100\"&\"phone_number\":\"1234\"}"
// Create the dictionary
NSDictionary *postDict = #{#"name":#"blah", #"reputation":#"100", #"phone_number":#"1234"};
// Create the JSON data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];
// Just for this example: display the jsonData as an ASCII string
NSLog(#"jsonData as String: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSLog output:
jsonData: <7b226e61 6d65223a 22626c61 68222c22 72657075 74617469 6f6e223a 22313030 222c2270 686f6e65 5f6e756d 62657222 3a223132 3334227d>
jsonData as String: {"name":"blah","reputation":"100","phone_number":"1234"}

image base64 corrupt post (Objective-C)

I'm trying to send a post with several parameters and include an image in base64.
The image coding does it well, I checked the base64 image in a online base64 to image converter and looks like the image is encoded successfully. I can do the post process without any problem, but when I download it, the log shows this error:
Error: ImageIO: JPEG Corrupt JPEG data: 120 extraneous bytes before
marker 0xf1
Error: ImageIO: JPEG Unsupported marker type 0xf1
I do this in a method
jpgData = UIImageJPEGRepresentation(image, 0.1f);
imageString = [jpgData base64EncodedStringWithOptions:0];
And this is the method that sends the post, which is where I think the error is.
- (void)putComment{
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
__block int responseCode = 0;
dispatch_async(backgroundQueue, ^{
NSString *requestParams = [NSString stringWithFormat:
#"idAdvertiser=%#&idUserDevice=%#&image=%#&text=%#&userName=%#&groups=%#",
ADVERTISER_ID, idUserDevice, imageString, texto, userName, groups];
[requestParams stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSData *postData = [requestParams dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
// NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString: URL_COMMENT]];
[request setHTTPMethod:#"POST"];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setValue:postLenght forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:40];
NSError *error = nil;
NSHTTPURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
});
}
The server side works perfectly (tested in an Android app), so the problem is not server related.
You encode your url so no need for this line:
[requestParams stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
Remove it and try again.
Also
[request setURL:[NSURL URLWithString: URL_COMMENT]];
can be turned to:
[request setURL:[NSURL URLWithString: [URL_COMMENT stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

Getting Black Image on server side after posting through Json parsing

thanks in Advance..
In my app, i have to upload an image to the server, below is my code. code is working properly, as i get the response but problem is that, on server side image is just black.
sessionid=[[[NSUserDefaults standardUserDefaults] valueForKey:#"SessionID"]objectAtIndex:0];
NSLog(#" ID = %#",sessionid);
NSData *da = [NSData data];
da = UIImagePNGRepresentation(self.Profilepic);
NSString *imgStr = [da base64Encoding];
NSLog(#" %d", imgStr.length);
NSString *serverscriptpath=[NSString stringWithFormat:#"http://c4ntechnology.com/biker/web_services/ws_insert_register3.php?"];
NSString *post =[[NSString alloc] initWithFormat:#"profile_pic=%#&sessionid=%#",imgStr,sessionid];
NSLog(#"post string is :%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"post length is :%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *script_path=[NSString stringWithFormat:#"%#",serverscriptpath];
[request setURL:[NSURL URLWithString:script_path]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",script_path);
NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[[NSString alloc] initWithData:serverReply encoding: NSUTF8StringEncoding] autorelease];
NSDictionary *dict = [responseString JSONValue];
NSLog(#"%#",dict);
[self ReceivedResponse:dict];
-(void)ReceivedResponse:(NSDictionary *)d
{
[AlertHandler hideAlert];
NSLog(#"%#",d);
}
please any one can help me to find out problem, that why on server image is black.?
i am using NSDatAdditions.h file for converting into base64.
when i am using
NSData *imageData = UIImageJPEGRepresentation(Profilepic, 1.0);
at server side, file is not supported occurring, so i used
NSData *da = [NSData data];
da = UIImagePNGRepresentation(self.Profilepic);
You should try using NSUTF8StringEncoding instead of NSASCIIStringEncoding (unless you're sure that the web-server uses ASCII encoding).
If this doesn't work, I'd try the followings:
Encode image as base 64, and afterwards decode it and check if the result is ok.
If 1 passes, check exactly what the server receives (should be the same base64 string as you've sent, otherwise there's probably an issue with different encodings)
As a side note, da = [NSData data]; is useless, since you overwrite it right after, use directly NSData *da = UIImagePNGRepresentation(self.Profilepic);

JSON for Objective-C returns error "Illegal start of token [r]"

I am attempting to connect to a web page and return a JSON string. This string simply needs to be parsed in JSON and returned into an NSArray that I have waiting for it. The problem is that JSON doesn't always return the results. Sometimes, it works well. Sometimes, it returns (null), citing the error below.
self.accounts = nil; // Clear the NSArray
NSString *post = [NSString stringWithFormat:#"username=%#", username.text];
NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]];
// Submit login data
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString: #"http://###.#####.###/app/getaccts.php"]];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody: postData];
// Retreive server response
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
accounts = [[content JSONValue] allValues]; // Parse JSON string into the array
NSLog(#"Array: %#", accounts);
The page I am submitting to returns this:
{"1":"856069060", "2":"856056407"}
JSON logs the following error:
-JSONValue failed. Error is: Illegal start of token [r]
Can I get a little more info ... specifically, I'd like you to check the return value of your sendSynchronousRequest so can you make this change and rerun your test:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (returnData == nil) {
NSLog(#"ERROR: %#", err);
} else {
NSLog(#"DATA: %#", returnData);
}