Write NSData to a file?

29,628

Try using :

NSError *error = nil;
path=@"/Users/aryaxt/Desktop/test2.avi";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

That'll tell you why the write is failing.

Share:
29,628
aryaxt
Author by

aryaxt

Updated on August 29, 2020

Comments

  • aryaxt
    aryaxt over 3 years

    I am trying to write an nsdata to a file on my disk, I have the following code and it doesn't work, am i doing anything wrong?

    Boolean result = [data writeToFile:@"/Users/aryaxt/Desktop/test2.avi" atomically:YES];
    

    test2.avi doesn't exist, I am assuming that writeToFile would create it for me

  • Jonathan Grynspan
    Jonathan Grynspan over 13 years
    error should only be examined if the method returns NO. Foundation classes may put other objects or fake errors or even garbage in the error argument. (That's not to say that they do, but it's part of the programmer contract that they can, so be careful.)
  • Coldsteel48
    Coldsteel48 almost 9 years
    I have a side question a bit off topic from the documents:Discussion This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide." So should I still use it or not ?
  • Coldsteel48
    Coldsteel48 almost 9 years
    "publicly accessible files" What does it mean ?
  • John Franklin
    John Franklin about 6 years
    Many people have upvoted Jonathan's comment about only checking the error if the method returns NO. I agree, this is true for released production code, and doubly so when sending the error to the user. The check was left out here partly for brevity and partly because the NSLog() call in this case is used for debugging during development.
  • Elise van Looij
    Elise van Looij over 5 years
    This code is quite old and doesn't take sandboxing into account. Also, check the warnings in Apple's Secure Coding Guide Race Conditions and Secure File Operations