jerfin
jerfin

Reputation: 893

How to store a NSData locally

I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this

 NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"the converted string to nsdata is :%@",conData);

[conData writeToFile:@"Filename.txt" atomically:YES];

but unfortunately this is not working can any one help.

Upvotes: 2

Views: 1560

Answers (3)

MoLowKey
MoLowKey

Reputation: 1142

you should pass a correct path in writeToFile method

NSString *docsDir;
NSArray *dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];

Upvotes: 1

Payal Maniyar
Payal Maniyar

Reputation: 4402

You have given only file name(Filename.txt) not whole file path thats why your code is not working.

Check below line of code you will get idea.

 NSArray *paths =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];  

NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];

Upvotes: 0

swiftBoy
swiftBoy

Reputation: 35783

Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.

This writes file for me

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // Generate the file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Filename.txt"];

     // Save it into file system
    [data writeToFile:dataPath atomically:YES];
});

Upvotes: 1

Related Questions