Web services for iOS application with C# using mysql? - ios

I am working on iPhone application with web services.
Using HTTP POST method I tried post the data. But data is saving in database. The response I'm getting is 404 or 400. here C# is used instead of PHP.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#""]];
NSString *userUpdate =[NSString stringWithFormat:#"Name=%#,FirstName=%#,DateofBirth=%#,Sex=%#,Country=%#,City=%#,PhoneNumber=%#,IncumbentonPremimum=%#",Name,FirstName,DateofBirth,Sex,Country,City,PhoneNumber,IncumbentonPremimum];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
NSString *postLength = [NSString stringWithFormat:#"%d",[data1 length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:data1];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);`

Related

Sending Post http request from nsstring

I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

Synchronous NSURLConnection https post request with JSON

I need to make a HTTPS post request to a server using a synchronous connection. I've made plenty of http connections but for some reason the code doesn't work with https and I'm sure the website address is right.
Some of my code:
Note that dparam is a dictionary object.
NSError *err;
NSData *parameterJSONData = [NSJSONSerialization dataWithJSONObject:dparam options:
NSJSONWritingPrettyPrinted error:&err];
NSString *param = [[NSString alloc] initWithData:parameterJSONData encoding:NSUTF8StringEncoding];
NSString *post =[[NSString alloc] initWithFormat:#"varnameOne=%#&varnameTwo=%#&param=%#",vone,vtwo,param];
//my_url is a string defined elsewhere
NSURL *url=[NSURL URLWithString:my_url];
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];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need to do this synchronously as I don't really have the time to change all my database calls to asynchronous and the calls need to either complete or fail before the program continues so it'd have to be made effectively synchronous anyway.
That said I did try a synchronous route but it didn't work with https only http.

IOS JSON sending an email from Mandrill

I have an IOS application that I would like to send an email via Mandrill. I have tried to implement this, but its not working and Ive confused myself.
When pressing the button to send an email from the IOS application I log this error message:
{"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}
My code is:
NSString *post = [NSString stringWithFormat:#"{\"key\": \"abcdefg123456\", \"raw_message\": \"From: me#mydomain.com\nTo: me#myotherdomain.com\nSubject: Some Subject\n\nSome content.}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://mandrillapp.com/api/1.0/messages/send-raw.json"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"Post: %#", post);
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);
Please let me know where I am going wrong.
It looks you forgot the \" after "content.".
Try to write your "post" variable as follow:
NSString *post = [NSString stringWithFormat:#"{\"key\": \"abcdefg123456\", \"raw_message\": \"From: me#mydomain.com\nTo: me#myotherdomain.com\nSubject: Some Subject\n\nSome content.\"}"];
I hope it helps.

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

Calling asp.net web service from iOS application crash when data contains ampersands?

I have an application which actually calling asp.net web service but when I transfer data with & it stop working. Like below jsonString have first_name which have "Pranav &" so as this stage when I call service with converting it in asciistringencoding it generate error because of ascii convert it like
&quotPranav &&quot
with finding two ampersands it stop working
NSString * jsonString = #"{"home_phone":"123","GroupId":"GP00000099","first_name":"Pranav &","city":"df","last_name":"Purohit","state":"sl","email":"pjp#gmail.com","member_Id":"GM00008513"}";
NSString * post = [[NSString alloc] initWithFormat:#"jsonText=%#", jsonString];
NSLog(#"%#",post);
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myweburl.com/mywebservice.asmx/mymethod"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I got answer, when you embed & replace it with \u0026

Resources