简体   繁体   中英

NSFileHandle from NSURL failure

I'm trying to write some data to a file. I am able to obtain an NSURL from a file dialog and the NSURL obtained has the following value

file:///Users/brad/Documents/2016-05-04-06-53-35.csv

My code does the following:

NSURL*  myFile = [panel URL]; // is     file:///Users/brad/Documents/2016-05-04-06-53-35.csv
NSError *error = nil;   

NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];
NSLog(@"%@",error);

if (myFileHandle)
{
  ... // do something 
} 
else 
{
 NSLog(@"File operation failed");
}

I get an error which indicates the following

 Error Domain=NSCocoaErrorDomain Code=2 "(null)" UserInfo={NSFilePath=/Users/brad/Documents/

Also myFileHandle is nil.

Any clues ?

See the documentation for NSFileHandle fileHandleForWritingToURL:error: . You get back nil if the file doesn't already exist.

Use NSFileManager to first check if the file exists or not. If not, use NSFileManager createFileAtPath:contents:attributes: to create an empty file.

NSURL *myFile = [panel URL];
if (![[NSFileManager defaultManager] fileExistsAtPath:[myFile path]]) {
    [[NSFileManager defaultManager] createFileAtPath:[myFile path] contents:[NSData data] attributes:nil];
}

NSError *error = nil;   

NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM