0

I'm updating an iOS app in objective c, and i have the warning sendSynchronousRequest(_:returningResponse:) was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:] So I changed my code from:

-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters{

   NSString *reponseStr;
   NSMutableData *postbody = [NSMutableData data];

   Setting *session =[Setting getSessionDataInstance];

   NSString *todayDate=[Utils Datefromstring:[NSDate date] byFormatter:@"HH:mm:ss"];
   NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/services/?&time=%@", appDelegate.mainUrlString,todayDate]];
   NSMutableURLRequest *request=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:600.0];

   if([method isEqualToString:@"userLogin"])
     {
       [postbody appendData:[[NSString stringWithFormat:@"&param=login"] dataUsingEncoding:NSUTF8StringEncoding]];
       [postbody appendData:[[NSString stringWithFormat:@"&username=%@",[parameters objectForKey:@"userName"]] dataUsingEncoding:NSUTF8StringEncoding]];
       [postbody appendData:[[NSString stringWithFormat:@"&password=%@",[parameters objectForKey:@"password"]] dataUsingEncoding:NSUTF8StringEncoding]];
       [postbody appendData:[[NSString stringWithFormat:@"&apnstoken=123456789"] dataUsingEncoding:NSUTF8StringEncoding]];   
     }

    if([method isEqualToString:@"userLogout"])
      {
        [postbody appendData:[[NSString stringWithFormat:@"&param=logOut"] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[NSString stringWithFormat:@"&user_id=%@",session.userId] dataUsingEncoding:NSUTF8StringEncoding]];
       [request addValue:[NSString stringWithFormat:@"%@",session.sessionToken ] forHTTPHeaderField:@"token"];
      }

      NSString * dataLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postbody length]];
      [request addValue:dataLength forHTTPHeaderField:@"Content-Length"];
      [ request setHTTPMethod: @"POST" ];
      [ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
      [ request setHTTPBody: postbody ];
      NSLog(@"request===%@",[request allHTTPHeaderFields]);
      NSLog(@"URL=====%@",[request URL]);
      NSLog(@"request===%@",request);
      NSError *theError = nil;
      NSURLResponse *urlResponse = nil;


      if ([self checkInternet])
        {
            //THE PART OF THE WARNING ------
            NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&theError];

            if(theError==nil){
                reponseStr= [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding]; 
                NSLog(@"ServerResponse===%@",reponseStr);  
            }
            else{
               NSLog(@"sendSynchronousRequest error = %@",theError.localizedDescription);
            }
        } 
      else{
           reponseStr=@"Network not Available.";
      }

    return reponseStr;
}

- (BOOL) connectedToNetwork
   {
     Reachability *r = [Reachability reachabilityForInternetConnection];
     NetworkStatus internetStatus = [r currentReachabilityStatus];
     BOOL internet;

     if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
      {
         internet = NO;
      } else {
         internet = YES;
      }

   return internet;
  }

-(BOOL) checkInternet
 {
    //Make sure we have internet connectivity
    if([self connectedToNetwork] != YES)
     {
        return NO;
     }
    else {
       return YES;
    }
 }

NEW CODE --just adding the parts that modified

-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters
 {
    __block NSString *reponseStr; 
    .......

    NSString * dataLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postbody length]];
    [request addValue:dataLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod: @"POST" ];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody: postbody ];
    NSLog(@"request===%@",[request allHTTPHeaderFields]);
    NSLog(@"URL=====%@",[request URL]);
    NSLog(@"request===%@",request);
    //NSError *theError = nil;
    //NSURLResponse *urlResponse = nil;

    if ([self checkInternet])
       {
          NSURLSession *session = [NSURLSession sharedSession];
          NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

          if(error==nil)
            {
              reponseStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
              NSLog(@"ServerResponse===%@",reponseStr);

            }
          else
            {
              NSLog(@"sendSynchronousRequest error = %@",error.localizedDescription);
            }

         }];

        [task resume];

       }
       else
         {
           reponseStr=@"Network not Available.";
         }

    return reponseStr;

}

With this new code, every time I log in displays the message that my username or password is incorrect but with the deprecated method everything works fine. Any help will be awesome! I've been struggling with this like 3 hours :(

Thanks!

Mr.Kushwaha
  • 491
  • 5
  • 14
Torres
  • 1
  • Do not check connectivity before issuing a request. Reachability doesn't work that way and Apple doesn't want you to use it that way. – Jon Shier Aug 20 '18 at 18:18

1 Answers1

0

It seems you mixed up between POST or GET in your post body.

Any URL with format

http://abcde.com/what.php?a=1&b=2

is a GET method.

And what you specify is POST method. So make clear about that first. Secondly, if you are using POST, then the data to post should be formatted properly (example: https://stackoverflow.com/a/19101084/501439). All the "&" in your postbody is causing the problem I am sure.

GeneCode
  • 7,545
  • 8
  • 50
  • 85