【问题标题】:AFNetworking POST cannot return json dataAFNetworking POST 无法返回 json 数据
【发布时间】:2013-02-27 07:48:35
【问题描述】:

我想用POST方法发出请求,然后我希望他们返回json数据或NSDictionary,但他们只能在成功时返回字符串

点赞NSString *response = [operation responseString];

有谁知道如何让他们返回NSdictionary 而不是NSString

-(IBAction)SubmitLogin:(id)sender{
    NSLog(@"Login");
   // NSLog(@"%@",username);

    //START FUNGSI UNTUK POST, PUT, DELETE

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:signinUrl];
    [httpClient defaultValueForHeader:@"Accept"];



    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"someuser", @"username",
                            @"somepassword",@"password",
                            nil];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@""
                                                      parameters:params];

 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:
     ^(AFHTTPRequestOperation *operation,
       id responseObject) {
         NSString *response = [operation responseString];
         NSLog(@"response: %@",response);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"error: %@", [operation error]);
     }];


    //call start on your request operation
    [operation start];

【问题讨论】:

    标签: ios networking post response afnetworking


    【解决方案1】:

    我试图发送 JSON 对象并取回 JSON 数据并解析它

    NSURL *url = [NSURL URLWithString:@"https://MySite.com/"];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
    //[httpClient setParameterEncoding:AFJSONParameterEncoding];
    //[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"Ans", @"name",
                            @"29",  @"age", nil];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"/testJSONReturn.php"
                                                      parameters:params];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"DATA: %@", [JSON valueForKeyPath:@"data"]);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failure Because %@",[error userInfo]);
    }];
    
    [operation start];
    

    可能有帮助

    【讨论】:

      【解决方案2】:

      这是我使用的,请随意满足您的需求:

      -(void) loginWithUserID:(NSString*)usrID User:(NSString*)usr Password:(NSString *)psw Sender:(id)sender
      {
          if ([sender respondsToSelector:@selector(startLoading)]){
              [sender performSelector:@selector(startLoading)];
          }
      
          baseURL = [NSString stringWithFormat:
                        @"http://xxx.xxx.xxx.xxx/test/service.svc/weblogin"];
          NSString* serviceURL = [NSString stringWithFormat:
                                 @"%@?userID=%@&user=%@&password=%@",baseURL,usrID,usr,psw;
      
          NSURL *url = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
      
          NSURLRequest *request = [NSURLRequest requestWithURL:url];
      
          AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
              self.LoginOK = [JSON valueForKeyPath:@"LoginOK"];
              if (LoginOK.intValue == 1) {
                  NSDictionary *usrData = [JSON valueForKeyPath:@"userData"];
                  userData = [[UserData alloc]init];
                  [userData readFromJSONDictionary:usrData];
                  NSLog(@"Userdata: %@",userData);
                  if ([sender respondsToSelector:@selector(loginSuccessful:)])
                  {
                      [sender performSelector:@selector(loginSuccessful:)];
                  }
              }else{
                  UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Correct Login Credentials" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                  [alertView show];
                  ;}
      
          } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
              if ([sender respondsToSelector:@selector(stopLoading)]){
                  [sender performSelector:@selector(stopLoading)];
              }
              [[[UIAlertView alloc] initWithTitle:@"Error"
                                          message:@"Loginservice not available! Check your connection!"
                                         delegate:nil
                                cancelButtonTitle:@"OK"
                                otherButtonTitles: nil] show];
              NSLog(@"Error: %@", error);
      
          }];
      
          [operation start];
          };
      

      编辑:哦,使用

      -(void)readFromJSONDictionary:(NSDictionary *)d
      {
      
          [self setProperty1:[d objectForKey:@"property1"]];
      }
      

      将该字典中的所有属性获取到自定义类中的方法。

      【讨论】:

      • 感谢您的回答和编辑我的问题,对不起我的英语不好。
      • 我没有编辑你的问题 Zoro,不用担心你的英语,这很好理解。希望这段代码对您有所帮助,欢迎来到 Stack Overflow :)。
      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 2013-03-13
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多