Santosh
Santosh

Reputation: 202

IOS8 Parameter is not getting appended to URL when posting data

I am calling the REST service to post lat & lng, however The data is not getting send to server

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *crnLoc = [locations lastObject];
    self.locationDesc.text = [NSString  stringWithFormat:@"%@",crnLoc.description];
    NSLog(@"%@",crnLoc.description);
    NSURL *aUrl = [NSURL URLWithString:@"http://localhost/web/location/create.php?"];
    NSMutableURLRequest *request = [NSMutableURLRequest
                                requestWithURL:aUrl];
    NSString *params = [[NSString alloc] initWithFormat:@"latitude=%g&longitude=%g", crnLoc.coordinate.latitude, crnLoc.coordinate.longitude];
   [request setHTTPMethod:@"POST"];
   [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
   [[NSURLConnection alloc] initWithRequest:request delegate:self];
   NSLog(@"%@",request.URL);
}

Is something wrong here which I am doing in above code? I can post the data using REST Easy client (firefox add-ons).

Upvotes: 2

Views: 58

Answers (1)

user3182143
user3182143

Reputation: 9589

Use this code

CLLocation *crnLoc = [locations lastObject];
self.locationDesc.text = [NSString  stringWithFormat:@"%@",crnLoc.description];
NSLog(@"%@",crnLoc.description);
NSURL *aUrl = [NSURL URLWithString:@"http://localhost/web/location/create.php?"];
NSMutableURLRequest *request = [NSMutableURLRequest
                            requestWithURL:aUrl];
NSString *params = [[NSString alloc] initWithFormat:@"latitude=%g&longitude=%g", crnLoc.coordinate.latitude, crnLoc.coordinate.longitude];
NSData *postData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(con) 
{
   NSLog(@"Connection Successful");
} 
else 
{
   NSLog(@"Connection could not be made");
} 

For reference:

Sending an HTTP POST request on iOS

Upvotes: 1

Related Questions