The documentation for [NSFileManager copyPath:toPath:handler:], a deprecated method, says:
File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also copied.
This is not stated in the docs for copyItemAtURL:toURL:error: or copyItemAtPath:toPath:error:. But is it also true of those methods? If I have file foo/bar.txt with a modified date of one hour ago, and I copy it to baz/bar.txt, and then I get the modification date of baz/bar.txt using attributesOfItemAtPath, will it be now or one hour ago?
I tested this with this code:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *firstPath = [documentsPath stringByAppendingPathComponent:#"test1.dat"];
NSData *data = [#"Foobar Test" dataUsingEncoding:NSUTF8StringEncoding];
[data writeToFile:firstPath atomically:YES];
NSDate *firstModDate = (NSDate *)[[[NSFileManager defaultManager] attributesOfItemAtPath:firstPath error:nil] objectForKey:NSFileModificationDate];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSString *secondPath = [documentsPath stringByAppendingPathComponent:#"test2.dat"];
[[NSFileManager defaultManager] copyItemAtPath:firstPath toPath:secondPath error:nil];
NSDate *secondDate = (NSDate *)[[[NSFileManager defaultManager] attributesOfItemAtPath:secondPath error:nil] objectForKey:NSFileModificationDate];
NSLog(#"Original date: %.2f", firstModDate.timeIntervalSince1970);
NSLog(#"New date: %.2f", secondDate.timeIntervalSince1970);
});
And it logs the same date twice. So it does indeed preserve modification date metadata. Tested with iOS 13.3.
Related
I am using this to get the log files data:
NSFileHandle *file;
file = [NSFileHandle fileHandleForReadingAtPath:#"~/Library/Application Support/RepoManager/*.log"];
NSData *filedata;
filedata = [file readDataToEndOfFile];
NSString *logC;
logC = [[NSString alloc] initWithData:filedata encoding:NSASCIIStringEncoding];
And than write them using this:
NSString *formatString = #"Log: %#";
return [NSString stringWithFormat:formatString, *logC.stringValue];
But it says logC does not contain a string value
NSString does not define a .stringValue property, and even if it did, *logC.stringValue would have no useful meaning in Objective-C. logC itself is what you want to be using as your format parameter. (It's the string containing the contents of the log file.)
can anyone help me in getting the formatted date from the parsed XML.
I can format that using NSXML formatter but now i am found difficulty in using it through Google XMl parser. where i can get the values through the key but i need that in a formatted way,
return [NSDictionary dictionaryWithObjectsAndKeys:
[[[xmlItem elementsForName:#"title"] objectAtIndex:0] stringValue], #"title",
[[[xmlItem elementsForName:#"link"] objectAtIndex:0] stringValue], #"link",
[[[xmlItem elementsForName:#"pubDate"] objectAtIndex:0] stringValue], #"Date",
nil];
here the pubDate is returned as such from xml with hr,min,sec i need the date alone.
Thanks in advance!!!!
I got the answer
//cell.textLabel.text = [item objectForKey:#"pubDate"];
NSString *yourXMLDate = [item objectForKey:#"pubDate"];
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"E, d LLL yyyy HH:mm:ss Z"];
NSDate *inputDate = [inputFormatter dateFromString:yourXMLDate];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"MMM dd, HH:mm a"];
NSString *outputDate = [outputFormatter stringFromDate:inputDate];
cell.textLabel.text=outputDate;
where this results in Oct 12, 12:30 AM. whatever parser used in the xcode this works fine....
I'm executing a zip command from within my app using NSTask. It's passed as arguments some paths which point to the files/folders to be zipped.
The problem is that without the -j option, the final zip ends up with absurd filepaths inside the zip, (like "/private/var/folders/A5/A5CusLQaEo4mop-reb-SYE+++TI/-Tmp-/9101A216-5A6A-4CD6-A477-E4B86E007476-51228-00014BCB9514323F/myfile.rtf"). However, if I add the -j option, then I constantly run into name collisions if any file anywhere deep inside a nested folder has
I've tried setting the path before executing the NSTask:
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
In the hope that the documentation for zip was telling the truth:
By default, zip will store the full path
(relative to the current directory)
But this did not work as expected. Adjusting settings of -j and -p and -r simply produces the above mentioned problems in different combinations.
QUESTION:
How can I take a set of directories like
/some/long/path/sub1/file1.txt
/some/long/path/sub2/file1.txt
and zip them into a zip whose contents are
/sub1/file1.txt
/sub2/file1.txt
Thanks for any advice on the subtleties of zip.
-----EDIT
One other thing I forgot to add is that the original directory being passed is "path", so the desired outcome is also to my mind the expected outcome.
Instead of
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
use -[NSTask setCurrentDirectoryPath:] prior to launching the task. For example:
NSString *targetZipPath = #"/tmp/foo.zip";
NSArray *args = [NSArray arrayWithObjects:#"-r", targetZipPath,
#"sub1", #"sub2", nil];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/zip"];
[task setArguments:args];
// set path to be the parent directory of sub1, sub2
[task setCurrentDirectoryPath:path];
…
This is not a universal solution, in that it won't handle multiple directories well, but the solution I'm using for a single directory of unknown contents (ie, mixed files/folders/bundles) is to enumerate the contents of the directory and add them individually as arguments to zip, rather than simply zipping the entire directory at once.
Specifically:
+ (BOOL)zipDirectory:(NSURL *)directoryURL toArchive:(NSString *)archivePath;
{
//Delete existing zip
if ( [[NSFileManager defaultManager] fileExistsAtPath:archivePath] ) {
[[NSFileManager defaultManager] removeItemAtPath:archivePath error:nil];
}
//Specify action
NSString *toolPath = #"/usr/bin/zip";
//Get directory contents
NSArray *pathsArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[directoryURL path] error:nil];
//Add arguments
NSMutableArray *arguments = [[[NSMutableArray alloc] init] autorelease];
[arguments insertObject:#"-r" atIndex:0];
[arguments insertObject:archivePath atIndex:0];
for ( NSString *filePath in pathsArray ) {
[arguments addObject:filePath]; //Maybe this would even work by specifying relative paths with ./ or however that works, since we set the working directory before executing the command
//[arguments insertObject:#"-j" atIndex:0];
}
//Switch to a relative directory for working.
NSString *currentDirectory = [[NSFileManager defaultManager] currentDirectoryPath];
[[NSFileManager defaultManager] changeCurrentDirectoryPath:[directoryURL path]];
//NSLog(#"dir %#", [[NSFileManager defaultManager] currentDirectoryPath]);
//Create
NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:toolPath];
[task setArguments:arguments];
//Run
[task launch];
[task waitUntilExit];
//Restore normal path
[[NSFileManager defaultManager] changeCurrentDirectoryPath:currentDirectory];
//Update filesystem
[[NSWorkspace sharedWorkspace] noteFileSystemChanged:archivePath];
return ([task terminationStatus] == 0);
}
Again, I make no claims this is bulletproof (and would love improvements) but it does work at correctly zipping any single folder.
The following code returns a NSCocoaErrorDomain with error code 513 (NSFileWriteNoPermissionError) when running from xcode.
NSError *error;
[[NSFileManager defaultManager]
createDirectoryAtPath:#"/Library/Application Support/myapp"
withIntermediateDirectories:YES
attributes:nil
error:&error];
This is on a Mac OS X 10.6.7, the specified directory does not exist, and my user has admin privileges.
The purpose is to save application support files that are shared among users. Shouldn't there be write permissions to create this directory?
No, that's the system's Library folder. You need the user's Library, at "~/Library/". You could try:
[NSHomeDirectory() stringByAppendingPathComponent:#"Library/Application Support/myapp"]
or:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString * appSupportPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myapp"];
Just for one more option, you can also get a URL from the file manager:
NSFileManager * fm = [[NSFileManager alloc] init];
NSArray * urls = [fm URLsForDirectory:NApplicationSupportDirectory inDomains:NSUserDomainMask];
NSURL * appSupportURL = [urls objectAtIndex:0];
I'm trying to use this line of code
[UIImagePNGRepresentation(image, 1.0) writeToFile:pngPath atomically:YES];
But obviously pngPath is undeclared. So I have to use stringByAppendingPathComponent.
I googled examples of this, and I found this
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName] ];
[myPlistPath retain]
;
The problem is that I don't have a plist file, because I don't need one. How can I solve all these issues and writeToFile the UIImage image?
I don't fully understand your question, but to get the full path where your file should be saved, you could try this:
NSString *file = #"myfile.png";
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [directory stringByAppendingPathComponent: file];
and then:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];