Downloading a file from url and saving to resources on iPhone

后端 未结 4 1262
感动是毒
感动是毒 2020-12-13 16:23

Is it possible to download a file (i.e. an sqlite database file) from the Internet into your iPhone application programmatically for later use within the application?

<
相关标签:
4条回答
  • 2020-12-13 16:35

    You need to expand the path with stringByAppendingPathComponent

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];
    
    0 讨论(0)
  • 2020-12-13 16:47

    This can be useful for you.

    NSString *stringURL = @"http://www.somewhere.com/thefile.png";
    NSURL  *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
    {
      NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString  *documentsDirectory = [paths objectAtIndex:0];  
    
      NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
      [urlData writeToFile:filePath automically:YES];
    }
    

    Note that this is a writeToFile method is synchronous, so it will halt/block your UI.

    0 讨论(0)
  • 2020-12-13 16:48

    What is fileData? How is it defined and initialized?

      fileData = [NSMutableData data];
    

    should be somewhere after:

    NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
    

    You have to initialize fileData and retain it per memory management rules.

    Try it with my answer. It Works!

    0 讨论(0)
  • 2020-12-13 16:50

    Try this code in a method and execute,

    NSURL *url=[NSURL URLWithString:@"http://en.wikipedia.org/wiki"];
    
    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:url];   
    
    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"Documents"]];
    
    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Text_file.txt"];  
    
    [dbFile writeToFile:filePath atomically:YES];
    
    0 讨论(0)
提交回复
热议问题