【问题标题】:NSUrlConnection to connect REST API - XCode 4.2 targetting iOS4 and iOS 5NSUrlConnection 连接 REST API - 针对 iOS4 和 iOS 5 的 XCode 4.2
【发布时间】:2012-02-29 03:44:18
【问题描述】:

我正在使用 XCode 4.2 开发一个至少针对 iOS4 的应用程序。以前从未做过,这是我开发 iPhone 应用程序的第一个月。

我做了一些研究并遇到了 ASIHTTPRequest - 它没有得到维护,甚至开发人员也建议使用其他东西:http://allseeing-i.com/%5Brequest_release%5D;

从该列表中,我想为什么不使用 NSUrlConnection,因为它是内置在 XCode 中的。我知道 RESTKit 在那里似乎很受欢迎,但我听说设置起来有点麻烦 - 而且我不需要任何花哨的东西,只需连接到返回 JSON 的 REST API 服务,所以我觉得 NSURLConnection 绰绰有余.

不太清楚该怎么做,特别是因为我的目标是 iOS4 和 iOS5,据我了解,iOS 5 SDK 引入了 NSURLConnectionDelegate(不确定它们有什么不同?)。

我最初关注这篇文章https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html。但我有一些疑问,因为上面清楚地写着:MAC OSX Developer Library not iOS Developer Library。

谁能指出我正确的方向?有什么例子或教程吗?

【问题讨论】:

  • 只是一个额外的评论,但 iOS 5 也引入了原生 JSON 解析,这真的很有帮助。

标签: rest ios5 ios4 xcode4.2 nsurlconnection


【解决方案1】:

我发现了与上面类似的文章,但适用于 iOS 开发者库(不是 MAX OSX 之一),它们都非常相似(或者很可能具有相同的内容)。 https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE 这就是我最后所做的,而不是实现 NSURLConnectionDelegate。

按照本教程与 JSONKit 相结合:http://www.techtraits.com/jsonkit/ 为我完成了这项工作。

请注意:我必须关闭 ARC,因为 JSONKit 目前不支持它。

例子:

- (IBAction)callRest:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://www.example.com/Person/123"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];                                
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

    if(connection) {
        responseData = [[NSMutableData alloc] init];
    } else {
        NSLog(@"connection failed");
    }

}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
    JSONDecoder *decoder = [[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone];
    NSDictionary* json = [decoder objectWithData:responseData];
    if(json != nil)
    {
        NSLog(@"First Name %@", [json objectForKey:@"FirstName"]);
        NSLog(@"Last Name %@", [json objectForKey:@"LastName"]);
    }
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];

    [responseData release];

    NSLog(@"connection error");
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connection success");
}

我还必须在 .h 文件中声明 responseData,如下所示

@property (retain, nonatomic) NSMutableData *responseData;

在 .m 文件中:

@synthesize responseData;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多