【问题标题】:Downloading a zip file in iOS在 iOS 中下载 zip 文件
【发布时间】:2013-06-24 09:46:20
【问题描述】:

尝试从给定的 URL 下载 zip 文件,因为 zip 文件每天都会更新,我在 ApplicationDidFinishLunching 方法中编写了代码,但它不起作用。我的代码有什么问题吗?

- (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;
}

【问题讨论】:

  • 是的,你在主线程同步下载。这是一个很大的禁忌,但它可能是也可能不是原因。但是,如果下载时间超过 10 秒,它将崩溃。使用异步方法(dispatch_async、NSURLConnection 等)。
  • @borrrden 我知道不要在主线程上下载,但这个下载只有几 kb,你看到我的代码有什么问题吗?
  • 即使文件只有几 kb,下载也可能需要一些时间,因为下载是在主线程上执行的,这将阻止应用程序启动!
  • @Ben 你在错误的地方进行同步网络调用。 application:didFinishLaunchingWithOptions: 应该立即返回,否则您的应用程序将被 Springboard 杀死,错误代码为 0x8badf00d。为避免这种情况,请启动异步调用(在后台线程上),它将在每次启动时下载所需的文件。
  • 很好的回应和所有的注意。谢谢大家。

标签: ios objective-c


【解决方案1】:

试试这个,因为它会在后台下载 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

【讨论】:

  • 似乎是一个非常优美的代码,目前 web 服务已关闭。我继续尝试,我会给你一个反馈。 Tnx
  • 干得好。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2015-07-21
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多