I want to move a file from a folder to another folder
I used
[[NSFileManager defaultManager]moveItemAtPath:#"Folder/Filename.fileExtension" toPath:#"FolderToMoveTheFile" error:nil];
Is there something else to type in error: ?
Why it isn't move my file?
You would get the error by doing this:
NSError* error;
if (![[NSFileManager defaultManager]moveItemAtPath:#"Folder/Filename.fileExtension" toPath:#"FolderToMoveTheFile" error:&error])
{
// handle error, typically using the NSError object pointed to by the error variable
// In an app, you might want to pass it to a -presentError:... method of a convenient responder
// This is good enough for debugging:
NSLog(#"failed to move file: %#", error);
}
The second path that goes after toPath: must be the path including the file name at the destination. It is not correct to just specify the path to the directory into which you want to move the file.
Also, you should typically use absolute paths, not relative paths. You can use relative paths but that then depends on the current working directory for the process. That's arbitrary for apps launched from the Finder or Dock. It's really only meaningful for command-line tools launched from a shell (e.g. a Terminal window) where the user might be expected to cd to a directory and then provide relative paths as command-line arguments.
Related
I have a macOS/Objective-C/Cocoa application. We want to spawn external applications, like TextEdit, to edit files created by this app. I'm creating these files by copying it into my ~/Documents directory (eventually I'd like to put it elsewhere, but I'm trying to simplify) with:
NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager copyItemAtPath:srcPath toPath:destPath error:&err];
NSDate *sourceModified = [self lastModificationOfFile:srcPath];
NSDictionary * attr = #{ NSFileModificationDate : sourceModified,
NSFileImmutable : [NSNumber numberWithBool:NO],
NSFilePosixPermissions : [NSNumber numberWithUnsignedLong:0666],
};
[defaultManager setAttributes:attr ofItemAtPath:destPath error:nil];
When I open this file in TextEdit, the window header says "filename.txt - Locked". Editing the document gives me the "Are you sure you want to modify the document in place?" dialog. I select "Overwrite", but then attempts to save give me "The document "filename.txt" could not be saved. You don't have permission."
However, this writes a "filename.txt.sb-a69dcdc5-7V6D2g" (or similarly named) file into my Documents directory. And files created from the bash shell with "echo blablabla > filename.txt" in that same directory open just fine.
I have tried many variations on those attributes. I cannot see any difference between the files which work and those which display "... - Locked" using "ls -la# filename.txt" or "xattr", even side-by-side in the same directory.
Clearly I'm up against some sandboxing issue with the files I create, but all of my search results are about the other side of this problem.
Argh. I found this: Why does TextEdit open HTML files as locked. Apparently because of the content of my .txt file, TextEdit was interpreting it as an HTML document and treating it differently based on that. Replaced the content of the file with things that didn't look like HTML and I'm able to edit the document now.
I am trying to write a Mac app that converts files. I am stuck at the beginning because my app cannot open local files, at least while running in the debugger. I use the NSOpenPanel to create a valid file NSURL:
“file:///Volumes/Seagate_1tib/projects/dataskunk/wasteproduct.xml”
But somewhere in xcode, or the debugger or whatever, this gets mangled into
"/Users/charlweed/Library/Developer/Xcode/DerivedData/dataskunk-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug/file:/Volumes/bigdrive/dataskunk/wasteproduct.xml"
Reading the file then fails with a "No such file or directory error".
How do I prevent this mangling during development?
For example, this gives the error, no matter what file is chosen:
let fileResult = openFileDialog("Choose File", message:"Message")
let xmlInFileURLOpt: NSURL? = NSURL.fileURLWithPath(fileResult)
if let xmlInFileURL = xmlInFileURLOpt
{
var xmlFileError: NSError?
if !xmlInFileURL.checkPromisedItemIsReachableAndReturnError(&xmlFileError){
println("\(xmlFileError)")
return
}
}
The answer is that NSURL.fileURLWithPath() does not take a URL-path as an argument, only a filesystem-path. So "file:///Volumes/disk/file.xml" is wrong, "/Volumes/disk/file.xml" is correct.
The mangling is NSURL prefixing the current directory onto what it thinks is a relative filesystem-path String.
I want my users to be able to drop a folder into my OSX app. I then look at all the files in the directory and its subdirectories. That works fine but not when there is an alias in the directory. The alias is resolved correctly (Thanks to Matt Gallagher, shame on you Apple) but the enumerator does not allow me to do enumerate the target directory (it just returns no elements and the error below). Here is some sample code:
-(void)enumDirAtPath:(NSString*)path {
NSString* file_enum = nil;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
while (file_enum = [enumerator nextObject])
{
NSString* file = [[NSString stringWithFormat:#"%#/%#",path,file_enum] stringByResolvingSymlinksAndAliases];
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath:file isDirectory: &isDirectory];
if (!isDirectory) {
NSLog(#"Adding file: %#",file);
} else {
NSLog(#"Found dir: %#",file);
[self enumDirAtPath: file];
}
}
}
the same code with enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: gives me this error:
error: Error Domain=NSCocoaErrorDomain Code=257 "The file “Musik”
couldn’t be opened because you don’t have permission to view it."
UserInfo=0x1094cf670
{NSURL=file://localhost/Users/david/Desktop/Musik,
NSFilePath=/Users/david/Desktop/Musik, NSUnderlyingError=0x1094d43f0
"The operation couldn’t be completed. Operation not permitted"}
Even If I just dispatch_async the recursive call it won't let me do it. Is there any way I can just iterate over a directory and get all the content?
Note: I am fully aware that this could result in infinite loops. This code is just to illustrate the problem.
I‘m pretty damn sure the answer is right there in the error message:
The file “Musik” couldn’t be opened because you don’t have permission to view it.
Reveal the destination of the alias in the Finder application and check its permission via “Get Info” or ls -l# in the Terminal — I’d bet that your user account david is not being granted one of the following permissions:
read
execute
list
The last one will typically not be visible on the command line except in combination with an explicit deny-access-control-entry.
My program pulls in a C style string from a file, converts it to an NSString and places it in an NSMutableArray. Every time I run the program, either Debug or Release version, in XCode it runs perfectly. However every time I run it outside of XCode it crashes and the report says "-[NSPlaceholderString initWithString:]: nil argument'". This is the line of code where the problem occurs.
input = [[[NSString alloc] initWithString:[NSString stringWithUTF8String:data->acctNames]] mutableCopy];
I have also tried this:
input = [NSString stringWithUTF8String:data->acctNames];
Can anyone explain what is wrong with this?
Sounds like the file you are opening doesn't exist and the string is not being initialized. You should look at the file path and see if it is an absolute path. Maybe you are trying to open the file in a local directory and the file doesn't exist in the run directory after you have built the binary.
I've tried the following
[[NSFileManager defaultManager] copyItemAtPath:#"whatever.txt"
toPath:#"/Volumes/MyDrive" error:©Error];
This gives me the error "The operation couldn’t be completed. File exists"
If I try to copy it to "/Volumes/MyDrive/testFolder" everything copies to testFolder just fine.
I've tried the following
[[NSFileManager defaultManager] copyItemAtPath:#"whatever.txt"
toPath:#"/Volumes/MyDrive" error:©Error];
This gives me the error "The operation couldn’t be completed. File exists"
First, as KennyTM already told you, the error message is telling you one possible cause of the problem: The file already exists. The destination must not exist; you must either delete it or give a different name for the destination.
Second, there is another possible cause of the problem: You only specified the destination folder, not the complete destination path. You must specify the complete destination path, including the destination filename. Quoth the documentation:
“When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename.”
If you want the copy to have the pathname /Volumes/MyDrive/whatever.txt, that's the pathname you need to pass.
Also, don't forget to check whether the copy succeeded before you attempt to look at the error object. You should only look at the error object if the copy failed.
If I try to copy it to "/Volumes/MyDrive/testFolder" everything copies to testFolder just fine.
I think you'll find that testFolder is, in fact, a file—specifically, it's the copy of whatever.txt.
Isn't the error very clear? "The operation couldn’t be completed. File exists". The doc of -copyItemAtPath:… states that:
The file specified in srcPath must exist, while dstPath must not exist prior to the operation.
You need to call -removeItemAtPath:error: to remove the destination file if you want to override it.