2

我正在寻找一种极其轻量级的方式来从 iOS 设备上的 Web 服务器请求一条数据。将请求放在一个网页上,例如http://www.myserver.com/getlevel?uid=johnsmith;异步发送请求,然后检索响应的内容(这将是一个仅包含一个整数的文本文件),并在结果到达后立即对其进行处理。

目标是最小化带宽,最大化速度,并使代码尽可能简单。

谢谢!

4

2 回答 2

1

根据您的应用程序是否会扩展以包含其他 Web 服务调用,您可能需要考虑 AFNetworking - https://github.com/AFNetworking/AFNetworking。是的,你必须在你的项目中安装 AFNetworking 库,但它很容易做到,然后你就可以享受以下内容:

NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];
[operation start];

(代码取自 AFNetworking github 文档页面)。

于 2013-02-08T15:12:19.037 回答
1

如果您正在寻找最简单的 iOS 代码示例,那将是

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSError *error;
    NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.myserver.com/getlevel?uid=johnsmith"]
                                                encoding:NSUTF8StringEncoding
                                                   error:&error];
    [self doSomethingWithString:string];
});

请注意,如果这doSomethingWithString要更新用户界面,您将执行以下操作:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSError *error;
    NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.myserver.com/getlevel?uid=johnsmith"]
                                                encoding:NSUTF8StringEncoding
                                                   error:&error];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self doSomethingWithString:string];
    });
});

如果您可以让您的服务器生成 JSON 数据,那么这可能是一种更好的方法(这样服务器可以制定适当的响应,可以报告错误,您的客户端可以检测 404 错误等):

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSError *error;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.myserver.com/getlevel?uid=johnsmith"]
                                         options:kNilOptions
                                           error:&error];
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                               options:kNilOptions
                                                                 error:&error];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self doSomethingWithJsonObject:dictionary];
    });
});
于 2013-02-08T15:09:50.453 回答