Getting a -1 from open on iOS, why? - ios

The code is copied below. I am using the documents directory because I know you can write outside of your apps sandbox.
I also compare the string I was using to determine the path to one created by the NSFileManager and they are the same. What do you all think?
- (NSString *)documentsDirectory
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
- (void) whateverFunction{
NSString *memfileName = #"memmapfile.map";
NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:memfileName];
NSLog(#"Here is the filePath: %#", filePath);
NSLog(#"Other version: %s", [[NSFileManager defaultManager] fileSystemRepresentationWithPath:filePath]);
int memFD = open([filePath cStringUsingEncoding:NSASCIIStringEncoding], O_RDWR);
NSLog(#"I am getting -1 for memFD: %d", memFD);
}

I'd guess your file doesn't exist yet, so of course you can't open it. You should add O_CREAT to your open flags so that it gets created if it doesn't exist:
int memFD = open([filePath cStringUsingEncoding:NSASCIIStringEncoding], O_RDWR|O_CREAT);

Related

iOS clear caches ,simulator is effective,but when in real iPhone is not

iOS clear caches ,I delete the unuseful files use NSFileManager, but when I do it in simulator, it can clear all unuseful files, when I do it with a real iPhone(iPhone 5s),it was invalid, who can help me to solve this question? thank you very much!
code:
#define docPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
#define cachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
- (void)clearCaches
{
[self clearCachesWithFilePath:cachePath];
NSArray *docFileArr = [self getAllFileNames:docPath];
for (NSString * fileName in docFileArr) {
if (![fileName isEqualToString:#"mqtt.cer"]) {
[self clearCachesWithFilePath:[docPath stringByAppendingString:[NSString stringWithFormat:#"/%#", fileName]]];
}
}
}
- (NSArray *)getAllFileNames:(NSString *)dirPath{
NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:dirPath error:nil];
return files;
}
- (BOOL)clearCachesWithFilePath:(NSString *)path{
NSFileManager *mgr = [NSFileManager defaultManager];
return [mgr removeItemAtPath:path error:nil];
}
You are trying to delete the caches directory itself, instead get the list of contents in the caches directory and remove them one by one. Hope this helps.

Fails to copy writable plist file in document directory in ios8

Am trying to copy a plist file which has a http url written to it from app bundle to documents directory but its getting failed only in ios8 with message "NSInternalInconsistencyException', reason: 'The operation couldn’t be completed. (Cocoa error 4.)'.'" .Its working fine in ios7.Please guide what could be the reason.
//To get the plist file path within app
-(NSString *)ogPath
{
NSString *str = [[NSBundle mainBundle] bundlePath];
str = [str stringByAppendingPathComponent:#"configUrl.plist"];
return str;
}
//To get the plist file path within documents directory
-(NSString *)documentPath
{
NSString *str = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
str = [str stringByAppendingFormat:#"/Documents/configUrl.plist"];
return str;
}
//to copy plist file within app to documents directory
-(void)copytheplistfile
{
NSString *plistpath = [self ogPath];
NSString *docpath = [self documentPath];
NSFileManager *file = [NSFileManager defaultManager];
BOOL fileexist = [file fileExistsAtPath:docpath];
if(!fileexist)
{
NSError *err;
BOOL copyResult=[file copyItemAtPath:plistpath toPath:docpath error:&err];
NSLog(#"error:%#",[err localizedDescription]);
if(!copyResult)
NSAssert1(0, #"Failed to create writable plist file with message '%#'.", [err localizedDescription]);
}
}
In iOS 8 file system layout of app containers has been changed. Applications and their content are no longer stored in one root directory.
Change your document path
-(NSString *)documentPath
{
NSString *str=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
str = [str stringByAppendingFormat:#"/configUrl.plist"];
return str;
}

Proper way to giving name to file when [NSData writeToFile:] used

I'm using that code to save downloaded videos from internet to application document folder:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *save_it = [documentsDirectory stringByAppendingPathComponent:video_filename];
NSError *error;
BOOL success = [fileData writeToFile:save_it options:0 error:&error];
if (!success) {
NSLog(#"writeToFile failed with error %#", error);
}
it works, but if there is a slash "/" in the video_filename it breaks because of slash is directory seperator, I know.
For example when video_filename is : Best Video / Best Song Ever.3gpp , log says:
{NSFilePath=/Users/Apple/Library/Developer/CoreSimulator/Devices/5A7D36F5-6EDB-495D-9E8E-B9EB22E5357C/data/Containers/Data/Application/B1D0AC48-D84C-4A0D-9F09-08BF4C45DD32/Documents/Best Video / Best Song Ever.3gpp, NSUnderlyingError=0x7d339430 "The operation couldn’t be completed. No such file or directory"}
I don't know is there any other special character that will make crashing,
So what is the best way of cleaning these special characters from nsstring ?
We can make SEO friendly urls in PHP, I'm searching a function like that to do this.
The first problem I see here is that your file path includes some spaces. in the example you gave, the value of video_filename variable is "Best Video / Best Song Ever.3gpp" which includes spaces around the slash. You first have to delete the spaces, this might help you do that:
NSArray *components = [video_filename componentsSeparatedByString:#"/"];
for (NSInteger i = 0, i < components.count, ++i) {
NSString *string = components[i];
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
components[i] = string;
}
NSString *path = [components componentsJoinedByString:#"/"];
If I understood correctly, your video_filename might be either in the form xxx.3gpp or yyy/xxx.3gpp. If it's the format of yyyy/xxxx.3gpp, you first have to create a directory named yyyy and then save the file to that directory.
This might help you do that:
- (void)createDirectory:(NSString *)directoryName
atFilePath:(NSString *)filePath
{
NSString *filePathAndDir = [filePath
stringByAppendingPathComponent:directoryName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDir
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
NSLog(#"Create directory error: %#", error);
}
}
and the way you would use this is
[self createDirectory:components[0] atFilePath:documentsDirectory];
hope this helps!
So if your filename is actually "Best Video / Best Song Ever.3gpp" I am sorry but nothing easy comes to mind.
Now if Best Video is a folder where you will save your file you can use :
+(NSString*) getPathToFolder:(NSString*) folderName {
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:folderName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folderPath]) {
NSLog(#"Creating a new folder at\n%#", folderPath) ;
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
}
return folderPath ;
}
This will check if your folder exist or not, if it does not exists then it will create it.
it will return the path you will want to use to save your file.
Now regarding the naming of the files, using spaces is highly unadvisable, I suggest using :
NSString* pathWITHSpaces ;
NSString* pathWithoutSpaces = [pathWITHSpaces stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps a bit

contentsOfDirectoryAtPath returning null (iOS)

I'm having trouble displaying all files in directory. I did make a directory named "saves" in the same folder as all the app files.
I use this code:
NSError *error = nil;
NSArray *imageFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"saves" error: &error];
NSLog(#"FILES: %#", imageFiles);
Can anyone help me out, because this code logs "null" - so pretending there isn't anything in the folder, but in the folder I made one directory and two empty files.
NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Check for files in the test directory:
NSArray *filePaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:#"test"] error:nil]];
It looks to me like you're trying to save a file in your main bundle. Are you doing this on the simulator or on an actual device? You can't save files in your main bundle on a device.
NSError *error = nil;
NSArray *imageFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"saves" error: &error];
Not sure what ypou expect this to do...
NSLog(#"FILES: %#", imageFiles);
try this
NSLog(#"Image file count %d", [imageFiles count]);
for ( int i - 0; i <= [imageFiles count] - 1; i++)
{
NSLog(#"file name : %#", [imageFiles objectAtIndex:i]);
}
code NOT tested but I think you get the idea...

NSFileManager creating folders herarichy & not saving plist [open]

The problem is appearing on device not on simulator.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Plist1.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"documentsDirectory --- %#", documentsDirectory);
NSLog(#"path --- %#", path);
#try
{
if (![fileManager fileExistsAtPath:path])
{
[fileManager copyItemAtPath:documentsDirectory toPath:path error:&error];
}
}
#catch (NSException *exception)
{
NSLog(#" [exception description] -- %#", [exception description]);
}
#finally {
}
[dictEmot writeToFile:path atomically:YES];
// To verify
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSLog(#"[dict allKeys] My plist ----- %#", [dict allKeys]);
Above is the code which I have written to save two plist files in my documents directory. same method I use to save my second plist.
[self savePlist:plist1];
[self savePlist:plist2];
My problem is whenever I try to save second plist it creates hierarchy of folders inside documents directory and also not saves my plist2 file with it contents.
once it complets the 2nd method call, my app documents directory looks like below,
Documents
-> plist1
-> plist1
.
.
.
-> plist1
-> plist1
other files
I treid doing on main thread also but same result.
its not even printing exception.
What is my mistake ?
- Why its creating hierarchy ?
I don't know much about iOS but I think your problem is with stringByAppendingPathComponent:#"Plist1.plist" Check your documentation as I am supscious by the word Appending and even if you send new file name as you are hardcoding the value of the filename to Plist1.plist...
Still I am not sure as I have not done iOS coding for a long time now.

Resources