Krunal
Krunal

Reputation: 6490

Download file from URL and place it in Resource folder in iPhone

I am new to iPhone developer,

How can i download the epub file from url and store it in Resource folder ?

Here is my code snippet,

- (void)viewDidLoad
{
    [super viewDidLoad];
    fileData = [NSMutableData data];
    NSString *file = [NSString stringWithFormat:@"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
    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];
}

- (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:@"%@", [dirArray objectAtIndex:0]];

    if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
        NSLog(@"writeToFile error");
    }
    else {
        NSLog(@"Written!");
    }
}

I am not able to see anything in my NSLog.

Upvotes: 1

Views: 598

Answers (1)

Apurv
Apurv

Reputation: 17186

There is a problem in creation of file path also while writing. you have not specified any filename in the path. In the below line, I have used file name as "filename.txt". Give some proper name and it will write.

NSString *path = [NSString stringWithFormat:@"%@/filename.txt", [dirArray objectAtIndex:0]];

There is a problem in creating URL also. Do it like this,

NSString *file = [NSString stringWithString:@"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
     NSURL *fileURL = [NSURL URLWithString:file];

You have created your file data with below line.

fileData = [NSMutableData data];

Make it like below,

fileData = [[NSMutableData alloc]init];

OR

self.fileData = [NSMutableData data];

Here iOS releases filedata before your connection delegate get called.

Upvotes: 1

Related Questions