2014-04-17 119 views
0

我想弄清楚如何使用AFNetworking 2.0。我正在嘗試使用用戶名和密碼進行登錄。如何在iOS中創建POST請求?

這是我目前的嘗試,但有些不起作用,因爲它不會發送。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSDictionary *parameters = @{@"loginName": @"password"}; 
[manager POST:@"http://xxxx.com/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"JSON: %@", responseObject); 



    NSLog(@"Data saved"); 

    MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil]; 
    mainView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
    [self presentViewController: mainView animated:YES completion:nil]; 


} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
    NSString *error_msg = (NSString *) error; 
    [self alertStatus:error_msg :@"Sign in Failed!" :0]; 
}]; 

    } 
} @catch (NSException * e) { 
     NSLog(@"Exception: %@", e); 
     [self alertStatus:@"Sign in Failed." :@"Error!" :0]; 
    } 

但是什麼也沒發生,只是不斷收到此打印輸出:

2014-04-16 20:14:09.903 Slidedrawer[9279:60b] Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e78bd0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.} 

的響應將是JSON。任何人都知道我需要在代碼中編輯什麼或如何解決它?

JSON: { 
    "_id" = 533cb1c453769a02008c2d55; 
    name = dddd; 
    picture = "/img/users/default.jpg"; 
} 

如何訪問上述返回的JSON,試圖挑開每個返回的屬性設置爲一個字符串或整數等..

回答

1

試試這個:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSDictionary *params = @{@"userName": username, @"password": password}; 
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format 
[manager POST:@"http://asd.com/login.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"%@", responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"%@", error); 
}]; 

對於解析響應用這個responseObjectNSDictionary

NSString *userName = [responseObject objectForKey:@"userName"]; 
NSString *password = [responseObject objectForKey:@"password"]; 

希望這有助於.. :)

+0

嘿,我看到responseSerializer如何從數據中提取數據? – Lion789

+0

@ Lion789看我的編輯。 – Rashad

+0

非常感謝您的幫助 – Lion789

1

你可能會發現Send Nested JSON using AFNetworking爲答案。

錯誤Error Domain = NSCocoaErrorDomain Code = 3840從服務器收到無效的JSON對象。這可能是由服務器不正確處理缺少的參數引起的。您的參數字典只有一個關鍵對象loginName。