【问题标题】:Why is this URL Request is not being called?为什么没有调用此 URL 请求?
【发布时间】:2013-02-26 21:49:30
【问题描述】:

我有以下代码作为 iOS 应用程序的一部分,它从 URL 获取 JSON 数组并使用它来填充表格视图。出于某种原因,函数中没有发出请求,我不知道为什么。功能如下图。

P.S - 我是这个 Objective-C 百灵鸟的新手,如果我犯了一个非常明显的错误,请原谅我!

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    // Create a URL Request
    self.responseData = [NSMutableData data];
        NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:@"http://mydomain.com/return_json_list"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];

    self.viewController = [[BIDViewController alloc] initWithNibName:@"BIDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

【问题讨论】:

标签: objective-c xcode ios6


【解决方案1】:

您从未真正提出请求...您需要在NSURLConnection+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error(同步)上调用start(异步)。

您可以通过以下方式完成后者:

self.responseData = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://mydomain.com/return_json_list"]];

注意它会发生在主线程上,所以你的 UI 会受到影响。

【讨论】:

  • 用同步请求阻塞主线程是个坏主意,特别是因为要下载的 json 数据可能需要一些时间。此外,您无需调用start - 调用initWithRequest:delegate: 与调用initWithRequest:delegate:startImmediately:YES 相同
猜你喜欢
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2014-11-23
  • 2014-05-28
相关资源
最近更新 更多