Question

J'ai downloaa le fichier en utilisant le code illustré ci-dessous. Ensuite, j'essaie d'enregistrer la variable NSMutableData dans le fichier, cependant, le fichier n'est pas créé. Qu'est-ce que je fais mal? Dois-je convertir nsmutabledata en 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
}
Était-ce utile?

La solution

Vous ne pouvez pas écrire dans le bundle de votre application. Vous devrez l'enregistrer ailleurs, comme le répertoire des documents de votre application:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
[data writeToFile:filePath atomically:YES];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top