微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在目标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

DataModel.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

}
...

}

 NSUserDefaults:

用户默认数据库的接口,您可以在其中持久存储应用启动时的键值对。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。