我正在寻找一种极其轻量级的方法来从 iOS 设备上的 Web 服务器请求单个数据。将对网页的请求放在一起,例如http://www.myserver.com/getlevel?uid=johnsmith ;异步发送请求,然后检索响应的内容(这将是一个仅包含单个整数的文本文件),并在结果到达后立即对其进行处理。
目标是最小化带宽、最大化速度并保持代码尽可能简单。
谢谢!
最佳答案
如果您正在寻找最简单的 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];
});
});
关于iOS:从服务器请求少量数据的最简单、最快的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775066/