How to store the data to the iPhone app - objective-c

We developed the iphone app which will be used by employees of the diff. organizations (actually we have not made it enterprise app , instead we are going to put this app on app store for the charge) , So whats we want is whenever the person will install the app, and the app will open first time , one pop up will come over there asking for the enter URL (which will be the URL points to the server of that persons organization) , So going through code logic , what i want is when we will come to the login page in the view did load i want to check whether the URL is already stored in the app or not, if its not stored then i will give that pop up asking for enter URL, and if its stored then simply i will allow him to enter the login details.
My problem is how should i store that URL and where should i store that URL and How should i check whether that is already stored or not. I tried to store that URL with... Where the urlfield.text is the URL i am going to store.
NSError *error;
// For error information
// Create file manager
fileMgr = [NSFileManager defaultManager];
// Point to Document directory
documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents"];
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
// File we want to create in the documents directory
// Result is: /Documents/file1.txt
filePath = [documentsDirectory
stringByAppendingPathComponent:#"file1.txt"];
str=urlField.text;
// Write the file
[str writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:&error];
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
and i am checking whether its there or not using..
// fileExists is a BOOL variable
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
NSLog(#"Boolean value:=%d",fileExists);
if ( fileExists == 0 )
{
.......
........
}
but each time i runs the app it returns the '0' (means the BOOL variable fileExists) .
please some one will tell me the way to accomplish my task, I am end up with trying all the sides with this logic.

i use the NSUserDefaults for this.
first upon for checking that whether the user is opening the app first time i check the value for the first object of NSUserDefault like
//defaults is a object of NSUserDefault
NSString *URLEntered =[defaults objectForKey:#"URLISENTERED"];
if (!URLEntered) {
[defaults setValue:#"0" forKey:#"URLISENTERED"];
}
the URLEntered returns null at first time, so i set the value 0 for Key URLISENTERED
and i allowed users to enter the URL of there organizations server,
within that i set the valu for key URLISENTERED as a 1 , like
[defaults setValue:#"1" forKey:#"URLISENTERED"];
and at the same time i take one more object of NSUserDefault to store the URL of the server and stored that like
// defaultURL is the object of NSUserDefault, and main URL is the URL of server user entered
[defaultURL setValue:mainURL forKey:#"mainURL"];
so next when the user again logins to the app the value of
[defaults objectForKey:#"URLISENTERED"]
is 1 as we set and that time i navigated user to login screen directly , and have fetched the value of mainURL using
mainURL=[defaultURL objectForKey:#"mainURL"];
and used this URL for further use.

As I understand your problem your can use NSUserDefault or plist
Using plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: #"plist.plist"] ];
}
NSMutableDictionary *data;
NSString *userURL ;
if ([fileManager fileExistsAtPath: path])
{
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//To retrieve the data from the plist
NSMutableDictionary *savedURL= [[NSMutableDictionary alloc] initWithContentsOfFile: path];
userURL = [savedURL objectForKey:#"USER_URL"];
NSLog(#"%#",userURL);
// present login detail or more stuff with userURL
}
else
{
userURL = // prompt for user to enter URL
data = [[NSMutableDictionary alloc] init];
[data setObject:[NSNumber numberWithInt:value] forKey:#"USER_URL"];
[data writeToFile: path atomically:YES];
}
Using NSUserDefault:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *userURL = [defaults objectForKey:#"USER_URL"];
if(userURL) {
NSLog(#"%#",userURL);
//present login detail or more stuff with userURL
}
else {
userURL = // prompt for userURL
[defaults setObject:userURL forKey:#"USER_URL"];
}

Actually if you want to check URL on client . you can accomplish this task using sqlite database.

Related

sqlite3 database strangely disappears from NSDocumentDirectory

Problem: After long time running with no issues, my database is giving me a headache, it just wont stay at its place in the NSDocumentDirectory. The Database strangely disappears.
I never clear the documents-folder or delete anything. It only contains the database and saves some images in there which get downloaded if the user wants to keep them.
Has anybody an idea what could be going on?
after 3 days of struggling with this problem I can't come up with a possible solution, so please help me! :(
in my Database-Singleton I have the following init-Method
- (id)initWithName{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:kDatabaseName];
//kDatabaseName = nameOfDatabase.db
[self checkAndCreateDatabase];
return self;
}
and the checkAndCreateDatabase - method:
- (void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
NSURL *urlpath = [NSURL fileURLWithPath:databasePath];
NSError *error = nil;
[urlpath setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(success && sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"database opened");
sqlite3_close(database);
return;
}
else{
sqlite3_close(database);
NSLog(#"Database was created");
}
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
//NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:databaseName ofType:#"sqlite3"];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
if ([self createTables]){ //creates tables of DB, works fine
NSLog(#"Tables were created");
} else {
NSLog(#"Database failed to create and open");
}
}
This code worked for a year straight. and suddenly when i needed to do some updates, the database was not saved anymore.
After a lot of troubleshooting I found out the database is being created in the Documents folder, but when i try to access the exact same path (cause i don't touch the variables) it disappears, with it's tables.
I tried different versions of my repository, all of them seem to have the problem. I really am getting mad. :(
Are you persisting the databasePath between app launches? In iOS 8 the DocumentsDirectory (and all the others, Caches, tmp, etc) became dynamic - - their name changes in between every app launch. So if you're storing the absolute path anywhere in your app it will be invalid the next time the app launches. If this is the case, a good way to fix it is to store the path relative to the DocumentsDirectory and whenever you need it just call
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
and append your path to that.
Help this helps.

Read from file.Plist Returns Null

Program that Creates multiple Plist's Paths for Different information.
But only one path is not working.
(i think "writeToFile" is the problem)
code:
-(NSString *) createPath:(NSString *)withFileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:withFileName];
return path;
}
Path
NSLog = /var/mobile/Applications/02CABC0A-6B5B-4097-A9D1-4336BE8230B7/Documents/MessagesDB.plist
&
-(void) messagesDbFlush
{
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[_messagesDB writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);
}
"ReturnsInfo" Array is Null :/
Anyone please help?
I once had the same error.
1) Check the name of the plist in the directory listing to match your coded one
2) Check Project settings, manually delete the pre-existing plist from the "Build Settings" > "Copy Bundle Resources", and drag drop from the list.
3) Select the plist in directory listing, check Utilities sidebar, check Identity & Type > Location as valid
4) If you deleted the app's "default" plist aka bundle identifier, add copy build phase, choose destination, choose pref folder as absolut path check "copy only when installing"
This solved my returning null.
And if all fails on the bundle identifier, you can always copy the plist to pref folder by code:
NSString *path = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
BOOL PrefsExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
NSString *copyPrefsPath = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (PrefsExist == 0)
{
// Copy the plist to prefs folder (one-time event)
NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:#"com.MyCompany.MyApp" ofType:#"plist"];
[fileManager copyItemAtPath:tessdataPath toPath:path error:&error];
} else
{
// Read/Write the values from plist
}
i have stored following array with 5 objects in it, its working fine on my side, try it
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
for(int i=0;i<5;i++)
[array addObject:#"This is Demo String, You can write your own String here"];
NSString *_fileMessagesDB = #"MessagesDB.plist";
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[array writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);

move/copy a file to iCloud

I am a beginner using Objective-C. I used the following code to move a file to iCloud but it gives an error that The operation could not be completed. The file exists.
//store the file locally in document folder
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [docPaths objectAtIndex:0];
filePath = [filePath stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSString *writeError = nil;
NSData * fileData = [NSPropertyListSerialization dataFromPropertyList:dataDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&writeError];
if ([fileData writeToFile:filePath atomically:YES]) {
NSLog(#"Server file is stored locally");
}else {
NSLog(#"%#", writeError);
}
// store the file in iCloud folder
NSURL *ubiquitousURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSString *tmpubiquitousURL = ubiquitousURL.absoluteString;
tmpubiquitousURL = [tmpubiquitousURL stringByAppendingString:fileName];
NSURL *ubi2 = [[NSURL alloc] initWithString:tmpubiquitousURL];
[[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I used the following to remove the file from iCloud but it gives an error that Cannot disable syncing on an un-synced file.
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I checked the availability of iCloud in my app delegate and it's available. The file is an XML file (.plist) and I have a local copy stored in NSDocumentDirectory.
Overall, I want to sync that file in iCloud so it will be accessible on all devices using my app. I have been struggling with this for 2 days, so if you could help me to resolve the problem I would appreciate it.
Note: I would rather not to use UIDocument, however, if that is the only option please let me know.
I also have the same problem while using the code
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
you have to change the code like below for this to work correctly
[[[NSFileManager alloc]init]setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:nil];
this code is for moving a file to icloud, also you should change the name of the file you are moving. It should not be same.

IOS - load local file in order

I have a list of image in Document folder of app.And I want to load images in order of date created.
How can I do that ?
This code will enumerate all files in your documents directory in the order they were created:
See comments in the code to understand what is going on.
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(#"%#", f);
}
I would take a look: Getting a list of files in a directory with a glob
Specifically the NSFileManager. You can look at attributes of the file. From there you can most likely do a sort using NSPredicate.

Object-c/iOS :About use NSUserDefaults set serial numbers/password

I got many issues about setting sn/pwd
Because the first default data is from URL
got a plist data like this:
{
serial_number=1234;
password = 7777;
}
The application finish launched,It will download from URL via the code like this
NSString *urlString = [[NSString alloc]initWithString:#"http://getdefaults.php"];
NSArray *plistData;
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURLURLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *listFile = [[NSString alloc] initWithData:returnDataencoding:NSUTF8StringEncoding];
[listFile dataUsingEncoding:NSUTF8StringEncoding];
plistData = [listFile propertyList];
At first , I try to create a plist data in iphone:
NSArray *localPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localDocPath = [localPaths objectAtIndex:0];
NSString *localFilePath = [localDocPath stringByAppendingPathComponent:#"InputPassword.plist"];
NSMutableDictionary *localDictread = [[NSMutableDictionary alloc] initWithContentsOfFile:localFilePath];
Than I compare with the information I get
if(localDictread==nil){
//pop a textfield to let user enter the serial numbers and password
//if the text in the textfield is equal the default SN/PWD from plistData,write the sn/pwd to plist in iphone
}
But I found NSUserDefaults , Can it work as the same ?
I mean work as the same is can I record a serial number and password in my iphone ???
What is best way to record a user serial number/password in iphone ?
If you are a storing password, not NSUserDefaults nor serializing the data in NSDocumentDirectory are great solutions because data is stored with little protection. iOS provides the KeyChain mechanism for this porupose. It provides C interfaces that are a bit obscure, but a Buzz Andersen got a nice Objective-C interface going called SFHFKeychainUtils. With SFHFKeychainUtils you can do something like:
[SFHFKeychainUtils storeUsername:user.text andPassword:pass.text forServiceName:#"my_service" updateExisting:YES error:nil];
And that gets stored securely into the keychain. To recover the password:
NSString *pw = [SFHFKeychainUtils getPasswordForUsername:user.text andServiceName:#"my_service"