我有这个api(http://www.timeapi.org/utc/now),它只将时间作为字符串给出,我想使用NSURLConnection来检索它,除了我对NSURLConnection的工作方式感到困惑之外。
当前代码:
+(NSString *) fetchTime
{
NSString *timeString=@"not_set";
//Code for URL request here
NSURL *timeURL = [NSURL URLWithString:@"http://www.timeapi.org/utc/now"]
return timeString;
}
从视图控制器调用该方法,然后将其按照MVC依次显示在屏幕上,我所需要的只是一个很好的例子,可以使我朝正确的方向发展。
为了向该api发出请求,您需要这样的东西:
NSURL *timeURL = [NSURL URLWithString:@"http://www.timeapi.org/utc/now"]
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:120];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSString *string = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句