NSMutableData Сохранить в файл - PullRequest
4 голосов
/ 29 февраля 2012

Я загрузил файл, используя код, показанный ниже. Затем я пытаюсь сохранить переменную NSMutableData в файл, однако файл не создается. Что я делаю неправильно? Нужно ли конвертировать NSMutableData в 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
}

1 Ответ

11 голосов
/ 29 февраля 2012

Вы не можете писать внутри пакета вашего приложения.Вам нужно сохранить его в другом месте, например, в папке «Документы» вашего приложения:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
[data writeToFile:filePath atomically:YES];
...