NSURLSessionDataTask在登录中给我不正确的令牌

时间:2018-08-20 17:54:51

标签: objective-c xcode nsurlsession deprecated nsurlsessiondatatask

我正在目标c中更新iOS应用,并且警告sendSynchronousRequest(_:returningResponse:)已在iOS 9.0中弃用:使用[NSURLSession dataTaskWithRequest:completionHandler:] 所以我从以下位置更改了代码:

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

新代码-只需添加已修改的部分

-(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;

}

使用此新代码,每次我登录时都会显示一条消息,提示我用户名或密码不正确,但使用不推荐使用的方法,一切正常。 任何帮助都会很棒!我一直在努力挣扎约3个小时:(

谢谢!

1 个答案:

答案 0 :(得分:0)

似乎您的帖子正文中的POST或GET之间混在一起了。

任何具有格式的URL

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

是GET方法。

您指定的是POST方法。所以首先要弄清楚。 其次,如果您使用的是POST,则应格式化要发布的数据 正确(例如:https://stackoverflow.com/a/19101084/501439)。所有 ”&” 我敢肯定,在您的邮身中会引起问题。