I am trying to send multiple parameter for a registration usage. Here is my Code for Posting data :
-(void)PostRegistrationData:(NSString *)userEmail :(NSString *)Password{
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
/* We iterate the dictionary now
and append each pair to an array
formatted like <KEY>=<VALUE> */
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
}
/* We finally join the pairs of our array
using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:#"&"];
NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://teknofolk.com/spisrett_admin/slave/signup.php?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
NSMutableData *mutableData = [[NSMutableData alloc]init];
}
}
But no data i getting inserted . Am i missing something?
You have various choices what you want to use.
First option:
NSURLResponse *res = nil;
NSError *err = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];
(you have also the async way for this option).
or you can also follow your code and continue with this:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
and the request will be async and will call this methods (you need that this view controller responds to the NSURLConnectionDelegate and NSURLConnectionDataDelegate):
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
It was my mistake in the parameter.
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
Worked with simply this :
#"type":#"1",
#"request_type":#"2"
};
In my insertion i was passing wrong value on type and request type. Thanks to all for all
Related
I have made a login form. Fields r email and password. Now i want to POST the data from fields to specific url how it can be done. I'm totally new to IOS. Can anybody help me?? How to do HTTP request and JSON parsing?
/*********See this**********/
-(void)webServiceCall{
NSString *dataToSend = [NSString stringWithFormat:#"Username=%#&Password=%#“,<userIdEnter Here>,<Password enter here>];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *Length = [NSString stringWithFormat:#"%d",[postData length]];
[request setURL:[NSURL URLWithString:#“WEBURL”]];
[request setHTTPMethod:#"POST"];
[request setValue:Length forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// check connection if you want
/*****get response in delegates*******/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:
(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
/**************/
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// NSArray* latestLoans = [json objectForKey:#"loans"];
NSLog(#"json: %#", json);
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error --> %#",error.localizedDescription);
/***************/
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
// use Result
self.responseData = nil;
}
Actually I am using now JSON classes for calling web-services but now i want to call that webservice using NSURLConnection any one provide me code for that.
Please provide me details of frameworks what i have to import.
Thank you in advance.
NSURL *url = [NSURL URLWithString:stringurl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dictionary);
}];
You Can use this.
You can Do like this using Synchronous :
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *response=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dd=[response JSONValue];
OR Using Delegate Method
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSURLResponse *response = nil;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// NSArray* latestLoans = [json objectForKey:#"loans"];
NSLog(#"json: %#", json);
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
Use below code forrcalling SOAP web service (POST) :
-(NSString *)posturl:(NSString *)url withpoststring:(NSString *)postString {
NSString *post = postString;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *URL = url;
NSLog(#"%#", URL);
NSLog(#"%#",post);
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if ([data isEqualToString:#""]) {
} else {
data = stringByStrippingHTML(data);
}
return data;
}
Little issue that's been bothering me. I've been making a POST request to my AWS RDB. The request should return a json output. The issue I'm having is that I'll receive bytes back, but sometimes it contains incomplete json, thus converting it to a dictionary won't work. Sometimes I also receive a null value for the nsdata received, but I can print out the length of the data. Any ideas? Here's my iOS code for requests:
#import "ServiceConnector.h"
#implementation ServiceConnector{
NSMutableData *receivedData;
}
-(void)getTest{
//Send to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"GET"];
//initialize an NSURLConnection with the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
-(void)postTest:(NSMutableArray *)carSearches{
//build up the request that is to be sent to the server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"POST"];
NSError *writeError = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:carSearches options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON Output: %#", jsonString);
[request setHTTPBody:data]; //set the data as the post body
[request addValue:[NSString stringWithFormat:#"%lu",(unsigned long)data.length] forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
#pragma mark - Data connection delegate -
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails
NSLog(#"Connection failed with error: %#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Request Complete,recieved %lu bytes of data",(unsigned long)receivedData.length);
NSString *tmp = [NSString stringWithUTF8String:[receivedData bytes]];
NSLog(#"%#",tmp);
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[receivedData bytes] length:[receivedData length]] options:NSJSONReadingAllowFragments error:&error];
[self.delegate requestReturnedData:dictionary];
}
In this section:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
You are only appending data if the object hasn't been created yet. You want to append every time. That if statement should read like this:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
}
[receivedData appendData:data];
I have am NSURLConnection to get a JSON value from my web server. The code is placed in a class which can be called from other UIViewControllers.
I am a little unsure on how to return the JSON data from the class however.
Here is what I have tried:
+(NSJSONSerialization *) getTask:(id)task_id{
NSJSONSerialization *json;
NSLog(#"task id = %#", task_id);
NSString *post = [NSString stringWithFormat:#"&task_id=%#", task_id];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.iampeterstuart.co.uk/todo/index.php/task/get"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
[conn start];
return json;
}
// Log the response for debugging
+ (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(#"Resonse: %#", response);
}
+ (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
+ (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Each time the variable json is null?
Could somebody please advice?
Many thanks,
Peter
You are thinking incorrectly about the delegate's behavior.
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data will be called whenever new data is available (downloaded from the server), which is the raw bytes of the byte stream. You should have an instance of NSMutableData and append that received data to the mutable data when data is received. Finally, when the whole data (e.g. JSON string in your example) is downloaded, -(void)connectionDidFinishLoading:(NSURLConnection *)connection will be called. In that method, you should parse the JSON string:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
...where data is the cumulative data received. You can create the data instance as below in the class implementation:
NSMutableData *cumulativeData;
In init or whatever method that is initially called on your delegate before you start loading, call:
cumulativeData = [NSMutableData data];
Then in your (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data method, call:
[cumulativeData appendData:data];
That should append the received data into the cumulative data that you are "building".
This is my code.
- (void)loadData:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection found---------");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"reciving data---------");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"connection fail---------");
[self.pddelegate connectionError];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"data posting done---------");
[self.pddelegate dataPosted];
}
It is not working if url become bigger and give connection fail in logs.
Like
url=#".......order_details&admin=29&tableid=89&waiter_id=18&items=MzQ6MSwxMToxLDMzOjEsNjc6MSwzOToxLDY5OjEsNTY6MSw2ODoxLDg6MSw1NToxLDYyOjEsNzY6MSw0MToxLDIwOjEsNjE6MQ=="
see this SO post for get type request length What is the maximum length of a URL in different browsers?
for sending big string use POST type request instead of GET type.
We have there are two methods for sending data.
1. GET Method : Which is used for fixed length or limited length of string only.
2. POST Method : Which is used to send more string while comparing get method.
I have given the example Using PostMethod.
NSString *post =[[NSString alloc] initWithFormat:#"%#",YourString];
NSURL *url=[NSURL URLWithString:*#"YourURL like www.google.com"*];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
request.timeoutInterval = 60;
NSError *error = nil;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *errStr = _stringEmpty;
#try { errStr = [error localizedDescription]; }#catch (NSException * exception){ }
If any error occur errStr will show the error.
In the past, I have used some URL's that are around 2000 characters in length in iOS with no problem. NSURL, NSURLRequest, and NSURLConnection all managed just fine. If your URL is shorter than that, the problem is probably not due to its length, but instead related to the way the URL is constructed.