4

I downloaed the file using code shown below. Then i am trying to save NSMutableData variable to file, however, the file is not created. What am i doing wrong? Do i need to convert NSMutableData into NSString?

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response {
    response = [_response retain];
    if([response expectedContentLength] < 1) {
        data = [[NSMutableData alloc] init];
    }
    else {
        data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain];
    }
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

    NSLog(@"saved: %@", filePath);
    [data writeToFile:filePath atomically:YES];
    NSLog(@"downloaded file: %@", data); //all i see in log is some encoded data here
}
user914425
  • 16,303
  • 4
  • 30
  • 41
  • It would certainly help if you passed the address of an NSError variable to writeToFile, and tested the return value of the function. – Philip Sheard Feb 28 '12 at 21:43

1 Answers1

11

You can’t write inside your app’s bundle. You’ll need to save it somewhere else, like your app’s Documents directory:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
[data writeToFile:filePath atomically:YES];
Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
  • thanks this works.. file saved in simulator in /USER/apple/Library/Application .../iPhone Simulator/5.0/App_key/Documents. I am unable find the Library folder from folder browsing. However, using commandline i was able to find this saved file. Thank you Noah for your input. – user914425 Feb 29 '12 at 15:53