gpt4 book ai didi

iphone - 带有 json 反馈的 AFNetworking Post 请求

转载 作者:行者123 更新时间:2023-12-03 18:35:36 26 4
gpt4 key购买 nike

我正在使用 AFNetworking 并创建一个需要 json 反馈的发布请求。下面的代码有效,但是我有两个主要问题;在哪里释放 ActivityIndi​​cator 管理器?第二个问题是这段代码是正确的,作为新代码,我对 block 感到困惑,所以我真的想知道我是否在做正确的事情以获得最佳性能,即使它有效。

    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 所说,您应该使用 [[AFNetworkActivityIndi​​catorManager sharedManager] setEnabled:YES] 来打开事件网络指示器。这是一个singleton ,因此不需要您手动分配初始化和释放。至于另一个问题,我注意到您在 block 调用中缺少一些参数,而且,您可以这样做,这是更干净的代码:

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

关于iphone - 带有 json 反馈的 AFNetworking Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7630289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com