Writing to temporary directory does not work - objective-c

I am trying to write a file to a temporary directory. I am doing it like this:
NSString *_location = NSTemporaryDirectory();
NSString *_guid = [[NSCalendarDate calendarDate] descriptionWithCalendarFormat:#"%m%d%Y%H%M%S%F"];
_guid = [_guid stringByAppendingString:#".png"];
NSString *_tempFilePath = [NSString stringWithFormat:#"%#/%#", _location, _guid];
NSData *_temp_data = [imgRep representationUsingType: NSPNGFileType properties: nil];
[_temp_data writeToFile:_tempFilePath atomically: NO];
But it doesn't work for me. It doesn't create the file. What's the problem?
P.S. I have tried to create a directory with a unique name in NSTemporaryDirectory, and then write to a file there, but it didn't work either.
I noticed that it don't creates a file anywhere. Tried to set location to user's documents folder, but its not working.

Path for writing an image is incorrect:
NSString *_tempFilePath = [NSString stringWithFormat:#"%#/%#", _location,_guid];
OR
NSString *_tempFilePath = [location stringByAppendingPathComponent:#"%#",guid];

If you write to a file inside potentially new directories, you have to first create the directory:
[[NSFileManager defaultManager] createDirectoryAtPath:_directoryPath
withIntermediateDirectories:YES
attributes:nil error:nil];
[_myData writeToFile:[_directoryPath stringByAppendingPathComponent:_fileName]
atomically:YES];

Related

Get the list of files from selected folders having sizes >100MB with their paths objective c

I want to get the list of all files with their paths & sizes for my mac system.
From that, I want to filter only those files which have file size above 100 MB.
I got the size of my system using the below code.
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *fileAttributes = [fileManager attributesOfFileSystemForPath:#"/" error:&error];
Now I want to get the list of files with their paths and sizes.
I searched a lot but those couldn't meet to my requirements.
Pleas help me on this.
Thanks in advance...
I got my solution with the following scenario.
Thanks CRD for giving me the idea.
First, I took a path of a folder. Then for getting subfolders only, I used NSDirectoryEnumerator and then I used the code to find the size of file.
Once I got the size of the file, then I checked the file size and added to my array.
So it worked.
NSString *Path = [NSString stringWithFormat:#"/Users/%#/",NSUserName()];
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:Path];
NSString *file;
NSMutableArray *arrList = [[NSMutableArray alloc]init];
while ((file = [de nextObject]))
NSLog(#"file %#",file);
Path = [NSString stringWithFormat:#"/Users/%#/",NSUserName()];
Path = [Path stringByAppendingString:file];
NSLog(#"path %#",Path);
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:Path error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"%lld",fileSize);
float sizeKB = ((float)fileSize / 1000);
NSLog(#"%f",sizeKB);
float sizeMB = ((float)fileSize / 1000000);
NSLog(#"%f",sizeMB);
if (sizeMB >= 100.0)
{
[arrList addObject:file];
[test addObject:file.lastPathComponent];
}
Hope it helps someone else also.

File count of a directory in Objective-C

I would like to know how can I get the total amount of archives inside of a directory, for example desktop.
I don't just want to know what's inside of the root of the directory, but also inside of its subfolders.
To just get the archives on the root of desktop I can do the following:
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSUInteger numberOfFileInFolder = [directoryContent count];
But I need to get also the count of its subfolders.
Can somebody help me?
Edit:
Finally I have coded this way:
-(int) numberOfDocumentsInPath: (NSString *) path{
NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator* totalSubpaths = [manager enumeratorAtPath: path];
NSLog(#"Path %# has %d documents", path, (int)[[totalSubpaths allObjects] count]);
return (int)[[totalSubpaths allObjects] count];
}
Try this:
NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:FolderPath error:nil];
Straight from the docs:
If you need to recurse into subdirectories, use
enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: as
shown in “Using a Directory Enumerator”).
Check also here:
Using a Directory Enumerator
Swift version:
var subs = NSFileManager.defaultManager().subpathsOfDirectoryAtPath(path, error: nil) as! [String]
var filecount = subs.count
println(filecount)
for sub in subs {
//Do stuff with files
}

Cocoa contents of directory

I have a group/folder with a series of text files. I need to get a path for each one so that I can read the contents, but I can't seem to get anything to work.
I've mucked about with [NSBundle pathsForResourcesOfType:#"txt" inDirectory:#"directoryName"] which gave me nothing but nulls or a single string that reads "Contents", [[NSFileManager defaultManager] enumeratorAtPath:#"directoryName"] which I have no idea what to do with once it's created, and [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil].
I can't figure out what I'm doing wrong, and at this point I'm just grasping at straws. I went through 20 or 30 pages on here, none of which has really helped.
I should note that this is a Cocoa Application, not iOS.
If you want to read files in arbitrary directories, the path enumerator works nicely. A bit old fashioned, but that has its charm, too.
NSString *docPath = #"/tmp";
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:docPath];
NSString *filename;
while ((filename = [dirEnum nextObject])) {
//Do something with the file name
}
If you want to read from well-known and defined directories in your home directory, then you can use NSSearchPathForDirectoriesInDomains:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex: 0];
This will give you your Documents directory, and when used with the snippet above, list all files in that folder and subfolders.
Notice that we are not really supposed to use our nice, old Unix paths any more, but instead refer URLs.
In that case, you get something like:
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *docURL = URLs[0];
NSDirectoryEnumerator *URLEnum = [[NSFileManager defaultManager] enumeratorAtURL: docURL includingPropertiesForKeys: nil options: 0 errorHandler: nil];
NSString *filename;
while ((filename = [URLEnum nextObject])) {
// ...
}
Notice that enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: has all sorts of useful parameters, which you can read about in the docs.
Lets just take 1 of your 3:
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"directoryName" error:nil]
You should include the error parameter and check what it contains
You need to supply a full path, not just a "directoryName"
As a result you'll get an array containing the file names of the files in the directory
So if you want the full path you can do:
NSString *directoryPath = ...;
NSArray *fileNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:...];
for(NSString *fileName in fileNames) {
NSLog(#"%#", [directoryPath stringByAppendingPathComponent:fileName]);
}
The problem was that when adding the folder, I needed to create a reference to the folder as well. Xcode does not default to this option. I had initially chosen to simply create groups, and this does not do the job.
If your group is in your current project you can use:
NSString *path = [[NSBundle mainBundle] pathForResourcesOfType:#"txt" inDirectory:#"directoryName"]
this should work for you, I noticed that you tried something similar, but make sure you're using mainBundle.

move/copy a file to iCloud

I am a beginner using Objective-C. I used the following code to move a file to iCloud but it gives an error that The operation could not be completed. The file exists.
//store the file locally in document folder
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [docPaths objectAtIndex:0];
filePath = [filePath stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSString *writeError = nil;
NSData * fileData = [NSPropertyListSerialization dataFromPropertyList:dataDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&writeError];
if ([fileData writeToFile:filePath atomically:YES]) {
NSLog(#"Server file is stored locally");
}else {
NSLog(#"%#", writeError);
}
// store the file in iCloud folder
NSURL *ubiquitousURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSString *tmpubiquitousURL = ubiquitousURL.absoluteString;
tmpubiquitousURL = [tmpubiquitousURL stringByAppendingString:fileName];
NSURL *ubi2 = [[NSURL alloc] initWithString:tmpubiquitousURL];
[[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I used the following to remove the file from iCloud but it gives an error that Cannot disable syncing on an un-synced file.
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I checked the availability of iCloud in my app delegate and it's available. The file is an XML file (.plist) and I have a local copy stored in NSDocumentDirectory.
Overall, I want to sync that file in iCloud so it will be accessible on all devices using my app. I have been struggling with this for 2 days, so if you could help me to resolve the problem I would appreciate it.
Note: I would rather not to use UIDocument, however, if that is the only option please let me know.
I also have the same problem while using the code
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
you have to change the code like below for this to work correctly
[[[NSFileManager alloc]init]setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:nil];
this code is for moving a file to icloud, also you should change the name of the file you are moving. It should not be same.

where does the text file I dragged to xcode go on the iphone/simulator?

I have some data in a .txt file that I dragged over to resources in xcode 4.2. I then use some methods that call upon this file, read it, and display it on the screen to the user. It works. My problem is writing to the end of the same file (aka updating the file based on something the user did) directly on the iphone/ the simulator. It does not write for I feel I am not calling upon the right location and perhaps method. This is my code to write to the end of file, if anyone knows why this is not working it would be tremendous help.
Thank you
-(void)updateFile:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//append filename to docs directory
NSString *myPath = [documentsDirectory stringByAppendingPathComponent:#"Mom.txt"];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:myPath];
dateCombinedString= [dateCombinedString lowercaseString];
writtenString= [[NSString alloc]initWithFormat:#", %#, %#, %#",dateString,trimmedString,ForDisplay];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[writtenString dataUsingEncoding:NSUTF8StringEncoding]];
[writtenString release]
}
The file you dragged to Xcode is inside your app resources. You can get the path to resource with this line of code:
NSURL* fileUrl = [[NSBundle mainBundle] URLForResource:#"Mom" withExtension:#"txt"];
However, you cannot modify the files in the resource directory therefore you should first copy that file to your document directory, then modify it with the code in the question.
Here is how you can copy file from resources if the file does not exist on the documents folder:
NSFileManager* fm;
fm = [NSFileManager defaultManager];
//only copy it from resources if it does not exits
if(![fm fileExistsAtPath:myPath]){
NSURL* myUrl = [NSURL fileURLWithPath:myPath];;
NSError* error = nil;
[fm copyItemAtURL:fileUrl toURL:myUrl error:&error];
//handle the error appropriately
}