How can I deal with a file being split into several parts, when I send it to a server? - objective-c

I am trying to write code in Objective C which should send a JPEG file to a server. The problem is that the file is split into several parts, and only the first part is getting there. Is there a way of dealing with this?
Here is some of the code:
int j;
for (j = 0; j < 5; j++) {
// Read in data from appropriate signature file
NSMutableString *imagePath = [folder_path_2 mutableCopy];
[imagePath appendString:fn[j]];
[imagePath appendString:#".jpeg"];
NSLog(imagePath);
NSData *imageData = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if (fileExists) {
imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
} else {
NSLog(#"JPEG image file does not exist.");
}
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:#"POST"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Accept"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
int len = (int)[imageData length];
length_str = [NSString stringWithFormat: #"%d", len];
[request setValue:length_str forHTTPHeaderField:#"Content-Length"];
postBody = [NSMutableData data];
[postBody appendData:[NSData dataWithData:imageData]];
[request setHTTPBody:postBody];
// Make connection to the Internet
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil
error:nil];
NSString *returnString = (NSString*)[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
NSLog(returnString);
}

How big is the jpeg file that you're trying to send?

Related

Posting JSON data to server

I am trying to post and JSON data to server.
My JSON is:
{
“username”:”sample”,
“password” : “password-1”
}
The way I am sending it to server is:
NSError *error;
NSString *data = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(#"resposne dicionary is %#",responseDictionary);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
The JsonData that is created is a valid JSON accepted by the server.
But the app is crashing and the error is:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0
what is wrong that i am doing here?
I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.
-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#", action];
NSLog(#"%#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
You can easily call it:
- (void) login:(NSDictionary *)data
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placePostRequestWithURL:#"yourActionUrl"
withData:data
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (!(code >= 200 && code < 300)) {
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
NSLog(#"OK");
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
string, #"id",
nil];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
And finally, you invocation:
NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, #"username",
_textFieldPasssword.text, #"password", nil];
[self login:dataToSend
calledBy:self
withSuccess:#selector(loginDidEnd:)
andFailure:#selector(loginFailure:)];
Don't forget to define your callbacks:
- (void)loginDidEnd:(id)result{
NSLog(#"loginDidEnd:");
// Do your actions
}
- (void)loginFailure:(id)result{
NSLog(#"loginFailure:");
// Do your actions
}
First you create an NSString* that is supposed to contain JSON data. This doesn't work in general if the username and password contain any unusual characters. For example, I make sure that I have a quotation mark in my password to make sure that stupid software crashes.
You turn that string into an NSData* using ASCII encoding. So if my username contains any characters that are not in the ASCII character set, what you get is nonsense.
You then use the parser to turn this into a dictionary or array, but store the result into an NSData. Chances are that the parse fails and you get nil, otherwise you get an NSDictionary* or an NSArray*, but most definitely not an NSData*.
Here's how you do it properly: You create a dictionary, and then turn it into NSData.
NSDictionary* dict = #{ #"username": _textFieldUserName.text,
#"password": _textFieldPasssword.text };
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
That's it.
try this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"My URL"];
if (!request) NSLog(#"Error creating the URL Request");
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];

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.

sending files to server and receiving feedback

I have this code who send a file to my server:
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://websitetester.com/here.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSLog(#"File Send to server!");
this code works perfectly but I would like to receive a return from the server, the php file at the end of the code I show:
<?php
if(...){
...
echo "Data Received";
}else{
...
echo "Error in server";
}
?>
All I'm trying is receive this echo in php and show an alert inside my app, how code I can implement inside my code to do that?
EDIT
Hey I find a code who receive the return data in objetive-c, the code is:
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);
and now the code works the way I expected.

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

Get data from server using php

NSURL *url = [[NSURL alloc] initWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.php"];
NSData *data = [url resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:data encoding:NSMacOSRomanStringEncoding];
NSLog(#"result FOR ID %#",string);
I am using this code in didenterBackgroundMethod.In that i just want to call lastidretrieve.php which returns a response as a string.I am getting error as "receiver type nsurl for instance message does not declare a method with selector resourceDataUsingCache".i have no idead about this error.
Use this code instead of your code it gives the string output ,then you have to format that string to get disired output.
NSString *post =#"";
NSURL *url=[NSURL URLWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastidretrieve.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 setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
//NSData *data = [responseData resourceDataUsingCache:YES];
NSString *string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
NSLog(#"responseData-%#",string);
}
Output will be like this.
responseData-1995<br />prabu<br />1231231233<br />antab<br />8080808080<br />1360738531881.jpg<br />No
UPDATE
In case you want to add argument in your URL than change post string to this.
NSString *post =[[NSString alloc] initWithFormat:#"yourArg=%#",yourArg];
It would have been sufficient to read the documentation of NSURL. This method is deprecated. You should use [[NSData alloc] initWithContentsOfURL:url] instead.