I am trying to get connection from server and receive response from server but I can't understand for the response code.
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#",#"_username",#"_password"];
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:#"https://<MY_URL>"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
this is correct or not because I am not getting a response .??
now what is code for response?????
NSURLResponse *response=nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(#"%#",response);
if (response) {
//UIStoryboard *story=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
//TableViewController *obj=[story instantiateViewControllerWithIdentifier:#"table1"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login success" message:#"correct Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
//[self.navigationController pushViewController:obj animated:YES];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login Failure" message:#"Incorrect Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
}
You need to fetch that data:
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseData) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
NSLog(#"res---%#", results);
}
and use dictionary for further use.
ALL the code is correct only you need to add the this in your info.plist
App Transport Security Setting
Allow arbitrary Loads
I've this problem... I have to pass to a JSON two parameters: one is a simply integer and the other is a structure (practically a Dictionary).
I thought to build a structure like this:
NSDictionary *totalRequest = #{
#"param1": #"integerValue",
#"param2": #{
#"subParam1": #"text1",
#"subParam2": #"text2",
#"subParam3": #"text3",
#"subParam4": #"text4",
},
};
NSError *error;
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString: #"http://myurl.com/json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSMutableDictionary* jsonDictionary = [NSMutableDictionary dictionaryWithDictionary:totalRequest];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(#"Error %#",connectionError.description);
}
else
{
NSError *error;
NSDictionary *retData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",[retData objectForKey:#"data"]);
NSString *errore = [[retData objectForKey:#"data"] objectForKey:#"error"];
if ([errore isEqualToString:#"-30000"]) {
[[[UIAlertView alloc] initWithTitle:#"MyApp" message:NSLocalizedString(#"pwderror", nil) delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
if (errore == nil) {
//MY CODE
}
}
}];
The problem is that the server returns retData empty....
Is this the correct way to send two parameters (one simply and one complex) to server via JSON?
Thanks to all contributors...
I want to pass this data using api. I want to get countryname id,code,but I'm not getting how to do.
-(void) getCountries
{
NSString *get=[[NSString alloc]initWithFormat:#"city id=%#,&lang=%#",[self.countryCode text],[self.countryList textInputMode]];
NSLog(#"postDat :%#",get);
NSURL *url=[NSURL URLWithString:#"http://demo28.know3.com/api/country-list/en.html"];
NSData*postData=[get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"contentLength"];
//[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSError *error=[[NSError alloc]init];
NSHTTPURLResponse *response=nil;
NSData *urldata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code %d",(int)[response statusCode]);
if ([response statusCode]<=200 &&[response statusCode]<=300) {
NSString *responseData=[[NSString alloc]initWithData:urldata encoding:NSASCIIStringEncoding];
NSLog(#"Response=%#",responseData);
NSError *error=nil;NSDictionary *jsondata=[NSJSONSerialization JSONObjectWithData:urldata options:NSJSONReadingMutableContainers error:&error];
success=[jsondata[#"success"]integerValue];
NSLog(#"success:%ld",(long)success);
if (success==0) {
NSLog(#"Country");
[self alertStatus:#" country " :#"country List scucess!"];
}else {
NSString *errormsg=(NSString *)jsondata[#"errormesg"];
[self alertStatus:errormsg :#" Failed"];
}
}else{
[self alertStatus:#"connection Failed" :#"sign in failed"];
}
}
-(void)alertStatus:(NSString *)message :(NSString *)title
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil, nil];
[alert show];
}
Have you tried using AFNetworking? It will make your life much more easier.
Download the code from here AFNetworking
And import the AFNetworking folder to your project.
You can use the following code to get country list in an NSDictionary
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am using the following code to upload some images to server. I would like to implement the UIProgressbar. I wrote the connection didSendBody method. The thing is that, for some requests, the delegate method is working. But for the request where I upload image, the method is not called. Please help me in this.
-(void)performRequestWithPost:(NSData*)postData withURL:(NSString*)baseUrl forType:(NSString*)type contentType:(NSString*)contentType
{
if ([self internetAvailable] == YES) {
NSURL *theURL = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init] ;
[theRequest setURL:theURL];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:contentType forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody:postData];
[NSURLConnection connectionWithRequest:theRequest delegate:self];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(!connectionError)
{
NSString *theResponseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSError *error;
NSData *jsonData = [theResponseString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]];
[responseDict setObject:type forKey:#"type"];
NSLog(#"theResponseString-%#",responseDict);
if (self.delegate && [self.delegate respondsToSelector:#selector(serverDidRecieveResponse:)])
[self.delegate serverDidRecieveResponse:responseDict];
}
}];
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet" message:#"Check your Connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
});
}
}
-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if([self.delegate respondsToSelector:#selector(progressViewProgress:)])
{
NSLog(#"bytesWritten: %uld, totalBytesWritten: %uld, totalBytesExpectedToWrite: %uld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
[self.delegate progressViewProgress:(float)(totalBytesWritten/totalBytesExpectedToWrite)];
}
}
Note: I have added the NSURLConnectionDataDelegate. Also the image upload is success all the time.
Working in java, not in objective c. Data is not saved in the database despite getting in "Json Data Posted" condition.
I should send the data in the format as shown below to get the json response
{
"ProjID": "78",
"Uid": "12",
"EmailID": "ratnam_nv#yahoo.com",
"ProjectInviterFQAnswers": [{
"slno": "1",
"Answer": "a1",
"order": "1",
"flag": "F"
}, {
"slno": "2",
"Answer": "a1",
"order": "2",
"flag": "F"
}, {
"slno": "1",
"Answer": "a1",
"order": "2",
"flag": "Q"
}
]
};
I am sending the dictionary I got in log in the format as shown below.
The differnce between the above code and my log's screenshot is ';' after every key value pair and hence I get the response as mentioned in the title.
Any suggestions to correct the code/logic? Here's what I coded.
NSError *error = Nil;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *dictionaryArray1 = [NSDictionary dictionaryWithObjectsAndKeys:#"1", #"slno", #"a1", #"Answer", #"1", #"order", #"F", #"Flag", nil];
NSDictionary *dictionaryArray2 = [NSDictionary dictionaryWithObjectsAndKeys:#"2", #"slno", #"a1", #"Answer", #"1", #"order", #"F", #"Flag", nil];
NSDictionary *dictionaryArray3 = [NSDictionary dictionaryWithObjectsAndKeys:#"1", #"slno", #"a1", #"Answer", #"2", #"order", #"Q", #"Flag", nil];
NSArray *arrayAnswer = [NSArray arrayWithObjects:dictionaryArray1, dictionaryArray2, dictionaryArray3, nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"78", #"ProjID", #"12", #"UID", #"ratnam_nv#yahoo.com", #"EmailID", arrayAnswer, #"ProjectInviterFQAnswer", nil];
NSLog(#"Dictionary that is being sent to URL is = %#", dictionary);
NSURL *url = [NSURL URLWithString:#"http://cnapi.iconnectgroup.com/api/QRCodeScan/SaveAnswers"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
[activity stopAnimating];
}
}];
}
So here's how I solved my own issue.
NSString *str = #"{\"ProjID\": \"78\",\"Uid\": \"12\",\"EmailID\": \"ratnam_nv#yahoo.com\",";
str = [str stringByAppendingString:#"\"ProjectInviterFQAnswers\": ["];
str = [str stringByAppendingString:#"{\"slno\": \"1\",\"Answer\": \"a1\",\"order\": \"1\", \"flag\": \"F\"},"];
str = [str stringByAppendingString:#"{\"slno\": \"2\",\"Answer\": \"a1\",\"order\": \"1\",\"flag\": \"F\"},"];
str = [str stringByAppendingString:#"{\"slno\": \"1\",\"Answer\": \"a1\",\"order\": \"2\",\"flag\": \"Q\"}"];
str = [str stringByAppendingString:#"]}"];
NSLog(#"String is === %#", str);
NSURL *url = [NSURL URLWithString:#"http://cnapi.iconnectgroup.com/api/QRCodeScan/SaveAnswers/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
}
}];
In my case I got the same error, the issue was that I send the wrong data to the service. Basically, the error was caused by setting the wrong body with the line:
[request setHTTPBody: requestData];
Between, sendSynchronousRequest is deprecated in iOS9. Use
...
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
[activity stopAnimating];
}
}] resume];