1

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];
            }
           }
        }
    });
}
Ryan
  • 2,167
  • 2
  • 28
  • 33
AbhiRam
  • 2,033
  • 7
  • 41
  • 94
  • you get error because you try to send method objectForKey to NSArray. But NSArray does not have such method (this method for NSDictionary). You may at first check your (id)MainResponse for class and after this decide what to do. – Сергей Олейнич Jan 06 '16 at 13:45

2 Answers2

0

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];
                }
            }
        }
    });
}
Rohit Pradhan
  • 3,867
  • 1
  • 21
  • 29
  • no we should not do like that we have to check either dictionary having "error" key like(if ([MainResponse isKindOfClass:[NSDictionary class]] && MainResponse[@"error"])) in this way – AbhiRam Jan 07 '16 at 04:15
  • @AbhiRam : I did in the same way...but my syntax is different...you have used new syntax for object for key.But I prefer old one. – Rohit Pradhan Jan 07 '16 at 04:47
0

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());
}
}];