Post Request With NSURL/NSURLConnection not working in ios? - ios

I am trying to make a post request with some parameters but it is not accomplishing, have a look
#define kLatestKivaLoansURL [NSURL URLWithString: #"http://url...."]
NSDictionary *params = #{#"medcine": #"xanax", #"lat": #"31.0000",#"long":#"74.0000",#"offset":#"0"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:kLatestKivaLoansURL];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];
NSLog(#"%#",request);
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}
}
}];
[task resume];
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary
{
NSMutableArray *parameterArray = [NSMutableArray array];
[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", key, [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
NSLog(#"%#",string);
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
NSLog(#"%#",result);
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
ERROR
APP[2866:154303] dataTaskWithRequest error: Error Domain=NSURLErrorDomain Code=-1003 "The operation couldn’t be completed. (NSURLErrorDomain error -1003.)" UserInfo=0x7874ef60 {NSErrorFailingURLStringKey=http://URL..., _kCFStreamErrorCodeKey=8,
NSErrorFailingURLKey=http://URL..., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x78773e70 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1003.)"}

Try: Replace the below method.
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary
{
NSError *error =nil;
return [NSJSONSerialization dataWithJSONObject:paramDictionary
options:0
error:&error];
}

This link explains error codes pretty well, AppleDevDoc. Here is what is says about this error:
kCFURLErrorCannotFindHost = -1003
I think domain name is wrong.

Related

__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters unrecognized selector error

So Im new in programming with Objective-c. I want to make request with HTTP POST Method.The parameter that i'm sending is of type int.
I'm getting this error :
[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0xb0000000000048d3
at this line of code :
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
The whole Code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
[request setHTTPBody:[self httpBodyForParameters:params]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}}
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
}
NSLog(#"print123");
}];
[task resume];
}
- (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
NSMutableArray *parameterArray = [NSMutableArray array];
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string {
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}
#Paulw11 is right that the error is the result of a number being treated as a string. An immediate (but a little clunky) fix is to be less committed to the type of values you find when enumerating the dictionary...
// notice we change the type of obj id, not NSString*
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
// now, test for it's type and treat accordingly
NSString *objString = ([obj isKindOfClass:[NSString self]])? [self percentEscapeString:obj] : [obj stringValue];
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], objString];
[parameterArray addObject:param];
}];
But this brittle solution now works only for strings and numbers. If you can convince the server to accept JSON, then the request code can be simplified and generalized like this...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
// params is your original (serializable) dictionary
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject: params options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionTask *task = // ...

How to successfully login using by php web service

Firstly I have two text fields first is login and second is password and one login button. I am using a storyboard and login button connected to another view controller by push segue. This time working in my project, Put username and password in textfield and select login button and print server response in console.
I want to login successfully after move another view and login is failed don't move another view.
My php code
<?php
header('Content-type: application/json');
include('../conn.php');
if($_POST)
{
$loginid = $_POST['loginid'];
$loginpassword = $_POST['loginpassword'];
$schoolid = substr_id($loginid);
$table = tb3($schoolid);//profile
$sql=mysql_query("select * from $table where ID = '".$loginid."' AND PASSWORD = '".$loginpassword."'",$conn);
$row=mysql_fetch_assoc($sql);
if(mysql_num_rows($sql)>0)
{
echo '{"success":1}';
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
My viewcontroller code
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
}
}
This line is wrong
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
you are additionally added the & in your params ,this is not in loginpassword=%#& , you need to call like loginpassword=%# remove and send the request
use like
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",_user_id.text,_password.text, nil];
The problem is you are not serlize your JSON
so remove this line in your NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
and I follow your Answer
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
}
Ankur kumawat I tried your coding and Brother #Anbu.karthik answer in iOS 9.I got few warnings.First I post Anbu.Karthik brother answer.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
Above is brother Anbu.Karthik answer.I tried that and it shows me the warnings.
Warnings are
'sendSynchronousRequest:returningResponse:error:' is deprecated: first
deprecated in iOS 9.0 - Use [NSURLSession
dataTaskWithRequest:completionHandler:] (see NSURLSession.h
Then
Implicit conversion loses integer precision: 'long _Nullable' to 'int'
As I get warning I want to remove warning and
I must use
NSURLSession with dataTask because sendSynchronousRequest:returningResponse:error:' is deprecated in iOS 9.0
Then I modified the code.
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:#"POST"];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
The printed result is
The response is - {
success = 1;
}
And
Login SUCCESS
Now above my code works perfectly:-)
Try this code in view Controller file:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog(#"%#",dict);
if (dict)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
}
output: 1 // successfully
or
0 // Unsccssfully
NSString *msg = [NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]];
Replace your code with this :
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
Dictionary *dictResponce = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (dictResponce)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
if (status == "1"){
//Push to home view controller
[self performSegueWithIdentifier:#"Home_page" sender:self];
}
else{
NSLog([NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]]);
}
}
else{
NSLog(#"faield to connect");
}
}
}

How to perform a GET request and check the response

