2013-02-26 92 views
0

我有以下代碼作爲iOS應用程序的一部分,該應用程序從URL中獲取JSON數組並使用它來填充表視圖。出於某種原因,請求沒有在函數中進行,我不知道爲什麼。該功能如下所示。爲什麼這個URL請求沒有被調用?

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; 
} 
+0

該請求是異步的,並將回報給您的委託方法。所以你需要實現一些'NSURLConnectionDelegate'方法,例如:' - connection:didReceiveResponse:'。檢查https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html的文檔 – 2013-02-26 21:53:17

回答

0

你從來沒有真正做的請求......你需要在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會受到影響。

+0

這是一個壞主意,堵塞了同步請求主線,尤其是JSON數據下載可能需要一些時間。此外,您不需要調用'start' - 調用'initWithRequest:委託:'是一樣的調用'initWithRequest:委託:startImmediately:YES' – 2013-02-26 22:04:23

相關問題