我正在使用AFNetworking并创建需要json反馈的发布请求。下面的代码有效,但是我有两个主要问题;我应该在哪里释放ActivityIndicator Manager?第二个问题是此代码正确,是新代码,我对块感到困惑,所以我真的想知道我是否在正确地做它以获得最佳性能,即使它可以工作。
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");
}
非常感谢您的提前帮助:)
最佳答案
我知道这个问题有点老了,但我仍然想贡献一点。
正如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