Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JSON验证登录时的iOS密钥链实现_Ios_Objective C_Json_Keychain - Fatal编程技术网

使用JSON验证登录时的iOS密钥链实现

使用JSON验证登录时的iOS密钥链实现,ios,objective-c,json,keychain,Ios,Objective C,Json,Keychain,我整晚都在看iOS密钥链文档,试图找出如何在我当前的代码中实现它。因为我使用解析的JSON在应用程序和服务器之间来回传递,所以我使用key和objectForKey 几乎所有关于钥匙链的文档都是2011年或更早的版本。它已经过时了吗?此外,在所有的“KeyChainWrapper”和“SSKeychain”中,我也同样感到困惑。任何关于如何处理我的代码的建议都是非常有帮助的。特别是与objectForKey问题相关的keychain 我的ViewController.m文件 - (IBActio

我整晚都在看
iOS密钥链
文档,试图找出如何在我当前的代码中实现它。因为我使用解析的
JSON
在应用程序和服务器之间来回传递,所以我使用key和
objectForKey

几乎所有关于钥匙链的文档都是2011年或更早的版本。它已经过时了吗?此外,在所有的“
KeyChainWrapper
”和“
SSKeychain
”中,我也同样感到困惑。任何关于如何处理我的代码的建议都是非常有帮助的。特别是与
objectForKey
问题相关的
keychain

我的ViewController.m文件

- (IBAction)loginClicked:(id)sender {
    NSInteger success = 0;
    @try {

        if([[self.usernameText text] isEqualToString:@""] || [[self.passwordText text] isEqualToString:@""] ) {

            [self alertStatus:@"Please enter Email and Password" :@"Sign in Failed!" :0];

        } else {
            NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.usernameText text],[self.passwordText text]];
            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://www.domain.com/auth.php"];

            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

            NSLog(@"Response code: %ld", (long)[response statusCode]);

            if ([response statusCode] >= 200 && [response statusCode] < 300)
            {
                NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                NSLog(@"Response ==> %@", responseData);

                NSError *error = nil;
                NSDictionary *jsonData = [NSJSONSerialization
                                          JSONObjectWithData:urlData
                                          options:NSJSONReadingMutableContainers
                                          error:&error];

                success = [jsonData[@"success"] integerValue];
                NSLog(@"Success: %ld",(long)success);

                if(success == 1)
                {
                    NSLog(@"Login SUCCESS");
                    [self performSegueWithIdentifier:@"login_success" sender:self];

                }

                else {

                    NSString *error_msg = (NSString *) jsonData[@"error_message"];
                    [self alertStatus:error_msg :@"Sign in Failed!" :0];
                }

            } else {
                //if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Sign in Failed!" :0];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Error!" :0];
    }

}

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    alertView.tag = tag;
}
-(iAction)登录勾选:(id)发件人{
NSInteger成功率=0;
@试一试{
if([[self.usernameText]IseQualtString:@”“][[self.passwordText]IseQualtString:@”“])){
[自我提醒状态:@“请输入电子邮件和密码”:@“登录失败!”:0];
}否则{
NSString*post=[[NSString alloc]initWithFormat:@“用户名=%@&密码=%@”,[self.usernameText],[self.passwordText];
NSLog(@“PostData:%@”,post);
NSURL*url=[NSURL URLWithString:@”http://www.domain.com/auth.php"];
NSData*postData=[post数据使用编码:NSASCIIStringEncoding allowLossyConversion:是];
NSString*postLength=[NSString stringWithFormat:@“%lu”,(无符号长)[postData长度]];
NSMutableURLRequest*请求=[[NSMutableURLRequest alloc]init];
[请求设置url:url];
[请求设置HttpMethod:@“POST”];
[请求设置值:HttpHeaderField的postLength:@“内容长度”];
[请求设置值:@“应用程序/json”用于HttpHeaderField:@“接受”];
[请求设置值:@“应用程序/x-www-form-urlencoded”forHTTPHeaderField:@“内容类型”];
[请求setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHttpSCCertificate:YES for主机:[url主机]];
NSError*error=[[NSError alloc]init];
NSHTTPURLResponse*响应=nil;
NSData*urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&响应错误:&错误];
NSLog(@“响应代码:%ld”,(长)[响应状态代码]);
如果([response statusCode]>=200&&[response statusCode]<300)
{
NSString*responseData=[[NSString alloc]initWithData:urlData编码:NSUTF8StringEncoding];
NSLog(@“响应==>%@”,响应数据);
n错误*错误=nil;
NSDictionary*jsonData=[NSJSONSerialization
JSONObjectWithData:urlData
选项:NSJSONReadingMutableContainers
错误:&错误];
success=[jsonData[@“success”]integerValue];
NSLog(@“成功:%ld”,(长)成功);
如果(成功==1)
{
NSLog(@“登录成功”);
[self-PerformsgueWithIdentifier:@“登录成功”发件人:self];
}
否则{
NSString*错误消息=(NSString*)jsonData[@“错误消息”];
[自我提醒状态:错误消息:@“登录失败!”:0];
}
}否则{
//if(error)NSLog(@“error:%@”,error);
[自我提醒状态:@“连接失败”:@“登录失败!”:0];
}
}
}
@捕获(N例外*e){
NSLog(@“异常:%@”,e);
[自我提醒状态:@“登录失败”。:@“错误!”:0];
}
}
-(void)alertStatus:(NSString*)msg:(NSString*)title:(int)标记
{
UIAlertView*alertView=[[UIAlertView alloc]initWithTitle:title
信息:msg
代表:赛尔夫
取消按钮:@“确定”
其他按钮类型:无,无];
alertView.tag=标签;
}

以下是ARC版本钥匙链包装器的代码。只需将h/m文件复制并粘贴到项目中


是否要在密钥链中保存accountName和密码,并使用accountName检索该密码?忘了锁链包装器吧,它也让我困惑。它不是过时的。由于有一半的互联网用户发现自己的安全性受到了损害,因此很难做到安全,为了改变而改变也不是一个好主意。@KudoCC我只想分别保存用户名和密码(如果这是标准的话),并能在应用程序关闭后使用它们进行自动登录,以及,在整个用户会话中根据需要使用这些信息(将用户名发送到数据库,并返回帐户信息以填充应用程序提要)。@gnasher729我问它是否已经过时。我看到的唯一代码和文档都包括ARC内容…认为2011年后由Xcode处理?因为它是ARC版本,我不需要在其他地方对代码进行一些更改吗?我还需要在我的任何项目中使用类似的东西。计划在几周内尝试一下。不幸的是,我不知道在我所有的if语句中添加这段代码的位置。不管我把它放在哪里,我都会得到一个例外“无法添加钥匙链项目”。如果你能告诉我在哪里抛出这个代码。谢谢。这取决于你的应用程序的结构。例如,在我的应用程序中,我从用户那里获取登录凭据,并使用上面的前3行将其保存到密钥链中。然后我将登录请求发送到服务器。如果登录无效,我将重置keychainItem并要求用户输入新凭据。如果登录成功,应用程序将移动用户通过我的登录视图控制器,并读取登录凭据
//create a pointer to a KeychainItemWrapper
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"loginCredentials" accessGroup:nil];

// set the credentials (email and password are NSStrings in this example)
[keychainItem setObject:email forKey:(__bridge id)(kSecAttrAccount)];
[keychainItem setObject:password forKey:(__bridge id)(kSecValueData)];

// access an object after it has been set
NSString *email = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];

// resets the contents of "loginCredentials"
[keychainItem resetKeychainItem];