Copy contents of app to desktop programmatically - objective-c

How can I copy my entire .app bundle ([[NSBundle mainBundle] bundleURL]) to my desktop programmatically?
Here is my code but not helping me.
NSString *sourcepath = [[NSBundle mainBundle] bundlePath];
NSString *destpath = [NSHomeDirectory() stringByAppendingPathComponent:#"Desktop"];
[[NSFileManager defaultManager] copyItemAtPath:sourcepath toPath:destpath error:nil];

You can use the standard NSFileManager methods
copyItemAtURL:toURL:error: or
copyItemAtPath:toPath:error:
to copy directories as well as files. From Apple's docs:
When copying items, the current process must have permission to read the file or directory at srcPath and write the parent directory of dstPath. If the item at srcPath is a directory, this method copies the directory and all of its contents, including any hidden files.
Mind that you have to manually remove an item (file/directory) at the destination with the same name if it already exists or else the copy will fail (again, as per Apple's docs).

Here's how I solved it may be this can be helpful for someone.
- (IBAction)createShortcut:(id)sender {
NSString *sourcepath = [[NSBundle mainBundle] bundlePath];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *theDesktopPath = [paths objectAtIndex:0];
NSString *saveFilePath = [theDesktopPath stringByAppendingPathComponent:#"myApp.app"];
[[NSFileManager defaultManager] copyItemAtPath:sourcepath toPath:saveFilePath error:nil];
}

Related

How to get file from destination path

I dont know about how to open NSFileManager.
How to open NSFileManager in iPhone and upload document from NSFileManager please suggest any easy way.
How can open it and upload the document and also get the path for saved file.
Where I can find file physically.(Any location).
::EDIT::
I started coding in that year. so, i don't know about basic of NSFileManager.
Show contents:
NSLog(#"Documents directory: %#", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
Get all files
//get an instance of the File Manager
NSFileManager *fileManager = [NSFileManager defaultManager];
//we'll list file in the temporary directory
NSString * strPath = NSTemporaryDirectory();
//we'll need NSURL for the File Manager
NSURL *tempDirURL = [NSURL fileURLWithPath:strPath];
//An array of NSURL object representing the path to the file
//using the flag NSDirectoryEnumerationSkipsHiddenFiles to skip hidden files
NSArray *directoryList = [fileManager contentsOfDirectoryAtURL:tempDirURL
includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
Reference:http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files
http://nshipster.com/nsfilemanager/
An iPhone's documents directory is used for saving data. We can save some personal data like as file, image, video etc. The document's directory's data will remain in the iPhone's memory until the application is forcibly terminated.
Let's see an example of how to store some images & retrieve those images later in an iPhone.
// For saving the images in the Document's Directory
-(void)saveImagesInIPhone:(NSData*)imageData withName:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectoryPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NOattributes:nil error:nil];
//Add the FileName to FilePath
NSString *filePath = [folderPath stringByAppendingPathComponent:[iconName stringByAppendingFormat:#"%#",#".png"]];
//Write the file to documents directory
[imageData writeToFile:filePath atomically:YES];
}
Result:- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
///To retrieve the images from the document Directory
-(UIImage*)retrieveImageFromPhone:(NSString*)fileNamewhichtoretrieve
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Get the docs directory
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"IconImages"]; // subDirectory
NSString *filePath = [folderPath stringByAppendingPathComponent:
[fileNamewhichtoretrieve stringByAppendingFormat:
#"%#",#".png"]];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
return [[UIImage alloc] initWithContentsOfFile:filePath];
else
return nil;
}
result :- /var/mobile/Applications/20F869FD-5C61-4900-8CFE-830907731EC9/Documents/Designer0.png
You can get Directory Path like this..
-(NSString *)getDBPath
{
//Searching a standard documents using NSSearchPathForDirectoriesInDomains
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSLog(#"I am in --> getDBPath==%#",paths);
return [documentDir stringByAppendingPathComponent:#"abcd_DB.sqlite"];
}
**If you are using iOS Devices-
You can get Your DB directly by using https://macroplant.com/iexplorer Application.
**If you are using Simulator.
Get the Path directory
In terminal : open directory Path(Past your Directory Path).
Copy your DB and brows it with Firefox or sqlite browser.

Objective-c load and write plist - error

Hi I'm practicing with plists and I learned that there are 2 different ways to load them
FIRST METHOD:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [path lastObject];
NSString *filePath = [documents stringByAppendingPathComponent:#"test.plist"];
self.array = [NSArray arrayWithContentsOfFile:filePath];
SECOND METHOD:
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"Ingredients" ofType:#"plist"];
self.array = [NSArray arrayWithContentsOfFile:filePath];
I don't understand clearly which way it's best... but I noticed that if I use the second one, I can't write in the plist. can anyone tell me more about it? which is the best and correct way? What's the difference?
i'm doing some tests and i have some code working only with one method...
//using this code the nslog will print null
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"Ingredients.plist"];
ingredients = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"ingredients:%#", self.ingredients);
//using this code the nslog will print the content of the array
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"Ingredients" ofType:#"plist"];
ingredients = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"Authors:%#", self.ingredients);
First Method
Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.
Reference iOS Application Programming Guide.
To access the Documents directory of your applications sandbox, you can use the following:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
This Documents directory allows you to store files and subdirectories your app creates or may need.
To access files in the Library directory of your apps sandbox use (in place of pathsabove):
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
Second Method
The Second Method is used to write the file in the Apps main bundle.
The main bundle is the bundle that contains the code and resources for the running application. If you are an application developer, this is the most commonly used bundle. The main bundle is also the easiest to retrieve because it does not require you to provide any information.
It is better to copy the file from App Main Bundle to App Document Directory and then use the document directories path to read/write file.
If you are using the first method you need to copy the file from your main resources to the Documents Directory.
Code to Copy file from app bundle to App's Document Directory
#define FILE_NAME #"sample.plist"
// Function to create a writable copy of the bundled file in the application Documents directory.
- (void)createCopyOfFileIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
success = [fileManager fileExistsAtPath:filePath];
if (success){
return;
}
// The writable file does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:FILE_NAME];
success = [fileManager copyItemAtPath:defaultDBPath toPath:filePath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable file with message '%#'.", [error localizedDescription]);
}
}
Sample Code Dropbox Link

how to copy a file on the network in cocoa

I would like to copy the selected file from my computer to another computer on the same network. I tried to use NSFileManager but I was not successful. Could please help how to do it?
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Documents/test"]];
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:#"Shared/Test"]];
[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
[fileManager release];
2 suggestions:
1) as per the documentation, in this line the error should be "nil" not "NULL"
[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
2) Maybe the code is not finding the files. I notice you do not have any file extension on the paths (maybe "test" should be "test.txt"?). Most files have an extension even if you can't see the extension in the Finder. Get Info on the file to check its extension and fix the code if that's the case.

How to extract immages from a folder in the mainBundle to an array?

In my app bundle, I have several images of several items.
ItemA_largepicture.png
ItemA_smallPicture.png
ItemA_overViewPicture.png
ItemB_largepicture.png
ItemB_smallPicture.png
ItemB_overViewPicture.png
ItemC_largepicture.png
ItemC_smallPicture.png
ItemC_overViewPicture.png
...
I want to extract, for example all ItemB pictures into an array. I can do as Prince suggested
NSString *bundleRootPath = [[NSBundle mainBundle] bundlePath];
NSArray *bundleRootContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRootPath error:nil];
NSArray *files = [bundleRootContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self beginswith 'ItemB'"]];
NSLog(#"%#",files);
This worked very well. The next problem is that all ItemB files is in a folder named ItemB. Somehow I need to add a path within the bundle to the ItemB folder. I thought
NSString *bundleRootPath = [[NSBundle bundleWithPath:#"ItemB"] bundlePath];
was logical, but this didn't work.
Can anyone please explain how this works, and how to access the folder?
NSString *bundleRootPath = [[NSBundle mainBundle] bundlePath];
NSString *itemBPath = [bundleRootPath stringByAppendingPathComponent:#"ItemB"];
NSArray *itemBContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:itemBPath error:nil];

ObjC download file and save it to directory

Id like to "update" a local file from a server (save it to a directory).
I tried EVERYTHING! NOTHING WORKS! That's my last attempt:
NSURL *url = [NSURL URLWithString:#"http://www.doothie.com/QAFrameworks/QAUpdater.php"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"general.qa"];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
[str writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
Not sure if that's what you're trying to do, but you shouldn't try to download and replace a file that's in your Application bundle. Instead, download the file into the user's ~/Library/Application Support/<yourApplicationName>/<yourFiles>. Before using the file within your application bundle, check to see if the one with more current data is in the Application Support. If you application is installed for all users (within /Applications/), non-admin users wouldn't have the authority to change files within the app bundle. (And one should never assume every user runs with admin rights.)
Perhaps that's what's happening.
Additionally, you're loading everything into NSString. Does the file actually contain text?! If not, you might want to use NSData instead :
[[NSData dataWithContentsOfURL:url] writeToFile:filePath atomically:TRUE];