how to handle the file error? - iphone

I am getting a file error when i am trying to write a string into a file:
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent:fileName];
if ([file fileExistsAtPath: docFile] == YES)
{ if(![formatedlogStr writeToFile:LOG_FILE_V1 atomically:YES encoding:NSUTF8StringEncoding error:&error])
{
NSLog(#"Error: %#", [error userInfo]);
}
}
this gives me an error :
Error: {
NSFilePath = "error_log_V1.txt";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=13 \"The operation couldn\U2019t be completed. Permission denied\"";
NSUserStringVariant = Folder;
How to solve the problem I don't know.
Can anybody help me?

You're correctly finding a path within your documents directory, but you are trying to log the information to a bare path. You should follow the same procedure to build a path to a file within your sandbox for the log file and use that instead of LOG_FILE_V1.

Related

Upload audio file from document directory to iCloud

I am trying to upload audio file like session1.mp3 from document directory to iCloud using the following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"session1.mp3"];
NSURL* sourceURL = [[NSURL alloc] initFileURLWithPath:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSLog(#"File found!");
}
else
{
NSLog(#"File not found!");
}
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq)
{
NSLog(#"iCloud access at %#", ubiq);
NSError* error = nil;
NSURL *destinationURL = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"session1.mp3"];
[[NSFileManager defaultManager] setUbiquitous:YES
itemAtURL:sourceURL
destinationURL:destinationURL
error:&error];
if(error != nil)
{
NSLog(#"Error while uploading the file: %#", error);
}
else
{
NSLog(#"File ulpoaded successfully");
}
}
else
{
NSLog(#"No iCloud access");
}
The file i am trying to upload exists (the "File found" is printed), but the uploading it to iCloud generates the following error
Error while uploading the file: Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x1f03d9f0 {NSURL=file://localhost/var/mobile/Applications/20D82CDA-021E-4067-B9AB-C0197A6FA834/dox.app/session1.mp3, NSUnderlyingError=0x1f03d990 "The operation couldn’t be completed. Operation not permitted"}
Nothing inherently wrong with your code.
Are you checking the ubiquityIdentityToken anywhere to make sure it is available?
[ [ NSFileManager defaultManager ] ubiquityIdentityToken ];
Also, in your logging of a successful setUbiquitous, "upload successful" is not exact: the item was simply moved to the ubiquity container, and will be uploaded when the demon feels like it. You can check on the upload status through NSMetadataQuery.
You are not supposed to use iCloud to store this media.
Please review the Guidelines given by Apple.

how to create a directory in iphone settings in objective c

I am new programmer in objective c. I want to create "Download" directory inside the i phone(path : setting (i phone setting directory))I want to know is it possible?. I am using i phone simulator to test the program.
Another question is, How can I access created directory in i phone simulator. Below contains code I tried to create folder in i phone. But I can not access that directory by using i phone simulator. what the wrong of this code?
NSString *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Test"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
you can create Directory in to Document Directory as sub Folder like this way:-
-(IBAction)CreatDirInDocDir
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dir = [NSString stringWithFormat:#"%#",DirName];
NSString *path = [documentsDirectory stringByAppendingPathComponent:dir];
NSError *error;
if ([filemgr fileExistsAtPath:path ] == YES){
}
else
{
NSLog (#"File not found");
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
}
}
when ever you create directory in to Document directory folder then you can get all list of Created Custom directory like this way:-
//Get all Directory
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSMutableArray *directoryList=[[NSMutableArray alloc]init];
for ( NSString *direPath in filePathsArray )
{
NSString *path = [documentsDirectory stringByAppendingPathComponent:direPath];
BOOL isDir = NO;
[fileMan fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
NSLog(#"log path ==%#",fullPath);
[directoryList addObject:fullPath];
}
}
NSLog(#"list path ==%#",directoryList);
Now you have array of all directory you can get any directory with index :)
Hope its helps you
All The method posted here are correct and there are tons of answers about them, but I'd like to warn you about a concept. Since The introduction of iCloud, Apple started to reject applications that saves a lot of data in document directory, when they are used by means of caches or they could be downloaded again later. The problem here is that you can backup your ios devices on the cloud and document directory is one of the backupped. Can you image yourself backupping one GB on application on the cloud? That's the explanation about apple rejects. To avoid that temp/redownloadable/cached data should be saved in cache directory. This useful dir is freed when the device is running out of space on "disk", like when you try to install a new app and you don't have enough space. So this is ok if your data can be downloaded again and are not indispensable. the other way around is to keep data in the document directory but telling the system to do not backup them, this is possible adding a special flag to the doc subdirectory where you saved the file, here is how link , pay attention that this methods is only available from 5.0.1 so you need to check its existence if you target lower ioses. In this case the system will not free your data and not backup them this is safe for apple guidelines. hope this helps
For creating directory you can use:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Test"];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
{
NSLog(#"Couldn't create directory error: %#", error);
}
For getting the files inside that directory you can use:
NSArray *datArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:&error];
if(error)
{
NSLog(#"Could not get list from directory, error = %#",error);
}
Here all file names will be in the datArray.
No need append '/' . Just Use
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Test"];
Try This
NSArray *dirPath;
NSString *docsDir;
NSFileManager *filemgr = [NSFileManager defaultManager];
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
if ([filemgr changeCurrentDirectoryPath: docsDir] == NO)
{
NSLog(#"Error");
}else {
NSString *currentPath = [filemgr currentDirectoryPath];
NSLog(#"%#",currentPath);
}
NSString *dataDirectory = [docsDir stringByAppendingPathComponent:#"Test"];
if ([filemgr fileExistsAtPath:dataDirectory]){
NSLog(#"dir Exist");
}else{
NSLog(#"Creating Dir");
[filemgr createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
Anyone want to show your created directory in i phone simulator follow bellow steps :
Go to finder
Click Command +Shift + g
Type ~/Library then click Go
Open Application Support --> i phone simulator
Then you can find your created applications and directories..

Error while moving file in Cache Directory in Iphone

I am facing problem to move image file in Cache Directory. My requirement is when I am deleting one file for example image3.png then all other files (suppose there is 9 files like image1.png,image2.png,.....image9.png)after that position (image4.png,....,image9.png) will move to their previous position. I want to rename that files like image4.png to image 3.png.
Below is my code
NSError *error=nil;
NSString *imgName = [NSString stringWithFormat:#"image%d.png",3];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:imgName];
[fileManager removeItemAtPath: fullPath error:NULL];
for (int i=3; i<=9 ; i++) {
NSString *imgName1 = [NSString stringWithFormat:#"image%d.png",i];
NSString *getImagePath1 = [documentsDirectory stringByAppendingPathComponent:imgName1];
NSString *imgName2 = [NSString stringWithFormat:#"image%d.png",i+1];
NSString *getImagePath2 = [documentsDirectory stringByAppendingPathComponent:imgName2];
if ([fileManager moveItemAtPath:getImagePath2 toPath:getImagePath1 error:&error] != YES)
NSLog(#"Unable to move file: %#", [error localizedDescription]);
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileManager contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}
But its showing following error
Unable to move file: The operation couldn’t be completed. (Cocoa error 516.)
Please help me .
Thanks in advance.
From NSFileManager docs on moveItemAtPath:toPath:error::
If an item with the same name already exists at dstPath, this method
aborts the move attempt and returns an appropriate error
Delete the file you want to overwrite first.

Read/write file in Documents directory problem

I am trying to write a very basic text string to my documents directory and work from there to later save other files etc.
I am currently stuck with it not writing anything into my Documents directory
(In my viewDidLoad)
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSString *text = #"My cool text message";
[[NSFileManager defaultManager] createFileAtPath:textPath contents:nil attributes:nil];
[text writeToFile:textPath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"Text file data: %#",[[NSFileManager defaultManager] contentsAtPath:textPath]);
This is what gets printed out:
2011-06-27 19:04:43.485 MyApp[5731:707] Text file data: (null)
If I try this, it also prints out null:
NSLog(#"My Documents: %#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL]);
What have I missed or am I doing wrong while writing to this file?
Might it be something I need to change in my plist or some frameworks/imports needed?
Thanks
[EDIT]
I passed a NSError object through the writeToFile and got this error:
Error: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x12aa00 {NSFilePath=/var/mobile/Applications/887F4691-3B75-448F-9384-31EBF4E3B63E/Documents/file1.txt, NSUnderlyingError=0x14f6b0 "The operation couldn’t be completed. Not a directory"}
[EDIT 2]
This works fine on the simulator but not on my phone :/
Instead of using NSFileManager to get the contents of that file, try using NSString as such:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray objectAtIndex:0];
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSError *error = nil;
NSString *str = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"There was an error: %#", [error description]);
} else {
NSLog(#"Text file data: %#", str);
}
Edit: Added error checking code.
How are you getting documentsDirectory?
You should be using something like this:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [pathArray lastObject];
Put an NSLog statement after every line where you are setting a variable's value, so that you can inspect those values. This should help you quickly pinpoint where things start to go wrong.
The problem got solved by setting a non standard Bundle ID in die info.plist
I used the Bundle ID from iTunes Connect for this specific app. Now everything works perfectly.
You can also use NSFileHandle for writing data in file and save to document directory:
Create a variable of NSFileHandle
NSFileHandle *outputFileHandle;
use the prepareDataWrittenHandle function with passing file name in parameter with file extension
-(void)prepareDataWrittenHandle:(NSString *)filename
{
//Create Path of file in document directory.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
//Check file with above name is already exits or not.
if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath] == NO) {
NSLog(#"Create the new file at outputFilePath: %#", outputFilePath);
//Create file at path.
BOOL suc = [[NSFileManager defaultManager] createFileAtPath:outputFilePath
contents:nil
attributes:nil];
NSLog(#"Create file successful?: %u", suc);
}
outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath];
}
then write the string value to file as:
//Create a file
[self prepareDataWrittenHandle:#"file1.txt"];
//String to save in file
NSString *text = #"My cool text message";
//Convert NSString to NSData to save data in file.
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding]
//Write NSData to file
[_outputFileHandle writeData:data];
//close the file if written complete
[_outputFileHandle closeFile];
at the end of file written you should close the file.
You can also check the content written in file as NSString for debug point of view as mention above by #Glenn Smith:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:#"file1.txt"];
NSError *error;
NSString *str = [NSString stringWithContentsOfFile:outputFilePath encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"There was an error: %#", [error description]);
} else {
NSLog(#"Text file data: %#", str);
}

iPhone:Removing/Deleting SQLite database?

I know how to create sqlite database, inserting data into it, deleting row into it etc. through iPhone development, but i am trying to remove the entire database itself programmatically, but not getting any helps. Please someone guide me how to delete/remove the entire sqlite database itself from device thru code.
Thank you!
If your db is in Documents you can try:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath =  [documentsDirectory stringByAppendingPathComponent:#"youdb.db"];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
Try
NSError *err;
NSFileManager *fm = [NSFileManager defaultManager];
err = nil;
NSString *deleteFileName = [NSString stringWithFormat:#"%#/FileName",[[NSBundle mainBundle] resourcePath]];
NSURL *url = [NSURL fileURLWithPath:deleteFileName];
[fm removeItemAtPath:[url path] error:&err];
if(err)
{
NSLog(#"File Manager: %# %d %#", [err domain], [err code], [[err userInfo] description]);
}
else
{
NSLog(#"File %# deleted.",fileName);
}
If you're using Xamarin in Visual Studio this will work nicely.
string _FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "databaseFileName.db3");
File.Delete(_FileName);
Is the Database file in your document directory and not in the Bundle the you can use NSFileManager to delete the file.
Make sure that the isn't open by any progress.
If you want to delete the whole database you'll have to locate it in the file system and delete it there.