如何在目标c中检查用户是否登录



我正在尝试登录页面和注销页面。我成功地完成了api调用和登录,但我正在尝试检查用户是否已经登录。如果用户登录并杀死了应用程序,有时用户打开应用程序后,意味着应用程序应该显示主页,但我的应用程序显示登录页面。我尝试了下面的代码和api调用。

NSString *mailID=mailTextField.text;
NSString *password=passwordTextField.text;
NSString *noteDataString = [NSString stringWithFormat:@"email=%@&password=%@",mailID,password];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{@"language": @"en"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:@"https://qa-user.moneyceoapp.com/user/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSData *data = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody=data;
request.HTTPMethod = @"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

NSHTTPURLResponse *httpResponse= (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"The response is - %@",responseDictionary);
NSInteger status = [[responseDictionary objectForKey:@"status"] integerValue];
if(status == 1)
{
NSLog(@"Login SUCCESS");
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs setObject:mailID forKey:@"email"];
[defs setObject:password forKey:@"password"];
[defs synchronize];
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
if(mailID && password)
{
HomePageVC *homepageVC = [[HomePageVC alloc] initWithNibName:@"HomePageVC" bundle:nil];
[self.navigationController pushViewController:homepageVC animated:YES];
}
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^
{
NSLog(@"Login FAILURE");
[self alertView:@"Invalid user account"];
}];
}
}
else
{
NSLog(@"Error");
}
}];
[postDataTask resume];

我使用使用NSUserDefaults的类来创建一个包含用户登录信息参数的字典。此外,我使用布尔值来检查一个等效名称为joinedApp的值。

*DataModel.h*
//
@class Message;
// The main data model object
@interface DataModel : NSObject
// The complete history of messages this user has sent and received, in
// chronological order (oldest first).
@property (nonatomic, strong) NSMutableArray* messages;
// Loads the list of messages from a file.
- (void)loadMessages;
// Saves the list of messages to a file.
- (void)saveMessages;
// Adds a message that the user composed himself or that we received through
// a push notification. Returns the index of the new message in the list of
// messages.
- (int)addMessage:(Message*)message;
// Get and set the user's nickname.
- (NSString*)nickname;
- (void)setNickname:(NSString*)name;
// Get and set the secret code that the user is registered for.
- (NSString*)secretCode;
- (void)setSecretCode:(NSString*)string;
// Determines whether the user has successfully joined a chat.
- (BOOL)joinedChat;
- (void)setJoinedChat:(BOOL)value;
- (BOOL)joinedApp;
- (void)setJoinedApp:(BOOL)value;

- (NSString*)userId;
- (NSString*)deviceToken;
- (void)setDeviceToken:(NSString*)token;
@end

数据模型.m

#import "DataModel.h"
#import "Message.h"
#import "ViewController.h"
// We store our settings in the NSUserDefaults dictionary using these keys
static NSString* const NicknameKey = @"Nickname";
static NSString* const SecretCodeKey = @"SecretCode";
static NSString* const JoinedChatKey = @"JoinedChat";
static NSString* const JoinedAppKey = @"JoinedApp";
static NSString* const DeviceTokenKey = @"DeviceToken";
static NSString* const UserId = @"UserId";
@implementation DataModel
+ (void)initialize
{
if (self == [DataModel class])
{

// Register default values for our settings
[[NSUserDefaults standardUserDefaults] registerDefaults:
@{NicknameKey: @"",
SecretCodeKey: @"",
JoinedChatKey: @0,
JoinedAppKey: @0,
DeviceTokenKey: @"0",
UserId:@""}]; 
}
}
// Returns the path to the Messages.plist file in the app's Documents directory
- (NSString*)messagesPath
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = paths[0];
return [documentsDirectory stringByAppendingPathComponent:@"Messages.plist"];
}
- (void)loadMessages
{
NSString* path = [self messagesPath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
// We store the messages in a plist file inside the app's Documents
// directory. The Message object conforms to the NSCoding protocol,
// which means that it can "freeze" itself into a data structure that
// can be saved into a plist file. So can the NSMutableArray that holds
// these Message objects. When we load the plist back in, the array and
// its Messages "unfreeze" and are restored to their old state.
NSData* data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self.messages = [unarchiver decodeObjectForKey:@"Messages"];
[unarchiver finishDecoding];
}
else
{
self.messages = [NSMutableArray arrayWithCapacity:20];
}
}
- (void)saveMessages
{
NSMutableData* data = [[NSMutableData alloc] init];
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self.messages forKey:@"Messages"];
[archiver finishEncoding];
[data writeToFile:[self messagesPath] atomically:YES];
}
- (int)addMessage:(Message*)message
{
[self.messages addObject:message];
[self saveMessages];
return self.messages.count - 1;
}
- (NSString*)nickname
{
return [[NSUserDefaults standardUserDefaults] stringForKey:NicknameKey];
}
- (void)setNickname:(NSString*)name
{
[[NSUserDefaults standardUserDefaults] setObject:name forKey:NicknameKey];
}
- (NSString*)secretCode
{
return [[NSUserDefaults standardUserDefaults] stringForKey:SecretCodeKey];
}
- (void)setSecretCode:(NSString*)string
{
[[NSUserDefaults standardUserDefaults] setObject:string forKey:SecretCodeKey];
}
- (BOOL)joinedApp
{
return [[NSUserDefaults standardUserDefaults] boolForKey:JoinedAppKey];
}
- (void)setJoinedApp:(BOOL)value
{
[[NSUserDefaults standardUserDefaults] setBool:value forKey:JoinedAppKey];
}
- (BOOL)joinedChat
{
return [[NSUserDefaults standardUserDefaults] boolForKey:JoinedChatKey];
}
- (void)setJoinedChat:(BOOL)value
{
[[NSUserDefaults standardUserDefaults] setBool:value forKey:JoinedChatKey];
}
- (NSString*)userId
{
NSString *userId = [[NSUserDefaults standardUserDefaults] stringForKey:UserId];
if (userId == nil || userId.length == 0) {
userId = [[[NSUUID UUID] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
[[NSUserDefaults standardUserDefaults] setObject:userId forKey:UserId];
}
return userId;
}
- (NSString*)deviceToken //used in appdelegate
{
return [[NSUserDefaults standardUserDefaults] stringForKey:DeviceTokenKey];
}
- (void)setDeviceToken:(NSString*)token //used in app delegate
{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:DeviceTokenKey];
}

@end

然后,我在viewIsLoaded方法中调用消息,并在调试器窗口中打印验证。

*ViewController.h*
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@class DataModel;
@interface ViewController : UIViewController
@property (nonatomic, strong, readonly) DataModel* dataModel;
@property (retain, strong) UIImage* Image;
@end

ViewController.m

#import "ViewController.h"
#import "DataModel.h"
#import "PushChatStarter-Swift.h"
@implementation ViewController
- (id) initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
_dataModel = [[DataModel alloc] init];

}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
MockApiclient *client = [MockApiclient new];
[client executeRequest];
[self.dataModel setJoinedApp:YES];
if ([_dataModel joinedApp] == YES)
{
NSLog(@"hi from viewcontroller 1 ");//Here you know which button has pressed
}
...

}

NSUser默认值:

用户默认数据库的接口,在应用程序的启动过程中持久存储键值对。

我还从与其他消息一起使用的登录方法调用joinedApp。

最新更新