I am trying to find out if a document exists by running
NSString *DocumentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFile = [[DocumentPath stringByAppendingPathComponent:FileName] retain];
NSLog(#"File : %#",theFile);
NSLog(#"FileName : %#", FileName);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:theFile];
NSLog(#"FileExists : %#", fileExists);
I know that the document is there, but I want to run this to find out and if say its been deleted are something then do something else. But all I get as my NSLog is
FileExists : (null)
I have looked at some tutorials and they say this is right. I'm I missing something?
This code work for me. saving file in Resources->file.txt
NSString *myFilePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/file.txt"];
NSLog(#"FileExist %d",[[NSFileManager defaultManager] fileExistsAtPath:myFilePath]);
Use this line instead of your's:
NSLog(#"FileExists : %d", fileExists);
%# format specifier is used for objects only, and prints in result of description method call for specified object
Related
In my application I want to implement a simple Alarm function. I know how to use UILocalNotifications, but I came across this source code with a like UI of the iPhone's native Clock app alarm area as well as it having a believe a type of data persistence. Two things I am not good at interface design and data persistence this source code has. But I downloaded it and started playing around with it to find the alarms are not persistent.
Download
Does anyone know how the source code can be adjusted so that it is persistent and the plist can be saved and read to and from? I am open to learning too, this area is somewhat unknown to me too. Thanks
I review your code and find issue that you not moved your "Alarms.plist" file form resource to document directory. we are not able to edit file which is in resource folder. so write following code in app delegate file.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFileName = #"Alarms.plist"; //Change this appropriately
NSString *oldPath = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];//[NSString stringWithFormat:#"%#/Inbox/%#", documentsDirectory, theFileName];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, theFileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath])
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
Perform save operation on file which is in Document directory folder.
try this code... to save plist from bundle to Document Directory
Notice that you will have "Unable to read... " just at the first app launch
- (NSMutableArray *)displayedObjects
{
if (_displayedObjects == nil)
{
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"Unable to read plist file: %#", path);
NSLog(#"copy Alarms.plist to: %#", path);
NSString *pathToSetingbundle = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];
[[NSFileManager defaultManager]copyItemAtPath:pathToSetingbundle toPath:path error:nil];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
NSLog(#"#disply obj %#", alarm);
}
}
return _displayedObjects;
}
Scroll down to EDIT 1. This top bit is irrelevant now.
This is my code:
NSMutableDictionary *dictionary = [self.media objectAtIndex:index];
NSLog(#"dictionary: %#", dictionary);
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
UIImage *originalImage = [UIImage imageWithContentsOfFile:originalImagePath];
NSLog(#"original image: %#", originalImage);
return originalImage;
And my NSLog:
dictionary: {
IsInPhotoLibrary = 1;
MediaType = 0;
OriginalImage = "/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg";
}
path: /var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg
original image: (null)
Any ideas why this might be coming out as null, despite everything appearing to be in place?
EDIT:
This is the code to write the image to file:
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Images/"];
NSString *name = [NSString stringWithFormat:#"%#.jpg", [JEntry generateUuidString]];
NSString *filePath = [path stringByAppendingPathComponent:name];
[fullImageData writeToFile:filePath atomically:YES];
NSLog(#"original image 2: %#", [UIImage imageWithContentsOfFile:filePath]);
}
This NSLog also comes out as null. So the problem lies here, most likely. Any ideas?
EDIT 2:
So, back-tracing even more now, and I've realised that it's because this fails:
[fullImageData writeToFile:filePath atomically:YES];
You can return a bool on that line, telling if it was successful or not, and it's returning NO for me. Any ideas why this might be?
EDIT 3:
The image that gets passed in is NULL. Trying to figure out where that's gone wrong now.
Almost certainly your file does not exist. Modify your code as follows to log if a file exists or not:
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:originalImagePath];
NSLog(#"file exists: %d", fileExists);
Possible Reasons:
The file at originalImagePath does not exist.
UIImage can not initialize an image from the specified file, because the data is corrupted (maybe the data is empty or incomplete)
the file can not be accessed because of iOS file permissions (i.e. when accessing files beyond the app sandbox)
Have you checked that the image file is really placed on path in dictionary? You may use the iExplorer utility for that.
Also pay attention to the file name case, so it's extension is 'jpg' not 'JPG'.
Finally you should check, whether it's a valid image file, by opening it with some image viewer.
are you sure that the jpg file "E9904811-B463-4374-BD95-4AD472DC71A6.jpg" is there in that folder?
try to open the app file installed in the iPhone/ipad simulator clicking on yourFile.app
with ctrl key and choose to open package contents the open your folder images...
to get a fast link to your documents folder:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"doc:%#",docsDir);
your app should be in its parent folder
In my iOS app I would like that user can download some jpg file via iTunes. So I've enabled UIFileSharingEnabled. But users are now able to put files in my app. I would like to block that. Is there a way to do that ?
Thanks !
Don't think you can block it, but you can just delete unwanted files when your app becomes active.
Put some code a bit like the sample below - filling in the test to avoid deleting the files you want to be available in iTunes.
Call this from within applicationDidBecomeActive: in your application delegate.
If you're more cautious you might want to check the user hasn't dropped a jpg file with the same name as the one you've parked there. You could test for sameness of date or some such or, if you've not got many files, just delete everything and write them again when the app becomes active.
- (void) removeUnwantedFiles;
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray* directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:inboxPath error:NULL];
if (!directoryContents || [directoryContents count] == 0)
{
return;
}
for (NSString* fileName in directoryContents)
{
if ( /* some test of filename to see if it's one of my kosher files */ ) continue;
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError* error = nil;
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
// NSLog(#"Deleting (%#): %#", success ? #"succeeded" : #"failed", [filePath lastPathComponent]);
if (!success)
{
NSLog(#"Error: %#", [error localizedDescription]);
}
}
}
I need to write a string into a file. For that, my code is:
-(void)writeToFile:(NSString *)fileName: (NSString *)data {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:appFile atomically:YES];
}
I am calling this method like this
ownServices *obj = [[ownServices alloc]init];
[obj writeToFile:#"iphone.txt" :#"this is mahesh babu"];
but it didn't write into the text file.
What's the reason? Can anyone please help me.
Thank u in advance.
The most likely problem is that the documents directory does not exist. Create it if it doesn't, then write to it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *parentDir = [paths objectAtIndex:0];
/* Create the parent directory.
* This is expected to fail if the directory already exists. */
(void)[[NSFileManager defaultManager]
createDirectoryAtPath:parentDir
withIntermediateDirectories:YES
attributes:nil error:NULL];
NSString *path = [parentDir stringByAppendingPathComponent:fileName];
/* Now write, and if it fails, you'll know why thanks to the |error| arg. */
NSError *error = nil;
BOOL ok = [data writeToFile:path options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(#"%s: Failed to write to %#: %#", __func__, path, error);
}
Even simpler would be to use the latest API, which will create the directory for you if it doesn't already exist:
NSError *error = nil;
NSURL *parentURL = [[NSFileManager defaultManager]
URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask
appropriateForURL:nil create:YES error:&error];
if (!parentURL) {
NSLog(#"%s: *** Failed to get documents directory: %#", __func__, error):
return;
}
NSURL *furl = [parentURL URLByAppendingPathComponent:fileName];
error = nil;
BOOL ok = [data writeToURL:furl options:NSDataWritingAtomic error:&error];
if (!ok) {
NSLog(#"%s: *** Failed to write to %#: %#", __func__, furl, error);
}
Firstly, you are calling your method strangely. Rename the method to
-(void)writeString:(NSString *) data toFile:(NSString *)fileName
and call it like so:
[obj writeString:#"this is mahesh babu" toFile:#"iphone.txt"];
Secondly, writeToFile:atomically: is deprecated, use writeToFile:atomically:encoding:error::
NSError *error = nil;
BOOL success = [data writeToFile:appFile atomically:YES encoding:NSUTF8Encoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
This way, you also see what the error is.
Your code looks OK. Use the debugger (or an NSLog statement) to verify the values of data and appFile. If data is nil, nothing will happen (including no errors) because sending a message to nil is a no-op. It's also possible that appFile is not the path you think it is.
Check the permissions of the directory you are trying to write to (ls -la). On the device you can't, but on the simulator you can. Is it read-only for you? Is it owned by another user?
Assuming that isn't the problem, try calling with atomically:NO. Atomic file writing is performed by writing a file, then renaming it to replace the old one. If the problem is there, that will isolate the problem.
Bonus Style Critique
Class names should start with an uppercase letter: OwnServices instead of ownServices
Although your method name is perfectly valid, it's unusual to have two parameters with no words to separate them. A name like writeToFile:string: would be better.
Don't name a variable data if it is meant to point to an instance of something other than NSData. It's confusing, and there's almost a better (more specific) word you can use beside "data".
I have some string that have a type like this
NSString *string1 = #"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";
if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"
i have implement a code like this :
NSString *subString1;
int count = [string1 length];
NSLog(#"count : %d", count);
subString1 = [string1 substringFromIndex:121];
but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"
how can i do to fix it??
To get the name of your app's parent directory you should try this instead:
NSString *appUUID = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] lastPathComponent];
This will work both on a device and Simulator.
If you need to get the full path to the Documents folder inside your app sandbox:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
If you need to append a path component to a path string:
NSString *projectPath = [documentsPath stringByAppendingPathComponent: #"Project"];
Please, take a look at NSString documentation, section "Tasks", "Working with Paths". It is a must-read.
you can use stringWithRange method of NSString.
subString1 = [string1 stringWithRange:NSMakeRange(startPos,yourLengthToSelect)];
or you can use componentSeparetedByString and break string using #"/". it will return array of string. get your desired string using array index.