Getting Black Image on server side after posting through Json parsing - objective-c

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);

Related

send post request with dynamic data

good afternoon
I have been looking but I haven't found anything similar
I am starting with Xcode and objective C please you be patient with me
I want do this
I have a text field intended to be a search box
currently I send a POST request programmatically and the parameters are static
well, I want dynamic parameters
the content of the text field is dynamic parameters
how do I can do it?
I have also a button for sending the request
help please
this is code of the request
NSString *Post = [[NSString alloc] initWithFormat:#"query=deporte"];
NSURL *Url = [NSURL URLWithString:#"http://www.laleo.com/ebooks_android/ebooks_search_json.php"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [PostData length]];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:#"POST"];
[Request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[Request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[Request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[Request setHTTPBody:PostData];
NSData *returnData = [NSURLConnection sendSynchronousRequest:Request returningResponse:nil error:nil];
//NSString *myString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error;
NSMutableDictionary *allCourses = [NSJSONSerialization
JSONObjectWithData:returnData
options:NSJSONReadingMutableContainers
error:&error];
The text field already is available through of #synthesize palabra;
The button is in the graphical interface
First of all, you should create an action handler for your button. Use Interface Builder for that. Also you'll need to connect the outlet for the textfield with your viewcontroller's class. Then, just take a text value from your textfield and send it into the request. If you need to know how you can receive a text from the textfield, just use this:
NSString *text = _textField.text;

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

Sending images through json getting failed

Code:
NSData *imgd=UIImageJPEGRepresentation(Obj.thumbImage, 0.5);
[imgName insertObject:Obj.imageName atIndex:i];
[imgName1 insertObject:imgd atIndex:i];
[dic setObject:imgName forKey:#"name"];
[dic setObject:imgName1 forKey:#"image"];
[asiLoadingFormRequest setPostValue:contactName forKey:#"receivername"];
[asiLoadingFormRequest setPostValue:[dic JSONRepresentation] forKey:#"imagedata"];
Is it correct to way sending images through json?When i call server i am getting following error message
"Error Domain=org.brautaset.JSON.ErrorDomain Code=1 \"Unsupported value for key image in object\" UserInfo=0x9a611f0 {NSUnderlyingError=0x9a4a290 \"JSON serialisation not supported for NSConcreteMutableData\", NSLocalizedDescription=Unsupported value for key image in object
Is it problem with Json that does not support for images?I have no idea about this problem.any help will be appreciated.thanks in advance.
Try this:
Encoding Part:
First Add Base64 class into your project.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http:xxx.me.com/me.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSData *imageData = UIImagePNGRepresentation ([UIImage imageWithContentsOfFile: #"ur PNG image path"]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSArray *keys = [NSArray arrayWithObjects:#"image_id",#"image_name","image",nil];
NSArray *objects = [NSArray arrayWithObjects:#"22",#"myImageName.png",imageString,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
For Decoding the same on the server side(if your using php) refer this.
You cannot send NSData as JSON, if you want to send an image over JSON you have to first encode it in Base64 and then decode it on the server
Take a look at this
https://github.com/l4u/NSData-Base64

iOS http post response to NSDictionary or NSArray

I'm making a HTTP Post and I would like to know how to convert the response to NSDictionary, or NSArray. Here's my code:
NSString *post = [NSString stringWithFormat: #"SomeData=text", text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https://www.my.site/receiver"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
EDIT:
The response looks like this after converting like this:
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
2011-12-04 11:50:00.924 Dancing Ruby[404:207] response: SID=DQAAAMAAAAAjy9MXrxh7Hi4nXTpyVTnqMR4c_W2wCQmLmO7xDHz7v91kl16tH-0UyazONU2nGjsUYxGzAPd9lvNcCGLfcz7YFLQRhG8yW8_wn3V46g8SY0A5bnfmGhuIbAMoCetow09cOnE7aYUzEZ4u5zVnJFoNepa9BlheFAA8JFLomw3luHedLkJZi_CQJO48CtwLZeIF9zhD5RNUDUretNh_1QBN2fHntSiqASMHHHyd9dtlTaXpokx_KIJovxo0dNYUJbs
LSID=DQAAAMIAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_j3HXUNsqtTm-aEFgylW2QURA5F9_1Fx8WRECIWOkUoLfWBGchoxRfhxKqCoD-zzgg1opjSmrDyv0U1NZRN7YGiqkLj4Fz_Qm6oPapov2_J33KT0ENFTKnqyzS0zU3wHgKSGb1aoKKO0ZJCTFk20AX3cLYPuMWoJcnyrLipCzZjkjwGEEhfgz31ISPS9OGezPzYJji-UxTmaJB7Va7SGquX
Auth=DQAAAMEAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_gex6ZHpCOn0tXFwuivD7ESwhFMJGdLRYSspk-leGqj-eCkXUgsg4DBvxPbdpREFlU_j0RGm_qufXlaScZV3x17plY5-xrhvhziEVFf3eLiHEmN9HHNwh8uElyYyJ1rLNAbIunpG3D10ASr4WPQDIz_52OOKy07CmQrBNDdUcpkT5bXqBe3Cdw8aqld0LZH2AIMEdj7PupfRaneJgF-nCBZ
You need to use some kind of parser for that. If the response is in XML you could use NSXMLParser. Here you can find a tutorial on how to use it. The same concept applies for any other kind of data. You have to know beforehand what to expect so you can parse it properly.
I hope it helps

Put JSON encoded array as NSData from NSURLResponse into NSArray

I'm unable to get this to work:
NSString *post = [NSString stringWithFormat:#"userudid=%#", [udid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
//[udid dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myserver.com/myapp/readtags2.php"]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"responseData: %#", content);
is the POST formed correctly? Because i can get it to work from a manual html form posting to the same php file, but i get nothing back when doing it from iOS
You might have an easier time doing HTTP POST's with ASIHTTPRequest.
Form-Posting with ASIHTTPRequest is explained in the section titled "Sending a form POST with ASIFormDataRequest" here: http://allseeing-i.com/ASIHTTPRequest/How-to-use
Otherwise, have a look at the NSURLResponse, check the response code and see if iOS thinks the POST was successful.
Other thing you can use to check is a tool like wireshark to compare the network traffic from your web-based form POST to the traffic from your iOS POST. It looks like you're doing it right, but the best way to be sure is something like wireshark.