我正在开发一个 ios 应用程序,因为我需要输入公司代码和访问代码才能登录。首次使用访问码登录后,我们不能在打开应用程序时再次要求访问码。我的意思是我需要保存首选项。
我的代码在这里
- (IBAction)loginClicked:(id)sender {
@try {
if([[txtsecurecode text] isEqualToString:@""] || [[OrganizationCode text] isEqualToString:@""] ) {
[self alertStatus:@"Please enter Access code" :@"Login Failed!":0];
} else {
NSString *post =[[NSString alloc] initWithFormat:@"txtsecurecode=%@ @&password=%@",[txtsecurecode text],[OrganizationCode text]];
NSLog(@"PostData: %@",post);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://mycompany.com/AccountService/security/ValidateAccess?accesscode=%@&companycode=%@&type=1", txtsecurecode.text, OrganizationCode.text]];
[[ NSUserDefaults standardUserDefaults] setValue:OrganizationCode forKey:@"OrganizationCode"];
[[ NSUserDefaults standardUserDefaults] setValue:txtsecurecode forKey:@"txtsecurecode"];
[[NSUserDefaults standardUserDefaults] synchronize];
txtsecurecode = [[NSUserDefaults standardUserDefaults] objectForKey:@"txtsecurecode"];
OrganizationCode = [[NSUserDefaults standardUserDefaults] objectForKey:@"OrganizationCode"];
// NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"txtsecurecode"];
NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
if([responseData isEqualToString:@""]){
[self alertStatus:@"Please enter valid Access Code" :@"Login Failed !" :0];
}
else
{
responseData = [responseData stringByReplacingOccurrencesOfString:@" "" " withString:@""];
responseData = [responseData stringByReplacingOccurrencesOfString:@"\\" withString:@""];
NSString* encodedString = [responseData stringByReplacingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSLog(@"Response ==> %@" ,encodedString);
UIWebView *webView;
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0, 320, 470)];
webView.backgroundColor = [UIColor clearColor];
webView.opaque = NO;
[webView setDelegate:self];
NSString* urlTwo = [[encodedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
stringByReplacingOccurrencesOfString:@"%22" withString:@""];
NSURL *url2;
if([urlTwo hasPrefix:@"http://"]){
url2 = [NSURL URLWithString:urlTwo];
}else{
url2 = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@" , urlTwo]];
}
NSLog(@"url2:%@", url2);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[webView loadRequest:requestObj];
[[self view] addSubview:webView];
}
}
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
[self alertStatus:@"Login Failed." :@"Login Failed!" :0];
}
}
我曾使用 NSUserDefaults 方法来保存登录凭据,但它不起作用。凭据没有保存,应用程序再次要求凭据。