Data storing issue into plist file - ios

Once plist is created data storing start automatically, but after some time it automatically stop storing data in plist. But once when i kill app and restart again, it will start again as previously mention and cycle goes on...
Here is my code
- (void)saveLocationsToPlist:(NSMutableDictionary*)mdictPlist {
NSString *plistName = [NSString stringWithFormat:#"LocationArray.plist"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docDir, plistName];
NSMutableDictionary *savedProfile = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
NSLog(#"ADD LOCATION TIME : %#",[NSDate date]);
NSLog(#"ADD LOCATION DATA : %#",mdictPlist);
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
BFLog(#"applicationDocumentsDir Not exists");
fullPath = [docDir stringByAppendingPathComponent: [NSString stringWithFormat:#"LocationArray.plist"] ];
}
if (!savedProfile) {
savedProfile = [[NSMutableDictionary alloc] init];
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
} else {
self.myLocationArrayInPlist = [savedProfile objectForKey:#"LocationArray"];
}
if(mdictPlist) {
if(self.myLocationArrayInPlist == nil){
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
}
[_myLocationArrayInPlist addObject:mdictPlist];
[savedProfile setObject:_myLocationArrayInPlist forKey:#"LocationArray"];
}
if (![savedProfile writeToFile:fullPath atomically:FALSE]) {
BFLog(#"Couldn't save LocationArray.plist savedProfile :- %# \n Location Data :- %# \n fullPath:-%#",savedProfile,mdictPlist,fullPath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:#""];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
NSLog(#"%#",[NSString stringWithFormat:#"%#/%#", directory, file]);
if([file isEqualToString:#"LocationArray.plist"]){
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", directory, file] error:&error];
if (!success || error) {
// it failed.
BFLog(#"Delete error : %#",error);
}
else {
[self saveLocationsToPlist:myLocationDictInPlist];
}
}
}
}
}
Any idea about this issue.

Related

NSString to PDF file - iOS

I'm receiving a String from a web service and I would like to store it as a pdf file.
I know the have asked before but the answer is always the same. I've tryed it and didn't worked, and it's not explained enough.
So, this is what I'm doing:
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [#"documents/" stringByAppendingPathComponent:formattedName];
NSError *error = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error]) {
}
It's not entering in the if, and I think the file is not being generated.
I'm working with objective-c, xcode 9.
What should I modify?
Create it
NSError*error=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/Application Support"];
NSString*filePathC = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"historyImages"]];
if(![[NSFileManager defaultManager]fileExistsAtPath:filePathC])
{
if(
[[NSFileManager defaultManager] createDirectoryAtPath:filePathC
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"created");
}
else
{
NSLog(#"not created");
}
}
else
{
NSLog(#"exists");
}
///
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [filePathC stringByAppendingPathComponent:formattedName];
NSError *error2 = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error2]) {
}

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];
}
}

objective-c cannot read from property list

self.toDoItems = [[NSMutableArray alloc] init]; //initialize array
self.dataFileName = #"PropertyList";
self.filePath = [self.dataFileName stringByAppendingString:#".plist"];
self.rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
self.filePath = [self.rootPath stringByAppendingPathComponent:self.filePath];
self.NSSRootNodeName = #"ToDoList"; //name of the root node in the property list
// if (![[NSFileManager defaultManager] fileExistsAtPath: self.filePath]) {
// self.filePath = [[NSBundle mainBundle] pathForResource:self.dataFileName ofType:#"plist"];
// }
NSLog(#"File path: %#", self.filePath);
// Uncomment the following line to preserve selection between presentations.
self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
//read xml file and load to array
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:self.filePath];
if (plistXML==nil) {
NSLog(#"Error reading plistXML");
}
NSDictionary *rootDictionary = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!rootDictionary) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
the output is below. I am not sure why I get these errors below:
My PropertyList.plist is sitting in my Documents folder inside my application.
could someone point out what I am doing wrong.
File path: /Users/Computer/Library/Application Support/iPhone Simulator/7.1/Applications/78B5F9BA-8376-4001-ACA0-936D9B4D6342/Documents/PropertyList.plist
Error reading plistXML
Error reading plist: stream had too few bytes, format: 0
FWIW, here is what worked for me:
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath: [self filePathForState]])
{
printf("found state file\n");
NSData *data = [NSData dataWithContentsOfFile:[self filePathForState]];
...
}
else
{
printf("no state file found\n");
}
[fileManager release];
- (NSString *) filePathForState
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *result = [documentsDirectory stringByAppendingPathComponent: #"circles06"];
printf("filePathForState: %s\n", [result UTF8String]);
return result;
}
- (void) saveState
{
NSData *state = [model stateData];
[state writeToFile: [self filePathForState] atomically: NO];
}

Create a file to an application document folder

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]);
}
}

Adding Array to PLIST

I am trying to add and array to a Root array in my plist:
And is not working. Here's my code:
-(IBAction)addName:(id)sender{
NSArray *arrayValues = [NSArray arrayWithObjects: nameLabel.text, nameDate.text, nameValue.text, nil];
NSString *plistpath = [[NSBundle mainBundle] pathForResource:#"Names" ofType:#"plist"];
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistpath];
[namesNew addObject:arrayValues];
[namesNew writeToFile:plistpath atomically:YES];
}
What am I doing wrong? Thanks!
You need to move the file to NSDocumentDirectory. Then edit the plist file.
For example:
Moving to NSDocumentDirectory:
-(NSDictionary *)copyBundleToDocuments
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"Names.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;
}
}
Then get the plist:
-(void)plistArray:(NSArray*)array
{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//getting the plist file name:
NSString *plistName = [NSString stringWithFormat:#"%#/Names.plist",
documentsDirectory];
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistName];
[namesNew addObject:arrayValues];
[namesNew writeToFile:plistName atomically:YES];
return nil;
}
The plist should be a dictionary as the base object instead of an array.
NSMutableDictionary *namesNew = [NSMutableDictionary dictionaryWithContentsOfFile:plistpath];
[namesNew setObject: arrayValues forKey: #"Root"];
[namesNew writeToFile:plistpath atomically:YES];
You cant write your plist to the bundle you need to use NSDocumentDirectory or NSCachesDirectory
Just copy your plist to bundle the overwrite it.
Note: learn the difference between NSCachesDirectory and NSDocumentDirectory
https://developer.apple.com/icloud/documentation/data-storage/
Copy your plist from bundle to documents(in below code caches), you need to this only one time if your plist in your bundle, I prefer using this code in appdelegate.m when - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Names.plist"];
NSString *plistInDocuments=#"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:dataPath
error:&error];
}
NSLog(#"Error description-%# \n", [error localizedDescription]);
NSLog(#"Error reason-%#", [error localizedFailureReason]);
Get your file and overwrite it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistInDocuments=#"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
//add object here
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:dataPath];
[namesNew addObject:arrayValues];
NSError *error = nil;
if ([myFile writeToFile:dataPath options:NSDataWritingAtomic error:&error]) {
// file saved
} else {
// error writing file
NSLog(#"Unable to write plist to %#. Error: %#", dataPath, error);
}

Resources