Bạn không cần phải bận tâm với NSUserDefaults hoặc bất kỳ trình bao bọc keychain nào nếu bạn sử dụng NSURLCredential
. Thật vậy NSURLCredential
là đơn giản hơn nhiều để sử dụng, vì nó cho phép bạn lưu trữ cả tên người dùng và mật khẩu trong chuỗi trong hai dòng mã.
Mã của bạn sẽ là một cái gì đó như thế khi người dùng đăng nhập:
NSURLCredential *credential;
credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:self.loginProtectionSpace];
Sau đó, mỗi lần ứng dụng được khởi động, bạn có thể kiểm tra xem người dùng của bạn đã được đăng nhập bằng cách tìm kiếm cho bất kỳ chứng chỉ trong để tự động đăng nhập lại dùng của bạn (nếu cần thiết):
NSURLCredential *credential;
NSDictionary *credentials;
credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
NSLog(@"User %@ already connected with password %@", credential.user, credential.password);
bạn cũng cần để làm sạch các chứng chỉ khi người dùng muốn đăng xuất:
NSURLCredential *credential;
NSDictionary *credentials;
credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace];
credential = [credentials.objectEnumerator nextObject];
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:self.loginProtectionSpace];
loginProtectionSpace
được tạo một lần cho tất cả. Xin lưu ý rằng mã mẫu này giả định chỉ có một thông tin đăng nhập trong không gian này, thường là trường hợp trừ khi bạn quản lý một số tài khoản.
Dưới đây là một ví dụ về cách bạn sẽ tạo ra một NSURLProtectionSpace
:
NSURL *url = [NSURL URLWithString:@"http://www.example.com"];
self.loginProtectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url.host
port:[url.port integerValue]
protocol:url.scheme
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPDigest];
Cảm ơn bạn đã trả lời, vâng đây là những gì tôi làm để giữ cho thông tin cũ. Điều tôi muốn tránh là POST ban đầu để đăng nhập ở mỗi lần khởi động lại ứng dụng, tôi chỉ tự hỏi liệu thời gian tồn tại của cookie được AFNetworking xử lý có thể được mở rộng hay không. –
Thực ra, vui lòng không lưu trữ tên người dùng và mật khẩu trong NSUserDefaults. Sử dụng keychain để thay thế. Apple phân phối một KeychainWrapper mà về cơ bản giống nhau, nhưng an toàn hơn. – eddieroger