AFNetworking Post与json反馈请求
问题描述:
我正在使用AFNetworking并创建一个需要json反馈的post请求。下面的代码工作,但我有两个主要问题;我在哪里可以发布ActivityIndicator Manager?第二个问题是这段代码是正确的,是新的,我和块混淆了,所以我真的想知道,如果我为最佳性能做正确的事情,即使它有效。AFNetworking Post与json反馈请求
NSURL *url = [NSURL URLWithString:@"mysite/user/signup"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
AFNetworkActivityIndicatorManager * newactivity = [[AFNetworkActivityIndicatorManager alloc] init];
newactivity.enabled = YES;
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
usernamestring, @"login[username]",
emailstring, @"login[email]",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"mysite/user/signup"parameters:params];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id json) {
NSString *status = [json valueForKey:@"status"];
if ([status isEqualToString:@"success"]) {
[username resignFirstResponder];
[email resignFirstResponder];
[self.navigationController dismissModalViewControllerAnimated:NO];
}
else {
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Login Unsuccessful"
message:@"Please try again"
delegate:NULL
cancelButtonTitle:@"OK"
otherButtonTitles:NULL];
[alert show];
[alert release];
}
}
failure:^(NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", error);
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Login Unsuccessful"
message:@"There was a problem connecting to the network!"
delegate:NULL
cancelButtonTitle:@"OK"
otherButtonTitles:NULL];
[alert show];
[alert release];
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
NSLog(@"check");
}
非常感谢您的帮助提前:)
答
为什么不使用这个呢?
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
因此没有必要的alloc和init
不能说太多的其他代码,刚开始时学习Objective-C和AFNetworking .. :)
问候, Steve0hh
答
我知道这个问题有点老,但我仍然想贡献。
正如steveOhh所说,您应该使用[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]
来打开活动网络指示器。它是一个singleton,因此它不需要你手动alloc-init和release。至于其他的问题,我注意到你缺少一些参数在块调用,也可以做到这一点,这是非常干净的代码:
NSURL *url = [NSURL URLWithString:@"mysite/user/signup"];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:[NSURLRequest requestWithURL:url] success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// your success code here
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// your failure code here
}];
[operation start]; // start your operation directly, unless you really need to use a queue
哪里了'AFJSONRequestOperation operationWithRequest:sucess:面漆:'方法来自?我没有在API中看到它。 –
@reakinator他实际上'+ JSONRequestOperationWithRequest:成功:失败:'见示例[这里](https://github.com/AFNetworking/AFNetworking#readme)。 – borisdiakur