How to Get file From one Document Folder to Another Document Folder? - iphone

In my Application i save Recording file in Document Directory.then later gets all these file from document directory and showing all these files in My mainClass where i have UITableview for it.
When i Click on any row of this mainClass Tableview it goes to next Class where i play this file,delete this file and Send this file to my Favourite Recording Class where i have Tableview for it.Now my play button action method and delete Button action method works fine but i Don't know how to send this file to my Favurite Class Tableview.now i show here my delete button Code through which we can get the basic idea.
-(IBAction)deleteFile
{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *documentPath = [docsDir stringByAppendingPathComponent:#"MyRecordings"];
NSString *soundFilePath = [documentPath stringByAppendingPathComponent:fileToPlay];
recordedTmpFile = [NSURL fileURLWithPath:soundFilePath];
[[NSFileManager defaultManager] removeItemAtURL:recordedTmpFile error:nil];
}
As my Delete button Code show how we delete the Current Recording file which i selected from MainTableview .Now if the user Want to send the current Recording file to my Favourite Class Tableview instead of Deleting it then Whether i use the another Document folder here if answer is yes? then how we can save the Current file(recordedTmpFile) in this new Document folder.
-(IBAction)AddToFavourite
{
NSArray *dirPaths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir1 = [dirPaths1 objectAtIndex:0];
NSString *documentPath1 = [docsDir1 stringByAppendingPathComponent:#"MyFovouriteRecordings"];
// How to pass here the Current Recording File (recordedTmpFile) to this new document Folder.
}
When i NSlog recordedTmpFile it show result :file://localhost/Users/Umar/Library/Application%20Support/iPhone%20Simulator/4.2/Applications/9219677A-B0E3-4B78-B2E5-FEA49D689618/Documents/MyRecordings/06:Dec:12_05:54:07%20PM+Active%20song
Any Help will be appriated.Thanks

-(IBAction)AddToFavourite {
NSArray *dirPaths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir1 = [dirPaths1 objectAtIndex:0];
NSString *documentPath1 = [docsDir1 stringByAppendingPathComponent:#"MyFovouriteRecordings"];
NSString *soundFilePath1 = [documentPath1 stringByAppendingPathComponent:fileToPlay];
// How to pass here the Current Recording File (recordedTmpFile) to this new document Folder.
// First check if the directory existst
if([[NSFileManager defaultManager] fileExistsAtPath:documentPath1]==NO) {
NSLog(#"Creating content directory: %#",documentPath1);
NSError *error=nil;
if([[NSFileManager defaultManager] createDirectoryAtPath:documentPath1 withIntermediateDirectories:NO attributes:nil error:&error]==NO) {
NSLog(#"There was an error in creating the directory: %#",error);
}
}
//then get the origin file path
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *documentPath = [docsDir stringByAppendingPathComponent:#"MyRecordings"];
NSString *soundFilePath = [documentPath stringByAppendingPathComponent:fileToPlay];
//Then convert paths to URL
NSURL* originURL = [NSURL fileURLWithPath:soundFilePath];
NSURL* destinationURL = [NSURL fileURLWithPath:soundFilePath1];
//Then, you have to copy the file
[[NSFileManager defaultManager] copyItemAtURL:destinationURL toURL:originURL error:NULL];
}
That should do it, tell me if there is any error.

Just create an instance of NSData with your original file. Than write it to the other location.
//write file to the other location
NSData *myData = [[NSData alloc] initWithContentsOfFile:originalPath];
[myData writeToFile:newDataPath options:NSDataWritingAtomic error:&error];
//delete file from original location
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager removeItemAtPath:originalPath error:&removeError];

Related

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..

How can i store streaming video in resource folder in iOS?

If i go to the point then my problem is, i want to make a web view where it will load a video and when stream starts then i want to download/store that video data in the resource folder of the application.How can i do that?
Please somebody help me by any kinds of help.
BR
Emon
In the run time you can't save a video to resource folder but you can save files in to
NSDocuments and retrive them using NSFileManagers.Go through this link
http://www.techotopia.com/index.php/Working_with_Files_on_the_iPhone
Try with this Code to save a file
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/filename.MP4",documentsDirectory];
NSData* videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your Url"]];
[[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
[filemanager createFileAtPath:filePath contents:videoData attributes:nil];
To retrive:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/filename.MP4",documentsDirectory];
BOOL exists = [fm fileExistsAtPath:newDirectory isDirectory:&isDir];
if (exists) {
//Play Video with contents of file path.
}

How can I overwrite the contents of a plist file? (iPhone / iPad)

I have a plist file in my main app bundle that I want to update via my app. Here is the code I'm using, the problem is that the plist doesn't seem to be getting updated. Is my code incorrect or is there another issue?
// Data
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:self.someValue forKey:#"Root"];
// Save the logs
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"plist"];
[data writeToFile:filepath atomically:YES];
Please can someone help me out?
IOS restricts writing to bundled files. If you want a writable plist, you need to copy it to your app's Documents folder and write to it there.
Here's how I'm doing it in one of my apps
//get file paths
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"document.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"bundle.plist"];
//if file exists in the documents directory, get it
if([fileManager fileExistsAtPath:documentPlistPath]){
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
//if file does not exist, create it from existing plist
else {
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success) {
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
return nil;
}
Hope this helps

What am I doing wrong? NSFileManager woes

I'm currently building quite a large iPhone application. Bigger than I expected anyway. But that is beside the point, the overall idea of the application is to grab JSON from a web service, sort it all into custom NSObject's that are linked together and then present.
This goes all well and good. But, because I want the user to be able to see this information on the device without an internet connection, I need to save the information that I am presenting into the Documents folder that each Application has.
I basically implemented the NSCoding protocol into all the custom NSObject's that would need it in order to save it into a subdirectory of the Documents directory.
This is all achieved through this function here.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Data"];
NSString *dataFileString = [dataPath stringByAppendingPathComponent:#"Company.archive"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataFileString]) //Does directory already exist?
{
MACompany *company = [MACompany sharedMACompany];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Data"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
NSString *dataFileString = [dataPath stringByAppendingPathComponent:#"Company.archive"];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:company forKey:#"MACompany"];
[archiver finishEncoding];
[[NSFileManager defaultManager] createFileAtPath:dataFileString
contents:data
attributes:nil];
[archiver release];
[data release];
} else {
NSLog(#"File already exists, no need to recreate, not yet anyway");
}
}
I do the following request when the user first loads the application (application didFinishLaunchingWithOptions:) and when the user opens the application after being in the background (applicationWillEnterForeground:).
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Data"];
NSString *dataFileString = [dataPath stringByAppendingPathComponent:#"Company.archive"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataFileString]) //Does directory already exist?
{
NSLog(#"Create a new Company Request");
MAWebRequests *companyReq = [[MAWebRequests alloc] init];
[companyReq getCompanyDetails];
[companyReq release];
} else {
NSLog(#"Saved Company Needs to be Decoded applicationWillEnterForeground");
MACompany *company = [MACompany sharedMACompany];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Data"];
NSString *dataFileString = [dataPath stringByAppendingPathComponent:#"Company.archive"];
NSData *data = [[NSData alloc] initWithContentsOfFile:dataFileString];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[data release];
company = [unarchiver decodeObjectForKey:#"MACompany"];
[unarchiver finishDecoding];
[unarchiver release];
}
Now this works all well and good and I can pull from this file also. But, I can only grab the data stored in this file when I have Xcode's debugger attached to the application. As soon as is stopped, the data is corrupted and doesn't include the original data.
The data is still stored there, I can see the created file, but the actual data itself that is stored within the file is wrong...
Should I not be using the above logic to save the data to the file and then pull recreate the shared object?
Has anyone else tried to do such a thing and had success?
Is there any reason as to why I'm running into this weird issue?
Has anyone else had this issue?
Any help would be greatly appreciated, have been trying all sorts of different methods to get it to work and nothing has been able to get there. All I need to be able to do is be able to store the data there permanently until I need to update it...
I have resolved this issue by saving the MACompany object well before applicationDidEnterBackground:
Major thanks to #OleBegemann for his aid in finding where the issue nested.

iphone, write csv file in sandbox

i must write (at start of app) and delete is content (at the end of app) a csv in my sandbox file with a stream of data.
For your experience, what's the best way to do this?
edit:
i'm trying with this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename =#"test.csv";
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
[[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
}
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
NSString *data = [NSString stringWithFormat:#"%#,%#\n", latitudine.text, longitudine.text];
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
it work but.... every time writedata is call i got only one row, no append. i want to collect all values of my two textlabel.
Where my mistake?
edit2:
yessss, find the solution with this code:
first i've create this one:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"myfile.csv"];
}
and in my viewDidLoad i check and if does not exist, create my file
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
and in one of my method i add the code for retrieve data and append to my file:
NSString *data = [NSString stringWithFormat:#"%#,%# ", latitudine.text, longitudine.text];
//create my data to append
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
//write data to with the right encoding
Hope this helps!
If you put it in NSTemporaryDirectory(), I think it's supposed to be cleaned up on app exit — it's probably worth checking if this is the case.