Create a file to an application document folder - ios

I want to create a file in my application document folder and i have to store some content. That content takes from my localhost file. So i write a below code. But this code didn't create a file in my application document folder.
- (void) createFile
{
NSString *strPath = [NSString stringWithFormat:#"http://192.168.5.117/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"File Exists");
}
else
{
NSLog(#"File not exists");
}
NSString *content = [NSString stringWithFormat:#"%#",data];
[content writeToFile:strLastpath atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
}
While build for running i got this.
2013-10-11 11:36:38.833 SampleFileCreation[1321:c07] Path : http://192.168.5.117/~mac/banana.obj
File Name : Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] Database Path : /Users/mac/Library/Application Support/iPhone Simulator/6.1/Applications/4FA749DF-D12D-4956-AF76-140D2F981F17/Documents/Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] File not exists

You can also try this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileName = #"yourFileName";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/fileName"];
NSDate *data = [NSData dataWithContentsOfURL:YourUrl]; // get date form url
[data writeToFile:dataPath atomically:YES]; // save data in file

I found the answer. File created successfully.
- (void) createFile {
NSString *strPath = [NSString stringWithFormat:#"http://-.-.-.-/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
docsDir=[docsDir stringByAppendingString:#"/Object File"];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSError *theError = nil;
NSFileManager *filemgr = [NSFileManager defaultManager];
**//I added this line**
[filemgr createDirectoryAtPath:docsDir
withIntermediateDirectories:YES
attributes:nil
error:&theError];
**//Changed this line**
[data writeToFile:[docsDir stringByAppendingPathComponent:strLastpath]
options:NSDataWritingAtomic
error:&theError];
if ([filemgr fileExistsAtPath:[docsDir stringByAppendingPathComponent:strLastpath]]){
NSLog(#"File Exists");
} else {
NSLog(#"File not exists");
NSLog(#"Tell Me error %#",[theError localizedDescription]);
}
}

Related

How can I backup and restore .zip file on iCloud Drive?

I want to store .zip files on iCloud. Anybody help me how to upload and restore? I have read the Apple guideline for iCloud backup and now I have created one folder with some files and two folders with multiple images and then generate zip file of that folder.
First Save your File and Folder on Local Storage.
Then Create this File & Folder's Zip File.
And Last Upload Your zip file on iCloud.
For get this file doing reverse process.
- (void)viewDidLoad {
[super viewDidLoad];
[self CreatFileAndFolder];
}
Create Folder on local and save file in this folder that you want upload on iCloud Drive.
-(void)CreatFileAndFolder{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/meetInChat"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *stringToWrite = #"1\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n41\n2\n3\n4";
NSString *exportPath = [dataPath stringByAppendingString:#"/mytext.txt"];
[stringToWrite writeToFile:exportPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
Create Action that First Create Zip file your Folder and then Upload your Zip file on iCloud Drive.
-(IBAction) iCloudSyncing:(id)sender
{
[self zipFolder];
//--------------------------Zip Folder Upload on iCloud-----------------------------//
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"meetInChat.zip"];
NSLog(#"FilePath=>%#",zipFilePath);
NSURL *u = [[NSURL alloc] initFileURLWithPath:zipFilePath];
NSData *data = [[NSData alloc] initWithContentsOfURL:u];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"]URLByAppendingPathComponent:#"meetInChat.zip"];
Mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
Mydoc.zipDataContent = data;
[Mydoc saveToURL:[Mydoc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"PictureZip: Synced with icloud");
[[NSUbiquitousKeyValueStore defaultStore]setData:data forKey:#"meetInChat"];
}
else
NSLog(#"PictureZip: Syncing FAILED with icloud");
}];
}
Create Zip file from your folder
-(BOOL)zipFolder
{
//--------------------------Create Zip Folder -----------------------------//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir=NO;
NSArray *subpaths = nil;
NSString *exportPath = [docDirectory stringByAppendingString:#"/meetInChat"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:exportPath];
}
NSString *meetInChatPath = [docDirectory stringByAppendingString:[NSString stringWithFormat:#"/%#.zip",#"meetInChat"]];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:meetInChatPath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [exportPath stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[archiver addFileToZip:fullPath newname:path];
}
}
} else {
[archiver addFileToZip:exportPath newname:#"meetInChat"];
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
return YES;
else
return NO;
}
Here Get ZipFile back From iCloud Drive then Doing reverse process Unzip your file and get data back.
- (IBAction)GetData:(id)sender {
//--------------------------Get data back from iCloud -----------------------------//
id token = [[NSFileManager defaultManager] ubiquityIdentityToken];
if (token == nil)
{
NSLog(#"ICloud Is not LogIn");
}
else
{
NSLog(#"ICloud Is LogIn");
NSData *dataFile = [[NSUbiquitousKeyValueStore defaultStore]dataForKey:#"meetInChat"];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = [NSString stringWithFormat:#"meetInChat.zip"];
NSString* fileAtPath = [documentsDirectory stringByAppendingPathComponent:fileName];
[dataFile writeToFile:fileAtPath atomically:NO];
}
}

Saving many pdf locally on device and retrieving it on click

NSURL *url = [NSURL URLWithString:#"PDFLINK"];
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:url];
NSString * name = #"First";
// Store the Data locally as PDF File
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *newFilePath = [documentsDirectory stringByAppendingPathComponent:#"my.pdf"];
NSError *error;
if ([fileManager createFileAtPath:newFilePath contents:pdfData attributes:nil])
{
NSLog(#"Create Sucess");
[self loadPDF];
}
else
{
NSLog(#"Create error: %#", error);
}
}
-(void)loadPDF
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSArray *resultArray = [fileManager subpathsOfDirectoryAtPath:documentsDirectory error:nil];
if (![resultArray containsObject:arrObj])
{
// do something
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[resultArray objectAtIndex:0]];
// Now create Request for the file that was saved in your documents folder
//NSLog(#"The filePath %#",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSLog(#"The url %#",url);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
}
Here is my code.I have more 10 pdf and want to store them locally on device and display next time without download.
It saves the pdf again and i cannot check whether it is downloaded or not ?
Please help me
I am not sure what you mean but, to download a file , you need to use NSData:
NSString *stringURL = #"your file URL";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.extension"];
[urlData writeToFile:filePath atomically:YES];
}
Now the downloaded file exists at filePath and you can get it by using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"filename with extension"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
you can try this to check if file exists at file path:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:#"filename"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
if(fileExists){
//dont download, just grab it and display it
}
else{
//download and display it
}

need to access directory list in ios

I need to create a folder and files in this path
/var/mobile/Containers/Data/
but when I look for it can't find the folder
my code >>
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = #"/var/mobile/Containers";//[paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyNewFolder/myDB.db"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
I dint really understood your problem . Hope this helps :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(#"Saving");
NSUserDefaults *prefs = [[NSUserDefaults alloc] init];
NSString *path1 = [NSString stringWithFormat:#"/var/mobile/Containers"];
NSString *dataPath = [path stringByAppendingPathComponent:path1];
dataPath = [dataPath stringByStandardizingPath];
filePath = [dataPath stringByAppendingPathComponent:#"MyNewFolder/myDB.db"];
Here's the iOS 8 approach Apple recommends to retrieve the location of the Documents directory:
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Create Folder
//-- to select path from image--//
AppDelegate *del = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSString *dataPath=[del.databasePath copy];
NSString *Documentpath=[del.path_Folder_Document copy];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
dataPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images"];
Pathforimage=dataPath;
Add Folder if not Exist
if (![[NSFileManager defaultManager] createDirectoryAtPath:Pathforimage withIntermediateDirectories:NO attributes:nil error:nil])
{
//NSLog(#"directory... /Images already exist..");
}
else
{
//NSLog(#"directory created!");
}
NSString *pathforAudios=[NSString stringWithFormat:#"%#/Images_Audio",Documentpath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:pathforAudios withIntermediateDirectories:NO attributes:nil error:nil])
{
//NSLog(#"directory... /Images already exist..");
}
else
{
//NSLog(#"directory created!");
}
//-- end of path --//
Save Image to Folder
//Save Image to Documents Directory
NSString *imagePath = [Pathforimage stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",Img_File_Name]];
[UIImageJPEGRepresentation(image, 0.1) writeToFile:imagePath atomically:YES];
imagePath=nil;
image=nil;
Delete Files/Folder
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files =%#",files);
NSString *Images_Folder = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images"];
NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:Images_Folder error:nil];
for (NSString *filename in fileArray)
{
NSLog(#"Images =%#",filename);
[fileMgr removeItemAtPath:[Images_Folder stringByAppendingPathComponent:filename] error:NULL];
}
NSString *Images_Audio_Folder = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images_Audio"];
NSArray *fileArray1 = [fileMgr contentsOfDirectoryAtPath:Images_Audio_Folder error:nil];
for (NSString *filename in fileArray1)
{
NSLog(#"Images_Audio =%#",filename);
[fileMgr removeItemAtPath:[Images_Audio_Folder stringByAppendingPathComponent:filename] error:NULL];
}
Create floder
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyNewFolder"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dataPath]){
[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
}else{
NSLog(#"exist");
}
NSLog(#"dataPath:%#",dataPath);

Error reading csv file on iOS device

I created an app to save as an csv file, app works fine in iOS simulator with both write and read. When i load the app to iOS device it doesn't data.
- (IBAction)saveInfo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:#"%#,%#,%#\n",
self.food.text,
self.movies.text,
self.channel.text];
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
//resultView.text = docPath;
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
resultView.text = filename;
if (![[NSFileManager defaultManager] fileExistsAtPath:filename])
{
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filename];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
self.food.text = nil;
self.movies.text = nil;
self.channel.text =nil;
NSLog(#"Info saved");
}
- (IBAction)viewInfo:(id)sender {
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendingString:#"result.csv"];
NSString *fileContent=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
resultView.text = fileContent;
}
You are building the path incorrectly. Use:
NSArray *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSString *filename = [docPath stringByAppendinPathComponent:#"result.csv"];
The code you have results in a path like <path to app bundle>/Documentsresult.csv and on the device you can't write to the app bundle.
On Button action u can write below code maybe File will be displayed in my point of view its running correctly you should tray.....
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFile = [docsDir
stringByAppendingPathComponent: #"datafile.csv"];
NSLog(#"%#",dataFile);
NSData *data = [filemgr contentsAtPath:dataFile];
NSString *fooString=#"----------------\n Full File Data \n ---------------- \n " ;
fooString = [fooString stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ];
self.FileTextView.text=fooString;

How to create folder in NSLibraryDirectory in mac

Im trying to create an folder in user library directory,but its not creating. Is there any mistake in the below code.
databaseName = #"KITSMAW0051_DB.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
databasePath = [[documentsDir stringByAppendingPathComponent:folder ] stringByAppendingPathComponent:databaseName];
Ok first of all databasePath describes a path to a file not a directory. But let's say you actually want to create "Swasstik" folder inside user's Library:
// Your code
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = #"Swasstik";
// I edited here to keep only the folder
NSString *folderPath = [documentsDir stringByAppendingPathComponent:folder];
// At this point we got the path to the folder
// but we want to actually go on and create it
// NSFileManager to the rescue!
NSFileManager *manager = [NSFileManager defaultManager];
[manager createDirectoryAtPath: folderPath
withIntermediateDirectories: NO
attributes: nil
error: nil];
Of course you can study and set the manager as you like and also implement some error handling. I hope that this makes sense...
databaseName = #"KITSMAW0051_DB.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *folder = [documentsDir stringByAppendingPathComponent:#"Swasstik"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]) {
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error != nil) {
NSLog(#"Some error: %#", error);
return;
}
NSString *databasePath = [folder stringByAppendingPathComponent:databaseName];

Resources