【发布时间】:2014-03-05 01:54:53
【问题描述】:
我最近一直在通过我的 iOS 培训,现在我正在尝试学习 Web 服务。我相信我已经掌握了主要概念:
我调用了一个网络服务
我从该网络服务接收数据
我解析 JSON 数据
我现在对数据做任何我想做的事情。
现在我已经阅读了许多关于简单 Web 服务示例的教程,但它们都使用表视图来填充数据。在我更有经验之前,我不一定想这样做。现在,我只想打个电话,获取数据,然后 NSLog 它。下面是我从教程中得到的一些代码:
#import <Foundation/Foundation.h>
#define WXFORECAST @"http://api.openweathermap.org/data/2.5/\
forecast/daily?q=%@&units=Imperial&cnt=7&mode=json"
#define LOCATION @"Fairbanks"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
// Start the refresh control
// Create the URL string based on location
NSString *urlString =
[NSString stringWithFormat:WXFORECAST, LOCATION];
// Setup the session
NSURLSessionConfiguration * configuration =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session =
[NSURLSession sessionWithConfiguration:configuration];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL
URLWithString:urlString]];
// Create a data task to transfer the web service endpoint contents
NSURLSessionDataTask *dataTask =
[session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response, NSError *error) {
// Stop the refresh control
if (error)
{
return;
}
// Parse the JSON from the data object
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data options:0 error:nil];
// Store off the top level array of forecasts
NSMutableArray *items = [[NSMutableArray alloc] init];
items = json[@"list"];
}];
// Start the data task
[dataTask resume];
}
return 0;
}
现在说我不知道这段代码是轻描淡写。当我看到这个时,我不知所措。我相信这段代码正在打电话,但现在我想 NSLog 来自该 Web 服务的数据。这似乎是一个很简单的答案,但在过去的几个小时里,我一直为此感到沮丧。
感谢所有帮助,在此先感谢。
【问题讨论】:
-
你可以使用
NSLog来显示响应,例如NSLog(@"%@", json);
标签: ios objective-c json web-services