2013-06-24 123 views
3

嘗試從給定的URL下載zip文件,因爲zip文件每天更新​​我在ApplicationDidFinishLunching方法中編寫了代碼,但它不起作用。我的代碼有什麼問題?正在下載iOS中的zip文件

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // Override point for customization after application launch. 
    NSString *stringURL = @"http://webspace.apiit.edu.my/intake-timetable/download_timetable/timetableXML.zip"; 
    NSURL *url = [NSURL URLWithString:stringURL]; 
    NSData *urlData = [NSData dataWithContentsOfURL:url]; 
    //Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching) 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *path = [paths objectAtIndex:0]; 

    //Save the data 
    NSString *dataPath = [path stringByAppendingPathComponent:@"timetableXML.zip"]; 
    dataPath = [dataPath stringByStandardizingPath]; 
    [urlData writeToFile:dataPath atomically:YES]; 
    return YES; 
} 
+0

是的,你正在同步下載主線程。這是一個很大的禁忌,但它可能會或可能不會是原因。但是,如果下載時間超過10秒,則會崩潰。使用異步方法(dispatch_async,NSURLConnection等)。 – borrrden

+0

@borrrden我知道不要在主線程下載,但這個下載只有幾kb,你看到我的代碼有問題嗎? – Ben

+0

儘管文件只有幾kb,但下載可能需要一些時間,並且在主線程上執行下載,這將阻止應用程序啓動! – Groot

回答

14

試試這個,因爲它會在後臺下載zip文件。即使該文件只有幾kb,下載可能需要一些時間,並且下載在主線程上執行,這將阻止應用程序啓動!

dispatch_queue_t queue = dispatch_get_global_queue(0,0); 
dispatch_async(queue, ^{ 

    NSLog(@"Beginning download"); 
    NSString *stringURL = @"http://webspace.apiit.edu.my/intake-timetable/download_timetable/timetableXML.zip"; 
    NSURL *url = [NSURL URLWithString:stringURL]; 
    NSData *urlData = [NSData dataWithContentsOfURL:url]; 

    //Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching) 
    NSLog(@"Got the data!"); 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *path = [paths objectAtIndex:0]; 

    //Save the data 
    NSLog(@"Saving"); 
    NSString *dataPath = [path stringByAppendingPathComponent:@"timetableXML.zip"]; 
    dataPath = [dataPath stringByStandardizingPath]; 
    [urlData writeToFile:dataPath atomically:YES]; 

}); 

你不應該在主線程上下載任何東西,因爲它會「阻塞」你的應用程序。但應該指出,下載數據有更好的方法。請閱讀例如this

+0

似乎是一個非常漂亮的代碼,目前web服務已關閉。我繼續嘗試,我會給你一個反饋。 Tnx – Ben

+0

幹得好。非常感謝 :) – Ben