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"
Related
So, I'm trying to open a .mobileprovisioning profile to read what's inside... this is what I'm doing:
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
Of course I get the data read but I'm not finding the way of getting of get this data into something useful... an NSDictionary, an NSString or whatever...
I've already tried:
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Any idea? I'm sure this is an encoding issue, but I can't solve it after reading and googling for some time... I think the provisioning profile is saved as hexadecimal, but I don't know how to read that from objective-c. I have found this but there wasn't an useful answer.
How to convert NData populated with hex values to NSString
Thanks!
The following method should do what you want. As #rbrockerhoff says the mobile provisioning profile is an encoded CMS message. This method uses a decoder to first decode the data using the CMS functions and then creates the plist string/contents from the decoded data. This string can then be converted into a dictionary which is returned from the method. The dictionary will contain all the details from the mobile provisioning profile.
- (NSDictionary *)provisioningProfileAtPath:(NSString *)path {
CMSDecoderRef decoder = NULL;
CFDataRef dataRef = NULL;
NSString *plistString = nil;
NSDictionary *plist = nil;
#try {
CMSDecoderCreate(&decoder);
NSData *fileData = [NSData dataWithContentsOfFile:path];
CMSDecoderUpdateMessage(decoder, fileData.bytes, fileData.length);
CMSDecoderFinalizeMessage(decoder);
CMSDecoderCopyContent(decoder, &dataRef);
plistString = [[NSString alloc] initWithData:(__bridge NSData *)dataRef encoding:NSUTF8StringEncoding];
NSData *plistData = [plistString dataUsingEncoding:NSUTF8StringEncoding];
plist = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:nil error:nil]
}
#catch (NSException *exception) {
NSLog(#"Could not decode file.\n");
}
#finally {
if (decoder) CFRelease(decoder);
if (dataRef) CFRelease(dataRef);
}
return plist;
}
A .mobileprovisioning file is an encoded CMS message.
See https://developer.apple.com/library/mac/documentation/security/Reference/CryptoMessageRef/Reference/reference.html for details and an API for decoding it.
If you just want the encoded property list as text, a quick-and-dirty hack is to get the byte pointer for your NSData, scan for the beginning "<?xml" and up to the closing "</plist>". Then make a NSString from that.
You can simply force to open the mobile provisioning profile in TextEdit where you can see the
interior contents and in which you can trim/Edit the encoded CMS message or whatever you want . Then you can simply decode with NSData encodewithUTF string method.
Hope this helps.
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.
I have recently started Application development on MAC OS 10.6, I am trying to modify a "key/value" pair in a local JSON file on my MAC machine using SBJSON. I have successfully read the value of a key, but I am not able to get that how to modify the value of a key and synchronize this to the JSON file. Lets suppose, I have a following JSON Data int o a local file:
{
"name": {
"fName":"John",
"lName":"Doe"
}
}
And i want to change the value of "fName" to something else, like Robert.
I have tried alot searching about it, but got no clue... Can anyone help me.
I am using SBJSON Framework!
Code:
NSString *filePath = #"/Users/dev/Desktop/SQLiteFile/myJSON2.json";
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *responseString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"FILE CONTENT : %#", responseString);
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSDictionary * dictionary = (NSDictionary*)[jsonParser objectWithString:responseString error:NULL];
[dictionary setObject:#"Robert" forKey:#"fName"];
//
// Code for writing this change into the file, which i needed.
//
[jsonParser release];
You want a mutable deep copy of your dictionary. Then you'll be able to modify it.
I have an application currently on the app store which I intend to submit an update for soon.
With this update I want to add code which will tell the app when it first runs application:didFinishLaunchingWithOptions whether it is:
A new install from the app store.
Newly updated from a previous version
There is no code in the app currently in the app store to handle this.
The application uses a SQLite database, but for reasons I won't go into here I don't want to use a check for its existence as a solution to this problem.
As a side question, without storing the data manually, is there an SDK I can use to query when an app was installed onto a device? (Preferably iOS 3.0 compatible)
I have seen a similar question, but none of the answers apply to working with existing app store code.
The following code may help to answer your side question about when an app was installed. I am unsure if the app bundle create date is the XCode build date or the download date as this is untested from app store.
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath]; // e.g. /var/mobile/Applications/<GUID>/<AppName>.app
NSFileManager *manager = [NSFileManager defaultManager];
NSDictionary* attrs = [manager attributesOfItemAtPath:bundleRoot error:nil];
NSLog(#"Build or download Date/Time of first version to be installed: %#", [attrs fileCreationDate]);
NSLog(#"Date/Time of last install (unless bundle changed by code): %#", [attrs fileModificationDate]);
NSString *rootPath = [bundleRoot substringToIndex:[bundleRoot rangeOfString:#"/" options:NSBackwardsSearch].location]; // e.g /var/mobile/Applications/<GUID>
attrs = [manager attributesOfItemAtPath:rootPath error:nil];
NSLog(#"Date/Time first installed (or first reinstalled after deletion): %#", [attrs fileCreationDate]);
You could save a version number to NSUserDefaults, and update it accordingly.
If that won't work, you may be able to release an intermediate version which introduces the versioning scheme.
If that's not an option, you may be able to check for traces of previous runs from files you create, or preferences which you set conditionally or lazily.
try this code, i know i am too late for this answer but for knwoldge sharing here i go.
-(void) checkIsAppUpdated
{
NSString *urlString = #"http://itunes.apple.com/lookup?id=995558215";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSString *stringReply = (NSString *)[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error)
{
// NSLog(#"Error: %#", stringReply);
//error reviced
}
else
{
//The response is in data
//NSLog(#"Success: %#", stringReply);
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
float appStoreVersion=[[[[dictResponse objectForKey:#"results"] firstObject] objectForKey:#"version"] floatValue];
NSLog(#"app stroe version=%f",appStoreVersion);
NSString *strLocalVersion=[[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleShortVersionString"];
float localAppVersion=[strLocalVersion floatValue];
if (localAppVersion!=appStoreVersion)
{
//open app store url
// NSString *iTunesLink = #"itms://itunes.apple.com/us/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"https://itunes.apple.com/app/washthenfold/id995558215?mt=8"]];
}
}
}
note
id:-replace id with your own app id. you can get app id from itune connect selected app->more info->meta data
since simulator doesn't have app store app, this code won't work on simulator.
GBVersionTracking is good pod to track all version history.
[GBVersionTracking isFirstLaunchEver];
Here is a simple code to know if the current version is different (this code work on simulator too.)
-(BOOL) needsUpdate
{
NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString* appID = infoDictionary[#"CFBundleIdentifier"];
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://itunes.apple.com/lookup?bundleId=%#", appID]];
NSData* data = [NSData dataWithContentsOfURL:url];
NSDictionary* lookup = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if ([lookup[#"resultCount"] integerValue] == 1)
{
NSString* appStoreVersion = lookup[#"results"][0][#"version"];
NSString* currentVersion = infoDictionary[#"CFBundleShortVersionString"];
if (![appStoreVersion isEqualToString:currentVersion])
{
NSLog(#"Need to update [%# != %#]", appStoreVersion, currentVersion);
return YES;
}
}
return NO;
}
Note: Make sure that when you enter the new version in iTunes, this matches the version in the app you are releasing. If not then the above code will always return YES regardless if the user updates.
I have a embedded uiwebview in my app which will in turn call a webpage. This webpage contains some data which should be saved in the user defaults of the iphone. How to achieve this ?
It very much depends on what your page and data looks like... The basic approach is to use -stringByEvaluatingJavaScriptFromString: to retrieve content, e.g.:
NSString *script = #"document.getElementById('myTextInput').value";
NSString *result = [webView stringByEvaluatingJavaScriptFromString:script];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
result, #"MyTextInputValue",
// ... more?
nil];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"MyWebViewData"];
If the data is only used by scripts in the page, you could also simply use a script function that returns you one JSON string to store:
NSString *script = #"window.getJsonData()";
NSString *json = [webView stringByEvaluatingJavaScriptFromString:script];