Objective C post request not sending data
ios development
good day. I am trying to send simple post data to the server. This is my code.
-(void)makeRequest:(NSString*)stringParameters{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"http://vaenterprises.webatu.com/Authentication.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/text" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSString* postData = @"tag=hello&username=yo&something=something";
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[self parseJson:data];
}];
[postDataTask resume];
}
Looks great until I echo the whole post from the php side like this
echo json_encode($_POST);
I print the result in iOS like this
-(void)parseJson:(NSData*) data{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary* jsonObject= [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
NSLog(@"%@",myString);
}
The problem with this is that I get empty strings.. so it means no data is sent, this is 10000% objective c side issue, I don't know why this is happening, so in this approach we just use the one that contains the actual string setHttpBody contains key and value separated by &, but you can't see the data sent. So what am I doing wrong? please tell someone
Vishnu gondlekar
Http body must be of type NSData. Try the following code
NSString* stringData = @"tag=hello&username=yo&something=something";
NSData* data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];