我是iOS开发的新手,我被困在我的小项目中,我必须在php网站上创建异步POST请求。我在线阅读资源,发现AFNetworking最适合这项工作,所以我通过终端使用cocoapods安装了AFNetworking 2.4。我有一个视图控制器,它有2个文本字段(用户名和密码),每当我按下登录按钮,我就向php网站发送异步POST请求.POST请求必须包含参数' username'和密码'并将收到一个JSON回复,其中包含一个'代码'和一条消息'我必须在UIAlert中显示已解析的代码和消息以及api调用在几毫秒内所花费的时间。唯一有效的登录名是用户名:Yomaki密码:asdfgh。登录成功后,点按“确定”即可。在UIAlert上应该把我们带回MainMenuViewController。请看下面我尝试过的代码。我尝试过在线跟踪几个教程,但没有用。
请查看以下代码,
(IBAction)loginButton:(id)sender
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"Yomaki": _usernameTextField, @"asdfgh": _passwordTextField};
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"PHP URL HERE"]];
AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
}
请帮我处理代码,因为这是我第一次向php网站发送异步POST请求。
提前致谢。
答案 0 :(得分:1)
您不想使用_usernameTextField
(UITextField
),而是使用_usernameTextField.text
或更好的self.usernameTextField.text
(NSString
属性那个测试场)。密码也是如此。
我也可以使用POST
方法:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"userid": self.usernameTextField.text, @"password": self.passwordTextField.text};
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
请注意,在您的字典中,您将替换字段名称(可能类似于userid
和password
,但请与您的网络服务作者联系),其中显示的是示例用户ID /密码值。我想你想要恢复原始字段名称。
答案 1 :(得分:0)
来自:Junda Ong教程
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"yourURL"
parameters: parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject); }
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
答案 2 :(得分:0)
NSURL * url = @"your url";
NSString * user = ([userField.text length] == 0) ? @"" : userField.text;
NSString * pass = ([passField.text length] == 0) ? @"" : passField.text;
NSMutableDictionary * postVars = [NSMutableDictionary dictionary];
[postVars setObject:user forKey:@"username"];
[postVars setObject:pass forKey:@"password"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:url parameters:postVars success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([responseObject isKindOfClass:[NSDictionary class]]){
if ([responseObject objectForKey:@"code"]) && ([responseObject objectForKey:@"message"]){
NSString * code = [responseObject objectForKey:@"code"];
NSString * message = [responseObject objectForKey:@"message"];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// something went wrong with your http post
}];