I have a NSString which contains the URL. I want to make a GET request using the URL and also check if the response is 200.
With the current code i get response as 0.
Here is my code:
NSString *Url = #"http://www.xyx.com";
NSData *data = [Url dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
[req setURL:[NSURL URLWithString:Url]];
[req setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:req completionHandler:^(NSData data, NSURLResponse response, NSError *error) {
NSString *req = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Reply = %#", req);
}]resume];
use this code it works for you:
-(void)yourMethodNAme
{
NSString *post = #"";
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:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
and finally call it in ViewDidLoad as [self yourMethodNAme];
-(void) httpGetWithCustomDelegateWithString: (NSString*)urlString
{
[self startActivity];
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionDataTask *dataTask =[defaultSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
//NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
//NSLog(#"Data = %#",text);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"dictionary : %#",deserializedDictionary);
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
deserializedArr = (NSArray*)jsonObject;
NSLog(#"array : %#",deserializedArr);
}
}
[self setAlert];
}
else
{
[activityView removeFromSuperview];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[self showAlert:#"Error" :#"Network error occured." :#"Ok"];
}
}];
[dataTask resume];
}
just use the above code and call it by
[self httpGetWithCustomDelegateWithString:#"webStringHere"];
On Completion, it will call the method -(void)setAlert; so declare it in your class where you use this.
This may be due to App Transport Security blocking HTTP.
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
Try making a request to a secure site (e.g. https://www.google.com) as a test.

NSUrlSession not working

Hi i am very new for ios and in my project i am using NSUrlSession for calling services
but in my below code i have maintain if and else conditions for handing server response but those if and else conditions not calling
please help me where was the mistack happand?
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:myurl here]];
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
NSString * BasicnetworkError = [error localizedDescription];
NSString * AppendString = #"Http Response failed with the following ";
NSString * networkError = [AppendString stringByAppendingString:BasicnetworkError];
[self BasicError1:networkError];
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
NSString *statusCodeError = [NSString stringWithFormat: #"Http Response failed with the following code %ld", (long)statusCode];
[self BasicError1:statusCodeError];
}
}
// If response was JSON (hopefully you designed web service that returns JSON!),
// you might parse it like so:
else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
[self MainService:responseObject];
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}];
[task resume];
}
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary{
NSMutableArray *parameterArray = [NSMutableArray array];
[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", key, [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
There was a case of wrong if else block mentioned in your code. please use below code.
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"COLLECTION",#"SearchBy",
#"1284",#"SearchKey",
#"",#"Color",
#"",#"PriceFrom",
#"",#"PriceTo",
#"",#"QtyFrom",
#"",#"QtyTo",
nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://203.77.214.78/StockManager/SL/SearchProducts"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:mainDictionary]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}
}];
[task resume];
}

Incompatible block pointer types in

Here's the method that's giving me an error when I compile (see the requestMainPage method)
- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password success:(void (^)(void))successHandler failure:(void (^)(void))failureHandler {
NSURL *url = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
//Create and send request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"Pin=%#&Password=%#",
[self percentEscapeString:pin],
[self percentEscapeString:password]];
NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postBody];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse
*response, NSData *data, NSError *error)
{
// do whatever with the data...and errors
if ([data length] > 0 && error == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
// assuming you validated that everything was successful, call the success block
if (successHandler)
successHandler();
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from login), it was = %#", loggedInPage);
if (failureHandler)
failureHandler();
}
}
else {
NSLog(#"error: %#", error);
if (failureHandler)
failureHandler();
}
}]; }
- (NSData *)requestMainPage {
NSData *returner;
//Now redirect to assignments page
NSURL *homeURL = [NSURL URLWithString:#"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/PortalMainPage"];
NSMutableURLRequest *requestHome = [[NSMutableURLRequest alloc] initWithURL:homeURL];
[requestHome setHTTPMethod:#"GET"]; // this looks like GET request, not POST
[NSURLConnection sendAsynchronousRequest:requestHome queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *homeResponse, NSData *homeData, NSError *homeError) //Error is in this line.
{
// do whatever with the data...and errors
if ([homeData length] > 0 && homeError == nil) {
NSError *parseError;
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:homeData options:0 error:&parseError];
if (responseJSON) {
// the response was JSON and we successfully decoded it
NSLog(#"Response was = %#", responseJSON);
} else {
// the response was not JSON, so let's see what it was so we can diagnose the issue
NSString *homePage = [[NSString alloc] initWithData:homeData encoding:NSUTF8StringEncoding];
NSLog(#"Response was not JSON (from home), it was = %#", homePage);
return homePage;
}
}
else {
NSLog(#"error: %#", homeError);
}
return [NSString stringWithFormat:#"%#", homeData];
}]; }
The error came up when I decided I wanted my method (requestMainPage) to have a return type of NSData * rather then just returning void.
So I'm not sure exactly where the problem is.
I figured out my mistake, you can't return values from inside a block.
So if I remove the return homeError and return [NSString stringWithFormat:#"%#", homeData];, the problems go away and I can compile

Resources