views:

788

answers:

2

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

I am trying using NSURlConnection, but not able to save the file.

Here is the example code I am trying:

- (void)viewDidLoad {
    [super viewDidLoad];

        NSString *file = [NSString stringWithFormat:@"http://en.wikipedia.org/wiki/Text_file"];
        NSURL *fileURL = [NSURL URLWithString:file];

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




}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        [self.fileData setLength:0];
        self.totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [self.fileData appendData:data];        
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {



    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    NSLog(@"%@", [dirArray objectAtIndex:0]);

    NSString *path = [NSString stringWithFormat:@"%@/blah.text", [dirArray objectAtIndex:0]];
    if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
        NSLog(@"writeToFile error");

    }
else {

    NSLog(@"Written!");
}

    }
+2  A: 

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!

Jordan
Yes, it is defined that way in the header file.
msk
I don't see it in viewDidLoad above. Where is it initialized???fileData = [NSMutableData data];
Jordan
Initialize fileData as I stated in my answer (in viewDidLoad) and it'll work.
Jordan
You need:fileData = [[NSMutableData alloc] initWithLength:0];orfileData = [NSMutableData data];in -(void)viewDidLoad.
Jordan
Thanks, that helped.
msk
Select this as the answer. Re-Ask your questions with regards to the database.
Jordan
+2  A: 

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"];
slf
I want to download the database from the Internet (stored somewhere on some server)
msk
it doesn't matter, you still need to expand the ~
slf