Sharing multiple files on App Via iTunes File Sharing (Code shows 1 file) - iphone

I'm trying to file share multiple files with iTunes file share.
Here is the current code.
Delegate.h
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// file sharing trying
{
NSString *fileName = #"Test.mp3";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:fileName];
if (![fileManager fileExistsAtPath:documentDBFolderPath])
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
}
}
[self.window makeKeyAndVisible];
return YES;
}
At the moment only 1 file gets shared.
Thanks

I assume you want to add a bunch of files in an NSArray? then loop through it like this:
NSArray *names = [NSArray arrayWithObjects: #"foo", #"bar", nil];
for (NSString *fileName in names)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:fileName];
if (![fileManager fileExistsAtPath:documentDBFolderPath])
{
NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
}
}

Related

Name of folder in my directory path in iPhone

I am new to iPhone,
I want to check how many folders are there in my Document Directory and i want fetch name of all folders and i want to store it in my array.
I want only name of folders and not contents inside folder.
Any help will be appreciated.
NSFileManager *mgr = [NSFileManager defaultManager];
NSString *documentsDir [NSSearchPathsForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *allFilesInDocuments = [mgr contentsOfDirectoryAtPath:documentsDir error:NULL];
NSMutableArray *found = [NSMutableArray array];
for (NSString *filename in allFilesInDocuments)
{
NSString *fullPath = [documentsDir stringByAppendingPathComponent:filename];
BOOL isDir;
[mgr fileExistsAtPath:fullPath isDirectory:&isDir];
if (isDir) [found addObject:fullPath]; // or filename
}
now found should contain all the paths/names of the subdirectories of the Documents directory (i. e. entries in the Documents directory which are directories themselves.)
#define rootFileName XXXXXXXX
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *yourDirectory = [documentsDirectory stringByAppendingPathComponent:rootFileName];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDirectory error:nil];
for(int i = 0; i < [fileList count]; i++)
{
NSString *fileName = [fileList objectAtIndex:i];
NSLog(#"yourFileName:%#",fileName);
if([fileName isEqualToString:#".DS_Store"])
{
NSString *dotDS_StorePath = [NSString stringWithFormat:#"%#/.DS_Store",yourDirectory];
[[NSFileManager defaultManager] removeItemAtPath:dotDS_StorePath error:nil];
}
}
there is one thing you should know , the fileLists has a more file is .DS_Store , the file is created by the os.
DO this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [[fileManager directoryContentsAtPath:yourDocumentPath] retain]; // your path here instead (DOCUMENTS_FOLDER)
NSMutableArray *directoryList = [[NSMutableArray alloc] init];
for(NSString *file in fileList) {
NSString *path = [yourDocumentPath stringByAppendingPathComponent:file]; // create path for directory and check it exits or not as directory
BOOL isDir = NO;
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir) {
[directoryList addObject:file];
}
}
NSLog(#"%#", directoryList);
take a look at the NSFileManager class
it sounds like you want the subpathsAtPath: method
here's the sample code
BOOL isDir=NO;
NSArray *subpaths;
NSString *fontPath = #"/System/Library/Fonts";
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)
subpaths = [fileManager subpathsAtPath:fontPath];
[fileManager release];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
Simplest method:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (int i = 0; i < [imageFilenames count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[imageFilenames objectAtIndex:i] ];
if (![[imageFilenames objectAtIndex:i]isEqualToString:#".DS_Store"])
{
NSLog(#"\n %#",imageName);
}
}

Where does iPhone simulator put data files?

If I compile my iPhone App with a database that has been built into the bundle what path do I have to use to find the file so that I can open it, as in:
FMDatabase* db = [FMDatabase databaseWithPath:#"/???/database.sqlite"];
Inside your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
set the following code:
databaseName=#"yourfileName.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
-(void) checkAndCreateDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
else
printf("NO File found");
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
You can use like this regardless of simulator or device. Please dont forget to add db file to your project folder and add to your bundle.
#define DATABASE #"databasefile.sqlite"
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[documentsDir stringByAppendingPathComponent:DATABASE]];

how do we open an already existing database fmdb and where to include it?

I am using fmdb but i am not knowing where to add the db file.
I found this old answer that i think it doesn't fit for xcode 4.2 (since we dont have 'Resources' folder anymore).
I created a database in 'Lita', added the extension .sqlite and added the db file as follows :
then tried to use the following
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"db.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
FMResultSet *results = [database executeQuery:#"select * from tbl"];
printf("hi");
while([results next]) {
printf("hi2");
NSString *name = [results stringForColumn:#"clm1"];
NSString *text = [results stringForColumn:#"clm2"];
NSLog(#"test: %# - %#",name, text);
}
printf("done");
i am getting the 'hi' 'done' but never 'hi2'...
anyone can help?
You want to add the (compiled) database to the project as a resource, and then copy it into the documents folder of the app on first start-up.
Here is an example method that does the work, call it from the applicationDidFinishLaunching and use the resultant FMDatabase * for all you queries.
- (FMDatabase *)openDatabase
{
NSFileManager *fm = [NSFileManager defaultManager];
NSString *documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *db_path = [documents_dir stringByAppendingPathComponent:[NSString stringWithFormat:#"database.s3db"]];
NSString *template_path = [[NSBundle mainBundle] pathForResource:#"template_db" ofType:#"s3db"];
if (![fm fileExistsAtPath:db_path])
[fm copyItemAtPath:template_path toPath:db_path error:nil];
FMDatabase *db = [FMDatabase databaseWithPath:db_path];
if (![db open])
NSLog(#"Failed to open database!");
return db;
}
I am working with the same issues right now. But to answer your question: the documents folder is the folder that is to be used in the device.
Put the database in the the supporting files folder.
Here is what works for me:
//hide status bar for full screen view
[[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
//set reference to database here
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"RPRA.sqlite"];
[self createAndCheckDatabase];
// Override point for customization after application launch.
return YES;
}
//method used to create database and check if it exists
-(void) createAndCheckDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:self.databasePath];
if(success) return;
//else move database into documents folder
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"RPRA.db"];
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
}
- (void)ensureDBFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"retails.sqlite"]];
NSLog(#"Database Filepath Delgate = %#", dbFilePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL dbFileExists = [fileManager fileExistsAtPath:dbFilePath];
if(!dbFileExists){
//Copy the db file if it didn't exist
NSString *bundledDbPath = [[NSBundle mainBundle] pathForResource:#"retails" ofType:#"sqlite"];
if (bundledDbPath != nil) {
BOOL copiedDbFile = [fileManager copyItemAtPath:bundledDbPath toPath:dbFilePath error:nil];
if (!copiedDbFile) {
NSLog(#"Error: Couldn't copy the db file from the bundle");
}
}
else {
NSLog(#"Error: Couldn't find the db file in the bundle");
}
}
self.db = [FMDatabase databaseWithPath:dbFilePath];
[self.db setShouldCacheStatements:NO];
[self.db open];
if([self.db hadError]) {
NSLog(#"Database Error %d: %#", [self.db lastErrorCode], [self.db lastErrorMessage]);
}
}

Terminating app due to uncaught exception 'NSInvalidArgumentException'

I've finished my own project.
So I tested it on the simulator and everything is ok.
But unfortunately, the project does not run on my real iphone. This error occurs:
"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'"
What is the reason?
Here is some code that I used:
RootViewController *rootViewController;
...
- (void) startApp;
{
[rootViewController init]; // error occured
}
RootViewController is one of Project Simple File.
void Game::readData()
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"GameInfo.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"GameInfo" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
gameMaxLevel = [[savedStock objectForKey:#"GameMaxLevel"] intValue];
[savedStock release];
}
void Game::readData()
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"GameInfo.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"GameInfo" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
gameMaxLevel = [[savedStock objectForKey:#"GameMaxLevel"] intValue];
[savedStock release];
}
check if your GameInfo.plist exist in your application's resource, and it reside inside your application folder(if you are executing your code on two or more devices). If problem doesn't get solved, share your, complete exception log.

Create copy of database in iPhone

Can any one help me for:
How can we create copy of database?
How can we open that database in iPhone?
How can we create folder in our application path?
How can we copy folder with files in our application path?
"For Creating the copy of Database..."
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager fileExistsAtPath:finalPath];
if(success)
{
NSLog(#"Database Already Created.");
return;
}
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.sqlite"];
success = [fileManager copyItemAtPath:defaultPath toPath:finalPath error:&error];
if(success)
{
NSLog(#"Database Created Successfully.");
}
"For Open that Database..."
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSString *finalPath = [documentPath stringByAppendingPathComponent:#"test.sqlite"];
if(sqlite3_open([finalPath UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSLog(#"Error to Open Database :- %s",sqlite3_errmsg(database));
}
"For Creating Folder in Application Path"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
"For Copying The Files And Folder in Application"
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/FolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
BOOL successs;
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Files/FolderName"];
successs = [[NSFileManager defaultManager] fileExistsAtPath:defaultPath];
if(successs)
{
NSLog(#"TRUE");
NSString *strFile = [NSString stringWithFormat:#"%#",dataPath];
NSLog(#"File :- '%#'",strFile);
[fileManager copyItemAtPath:defaultPath toPath:strFile error:&error];
}
else
NSLog(#"FALSE");
}