Encode NSDictionary to send across AFNetworking - ios

How can i URLEncode a NSDictionary so i can send it across AFNetworking.
The code is as follows:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
How can i Encode this NSDictionary so i can send it across AFNetworking ?

Depends how you wish to send your data:
1) #"application/json" in which case you would use [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]
2) #"application/x-www-form-urlencoded" in which case you basically want to create the string: ?id=1211&man=33 from your dictionary rus.
Here's some code, may not be the most efficient by you get the idea:
NSString *temp;
int i=0;
for(NSString *key in options.params.allKeys)
{
NSString *value = [options.params objectForKey:key];
[parameters setObject:value forKey:key];
if(i==0)
{
temp = [NSString stringWithFormat:#"?%#=%#", key,value];
}
else
{
temp = [NSString stringWithFormat:#"%#&%#=%#", temp, key, value];
}
}
Note: may or may not be relevant to you, but my two cents:
I use AFHTTPSessionManager which handles all the details for me including url encoding, so I just pass in the desired dictionary:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
[self POST:#"/api/place/nearbysearch" parameters:rus success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"nearbyPlaces: success");
[self fetchedPlacesData:responseObject block:block];
if(task != nil && task.originalRequest != nil)
{
NSString *url = [task.originalRequest.URL absoluteString];
[self saveNearbySearchEvent:url params:params];
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"nearbyPlaces: error: %#", error);
block(self, nil, error);
}];
AFHTTPSessionManager encapsulates a lot of functionality included serializing the data: AFURLRequestSerialization either as JSON or HTTP Request. In case you interested on what AFHTTPSessionManager actually does here's some detail:
A) HTTP Request
Here's the code from AFURLRequestSerialization.m:
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
NSString *query = nil;
if (self.queryStringSerialization) {
NSError *serializationError;
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
} else {
switch (self.queryStringSerializationStyle) {
case AFHTTPRequestQueryStringDefaultStyle:
query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
break;
}
}
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? #"&%#" : #"?%#", query]];
} else {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
}
return mutableRequest;
}
B) JSON
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}

NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
If you are exchanging JSON data with your server:
NSError *error = nil;
NSData *aRequestData = [NSJSONSerialization dataWithJSONObject:rus options:NSJSONWritingPrettyPrinted error:&error];
if (!error) {
[urlRequest setHTTPBody:aRequestData];
}
If you are exchanging PLIST data with your server:
[self stringByAppendingQueryParameters:rus appendQuestionMark:NO];
- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)iParameters appendQuestionMark:(BOOL)iAppendQuestionMark {
BOOL aAppendAmpersand = YES;
NSMutableString *aWorking = [NSMutableString stringWithString:self];
if (iAppendQuestionMark) {
NSRange aQueryBeginning = [self rangeOfString:#"?"];
if (aQueryBeginning.location == NSNotFound) {
[aWorking appendString:#"?"];
aAppendAmpersand = NO;
}
} else {
aAppendAmpersand = NO;
}
for (id aKey in iParameters) {
id aValue = [iParameters valueForKey:aKey];
NSString *aKeyStr = [self convertObjectToURLEncodedValue:aKey];
if (aAppendAmpersand) {
[aWorking appendString:#"&"];
} else {
aAppendAmpersand = YES;
}
if ([aValue isKindOfClass:[NSArray class]]) {
NSArray *aSubParamaters = (NSArray *)aValue;
BOOL aFirstTime = YES;
for (id aSubValue in aSubParamaters) {
NSString *aValueString = [self convertObjectToURLEncodedValue:aSubValue];
if (!aFirstTime) {
[aWorking appendString:#"&"];
}
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
aFirstTime = NO;
}
} else {
NSString *aValueString = [self convertObjectToURLEncodedValue:aValue];
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
}
}
return [NSString stringWithString:aWorking];
}
- (NSString *)convertObjectToURLEncodedValue:(id)iObject {
NSString *anIntermediate = nil;
if ([iObject isKindOfClass:[NSString class]]) {
anIntermediate = iObject;
} else if ([iObject respondsToSelector:#selector(stringValue)]) {
anIntermediate = [iObject stringValue];
} else {
anIntermediate = [iObject description];
}
NSString *anEncodingString = (__bridge_transfer NSString *)(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)anIntermediate,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 ));
return anEncodingString;
}

Related

client server json response

I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newant‌​ara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/i‌​mages\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};
Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.
Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (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;
}
}

How to integrate NSUrlsession in ios

Hi I am very new to ios and in my app I am using NSUrlSession for integrating services.
Here my main problem is when I get a response from the server, I can't handle them properly.
When I get a correct response, then see the below json stucture:-
responseObject = {
{
Name = Broad;
DeptNo = A00;
BatchNo = 23;
DeptId = 120;
},
{
Name = James;
DeptNo = B00;
BatchNo = 23;
DeptId = 123;
},
}
when I get a wrong response, see the below json stucture:-
responseObject = {
error = 1;
message = "Invalid Code";
}
when I get a correct response from the server, I am getting an exception in my below if block(like __NSCFArray objectForKey:]: unrecognized selector sent to instance 0x1611c200') and when I get a wrong response then T get exception in my else block
Please help me how to handle them
my code:-
(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
if([MainResponse objectForKey:#"error"] != nil)
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
1)Change Your implementation like below
2)I checked is it dictionary type & error key has some value
3)Earlier you were calling objectForKey on Array, therefore it was crashing
-(void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
NameArray = [[NSMutableArray alloc]init];
IdArray = [[NSMutableArray alloc]init];
//here I checked is it dictionary type & error key has some value
if ([MainResponse isKindOfClass:[NSDictionary class ]] &&[MainResponse objectForKey:#"error"])
{
NSLog(#"No data available");
}
else{
for (NSDictionary *obj in MainResponse) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"DeptNo"]) {
NSString * Name = [obj objectForKey:#"Name"];
[NameArray addObject:Name];
NSString * Id = [obj objectForKey:#"id"];
[IdArray addObject:Id];
}
}
}
});
}
Try this:
//Result Block
typedef void (^ResultBlock)(id, NSError*);
//URL request
-(void)requestURL:(NSURLRequest *)request withResult:(ResultBlock)resultHandler{
//URLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if(!error){
NSError *jsonError = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if([result isKindOfClass:[NSArray class]]){
//Success
resultHandler(result,nil);
}
else if([result isKindOfClass:[NSDictionary class]]){
if([[result objectForKey:#"error"] integerValue]){
//Failure.
NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
[errorDetail setValue:[result objectForKey:#"message"] forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"Error" code:100 userInfo:errorDetail];
resultHandler(nil, errorDetail);
}
}
}
}];
[task resume];
}
//Call your requestURL method:
[self requestURL:request withResult:^(id result, NSError *error){
if(!error){
//Success, Read & update your list
}
else{
//Error
// NSLog(error.localizedDescription());
}
}];

IOS getting response null in http request

I'm sending a request to a server to test a specific situation. The response is a custom 510 http error and the content is the info of the error.
The web service works fine the first time a send the request. The next time I tried to replicate the error the response is nil. But, if I change the request avoiding the error, it works fine and the response is what it is supposed to be.
I'm executing the request with a brand new object each time.
#interface SCBaseConnection()
#property (strong, nonatomic) NSURLSessionDownloadTask *task;
#end
#implementation SCBaseConnection
- (instancetype) initWithUrl:(NSString *)url
path:(NSString *)path
body:(NSString *)body
headers:(NSDictionary *)headers
method:(NSString *)method
requestCode:(NSInteger)requestCode
{
self = [super init];
NSLog(#"%#", headers);
NSURL *uri = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", url, path]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uri];
request.HTTPMethod = method;
if (body) {
request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
}
if (headers) {
NSArray *keys = [headers allKeys];
for (NSString *key in keys) {
[request setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
NSURLSession *session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration]];
self.task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
int statusCode = (int)[response getStatusCode];
NSLog(#"%#", #(statusCode));
if (HTTP_UNAUTHORIZED == statusCode) {
[[NSNotificationCenter defaultCenter] postNotificationName:kUnauthorizedHttpRequest object:response];
}
if (error) {
[MCMGeneralUtils logError:error];
NSLog(#"%#", error.userInfo);
NSLog(#"%#", error);
}
NSData *res = [self dataFromFile:location];
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate didConnectionFinished:self
statusCode:statusCode
response:res
requestPath:path
requestCode:requestCode];
});
}];
return self;
}
This is the content of the error.userInfo after the second request.
NSErrorFailingURLKey = "http://192.168.1.201:23111/api/paciente";
NSErrorFailingURLStringKey = "http://192.168.1.201:2311/api/paciente";
NSLocalizedDescription = "The requested URL was not found on this server.";
The first time the request has no errors.
UPDATE
- (IBAction)save:(UIBarButtonItem *)sender
{
MCMPatientNew *patient = [MCMPatientNew new];
patient.name = self.name;
patient.lastname = self.lastname;
patient.fullname = [NSString stringWithFormat:#"%# %#", self.name, self.lastname];
patient.email = self.email;
patient.phones = [self extracPhones];
patient.patientNew = YES;
NSError *error = nil;
if ([patient assertPatient:&error]) {
MCMUser *user = [MCMUser loadUserInManagedContext:self.managedContext];
patient.delegate = self;
[patient storePatientInManagedContext:self.managedContext];
if ([MCMGeneralUtils isInternetRechable]) {
[self presentViewController:self.serverConnectionAlert animated:YES completion:nil];
[patient postPatientWithToken:user.token doctorId:user.userId];
} else {
[self storeInRequestLogWithRequestCode:REQUEST_CODE_PACIENTE_INSERT
appId:patient.appId
ready:YES
inManagedContext:self.managedContext];
[self cancel:nil];
[self postNotificationWithObject:patient];
}
} else {
[self displayErrorMessageWithErrorInfo:error.userInfo];
}
}
UPDATE 2
- (void)postPatientWithToken:(NSString *)accessToken doctorId:(NSNumber *)doctorId
{
NSMutableDictionary *mutable = [NSMutableDictionary dictionaryWithDictionary:[self jsonToPost]];
[mutable setObject:doctorId forKey:#"doctorId"];
NSDictionary *body = #{#"obj" : mutable};
[self connectToServerWithAccessToken:accessToken
body:body
path:PATH_PACIENTE_INSERT
method:HTTP_METHOD_POST
requestCode:REQUEST_CODE_PACIENTE_INSERT
delegate:self];
}
-
- (void)connectToServerWithAccessToken:(NSString *)accessToken
body:(NSDictionary *)body
path:(NSString *)path
method:(NSString *)method
requestCode:(NSInteger)requestCode
delegate:(id<SCBaseConnectionDelegate>)delegate
{
NSString *authenticator = [NSString stringWithFormat:#"Bearer %#", accessToken];
NSDictionary *headers = #{HEADER_CONTENT_TYPE : CONTENT_TYPE_APPLICATION_JSON,
HEADER_AUTHORIZATION : authenticator};
NSString *bodyStr = body ? [SCJson jsonFromDictionary:body] : #"";
SCBaseConnection *connection = [[SCBaseConnection alloc] initWithUrl:API_URL
path:path
body:bodyStr
headers:headers
method:method
requestCode:requestCode];
connection.delegate = delegate;
[connection execute];
}
-
- (BOOL)execute
{
if (self.task) {
[self.task resume];
return YES;
}
return NO;
}

shouldPerformSegueWithIdentifier issue

I tried too much to solve my bellow issue but i am failed.Please help me to solve this issue. I have login view and after validating id and password i am pushing it to next view controller.Please check bellow image.
Issue - When Id and Password is correct it's pushing to next view controller but after 2 clicks on login button.
Code -
ServiceManager.m
-(void)initGetAppServiceRequestWithUrl:(NSString *)baseUrl onCompletion:
(ServiceCompletionHandler)handler
{
NSString *fullUrl = [NSString stringWithFormat:#"%#",[baseUrl
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:fullUrl]];
[NSURLConnection sendAsynchronousRequest:(NSURLRequest *)request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,NSData *data,NSError *error)
{
if (error) {
handler(nil,error);
// NSLog(#"error = %#",error);
}
else
{ handler(data, nil);
// NSLog(#"data = %#",data);
}
}];
}
JSONResponseHandler.m
+(void)handleResponseData:(NSData *)responseData onCompletion:(JSONHandler)handler
{
if (responseData) {
NSError *jsonParseError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&jsonParseError];
if (!json) {
handler(nil , jsonParseError);
}
else
{
handler (json , nil);
}
}
}
ASKevrServiceManager.m
-(void)login:(Login *)login completionHandler:(ServiceCompletionHandler)handler
{
NSString *loginUrl = [NSString
stringWithFormat:#"http://249development.us/johnsan/askever/login.php?
login=%#&password=%#",login.emailAddr , login.password];
[self initGetAppServiceRequestWithUrl:loginUrl onCompletion:^(id object, NSError
*error)
{
handler(object , error);
}
];
}
ASKevrOperationManager.m
+(void)login:(Login *)login handler:(OperationHandler)handler
{
ASKevrServiceManager *serviceManager = [[ASKevrServiceManager alloc]init];
[serviceManager login:login completionHandler:^(id object, NSError *error)
{
[JSONResponseHandler handleResponseData:object onCompletion:^(NSDictionary
*json , NSError *jsonError)
{
if(json)
{
handler(json , nil , YES);
}
else
{
handler(nil , jsonError , NO);
}
}];
}];
}
LoginViewController.m
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"pushTab"])
{
if ([emailTxt.text isEqualToString:#""] || [passwordTxt.text
isEqualToString:#""])
{
[self showAlertWithMessage:#"Please write your id or password"];
return NO;
}
else
{
Login *loginModel = [[Login alloc]init];
loginModel.emailAddr =emailTxt.text;
loginModel.password = passwordTxt.text;
[ASKevrOperationManager login:loginModel handler:^(id object , NSError *error ,
BOOL success)
{
if (success)
{
NSLog(#"object =%#",object);
NSDictionary *arr = [object objectForKey:#"response"];
str = [arr objectForKey:#"flag"];
//check for error
NSDictionary *toDict = [object objectForKey:#"response"];
currentUserId = [toDict objectForKey:#"c_id"];
NSLog(#"currentUserId = %#",currentUserId);
}
else
{
[self showAlertWithMessage:#"Wrong Id or Password."];
}
}];
NSLog(#"str = %#",str);
if ([str isEqualToString:#"1"])
{
// [self showAlertWithMessage:#"Wrong Id or Password."];
return YES;
}
}
}
return NO;
}
When pressing login button do run the code
if (![emailTxt.text isEqualToString:#""] &&
![passwordTxt.text isEqualToString:#""]){
Login *loginModel = [[Login alloc]init];
loginModel.emailAddr =emailTxt.text;
loginModel.password = passwordTxt.text;
[ASKevrOperationManager login:loginModel handler:^(id object , NSError *error ,
BOOL success)
{
if (success){
NSLog(#"object =%#",object);
NSDictionary *arr = [object objectForKey:#"response"];
str = [arr objectForKey:#"flag"];
//check for error
NSDictionary *toDict = [object objectForKey:#"response"];
currentUserId = [toDict objectForKey:#"c_id"];
NSLog(#"currentUserId = %#",currentUserId);
//perform the segue only when succesful
[self performSegueWithIdentifier:#"yourSegue" sender:sender];
}else{
[self showAlertWithMessage:#"Wrong Id or Password."];
}
}];
}else {
[self showAlertWithMessage:#"Please write your id or password"];
}
Keep your shouldPerformSegueWithIdentifier simple
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender
{
if ([identifier isEqualToString:#"pushTab"])
{
//don't put logic here
//put code here only if you need to pass data
//to the next screen
return YES:
}
return NO;
}

Parse JSON text in a textfield (My result is NULL)

I am making an iOS application which communicate with an database via an API. The API sends valid JSON to the application but the application gives no error but another result: NULL.
Here is my code for the iOS app:
// Start hud
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Zoeken...";
return TRUE;
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if (request.responseStatusCode == 400) {
textView.text = #"Invalid code";
} else if (request.responseStatusCode == 403) {
textView.text = #"Code already used";
} else if (request.responseStatusCode == 204) {
textView.text = #"No content";
} else if (request.responseStatusCode == 412) {
textView.text = #"Precondition Failed";
} else if (request.responseStatusCode == 200) {
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
// NSString *naam = [responseDict objectForKey:#"DEB_NR"];
NSString *part0 = [responseDict objectForKey:#"klntnr"];
NSString *part1 = [responseDict objectForKey:#"klntnm"];
NSString *part2 = [responseDict objectForKey:#"adrs"];
NSString *show = [NSString stringWithFormat:#"\r%#\r%#\r%#" , part0 , part1 , part2 ];
// if ([unlockCode compare:#"com.razeware.test.unlock.cake"] == NSOrderedSame) {
textView.text = [NSString stringWithFormat:#"Resultaten: %#", show];
// } else {
// textView.text = [NSString stringWithFormat:#"Resultaat: %#", unlockCode];
// }
} else {
textView.text = #"Unexpected error API ERROR";
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSError *error = [request error];
textView.text = error.localizedDescription;
}
#end
Thanks in advance,
Maurice.
It would really help if you just show the JSON string;
But try this
else if (request.responseStatusCode == 200) {
NSError* error;
NSString *responseString = [request responseString];
NSArray *responseObj = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &error];
NSString *part0=#"";
NSString *part1=#"";
NSString *part2=#"";
for (int i=0; i<[responseObj count]; i++) {
NSDictionary *dataDict = [responseObj objectAtIndex:i];
NSString *part0 = [dataDict objectForKey:#"klntnr"];
NSString *part1 = [dataDict objectForKey:#"klntnm"];
NSString *part2 = [dataDict objectForKey:#"adrs"];
}
NSString *show = [NSString stringWithFormat:#"\r%#\r%#\r%#" , part0 , part1 , part2 ];
textView.text = [NSString stringWithFormat:#"Resultaten: %#", show];
}

Resources