iOS网络库建议
我会为我的应用程序选择iOS网络库提出一些建议。
我的需求是:
- 发送异步请求(GET和POST),如果网络关闭,则显示
UIAlertView
以通知用户该错误。 - 发送简单同步请求(GET),如果网络关闭,请执行上述相同操作。
有没有人有一些建议? (除了不再支持的ASIHTTPRequest)可能,如果这个lib有一些不错的doc更好。 我是iOS初学者。
提前感谢您的帮助。
我听说过关于RestKit的好消息https://github.com/RestKit/RestKit
在这篇博客文章的底部有一个很好的备选方案列表。 http://allseeing-i.com/%5Brequest_release%5D;
我之前只使用过ASIHTTPRequest,即使它不再由Ben Copsey开发,看起来他仍在合并拉取请求和东西。 它被许多人使用,如果社区选择它,我不会感到惊讶。 对于至少另一个版本的iOS,它可能是安全的。
你真的不需要一个库。
要发送同步GET请求:
//set up the GET URL and params NSURL *getURL = [NSURL URLWithString:@"http://somesite.com/somepath?foo=bar"]; //create the request NSURLRequest *request = [NSURLRequest requestWithURL:getURL]; //get the response NSError *error = nil; NSURLResponse *response = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
要发送同步POST请求:
//set up the POST URL and params NSURL *postURL = [NSURL URLWithString:@"http://somesite.com/somepath"]; NSString *postParams = @"foo=bar&hello=world"; //create the request - this bit is the same for every post NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:postURL]; [request setHTTPMethod:@"POST"]; [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; NSData *data = [postParams dataUsingEncoding:NSUTF8StringEncoding]; [self addValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"]; [self setHTTPBody:data]; //get the response NSError *error = nil; NSURLResponse *response = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
在任何一种情况下,如果responseData为nil或error不为nil,则使用以下内容显示警报:
[[[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease] show];
正如问题所述,他也在寻找异步请求。
我建议AFNetworking或GCNetworkKit(最后一个是我自己的)。 这两个库都非常易于使用且function强大。
我不认为AFNetworking提供同步网络请求。 好吧,至少我的不是。 无论如何你不应该这样做。 两个库都支持error handling。 实现UIAlertView应该没有问题。
你可以在GitHub上找到它们。 只是搜索它们。 希望这可以帮助 :)