尝试从给定的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;
}
Run Code Online (Sandbox Code Playgroud)
Gro*_*oot 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];
});
Run Code Online (Sandbox Code Playgroud)
您永远不应该在主线程上下载任何内容,因为它会"阻止"您的应用程序.但是应该注意,有更好的方法来下载数据.阅读例如这个.
| 归档时间: |
|
| 查看次数: |
6773 次 |
| 最近记录: |