UIWebview检查用户是否登录并返回True或False

时间:2018-09-25 09:19:46

标签: ios objective-c cookies uiwebview nsuserdefaults

我正在将Webview应用程序更新为最新的iOS SDK,以支持iOS 12.0。我曾经通过Cookie和 NSURLConnection 调用会话和登录信息,因此如果用户登录,则在侧面菜单中返回用户名。在更新SDK和PODS之后,即使他已经登录并且Loggedin = null的值,我总是让用户注销。

我的ViewController代码

- (void)viewDidLoad {
    [super viewDidLoad];
    preferences = [[NSUserDefaults alloc] init];
    NSLog(@"perf %@", preferences)
    isLoggedin = [preferences objectForKey:@"islogedin"];
    NSLog(@"isLoggedin View Controller --- %@", isLoggedin)
}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [self loadCookies];
   // webView.hidden=NO;
  //  [SVProgressHUD dismiss];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{

[self saveCookies];

//  [SVProgressHUD dismissWithDelay:0.5 completion:^{
//      webView.hidden=NO;;
//      
//  }];
}

-(void)saveCookies{
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults    = [NSUserDefaults standardUserDefaults];
   [defaults setObject: cookiesData forKey: @"cookies"];
   [defaults synchronize];
}

- (void)loadCookies
{
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"cookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in cookies)
    {
        [cookieStorage setCookie: cookie];
    }
}

-(void)getUserName
{
    NSString *userName = @"";
    NSString *string = [webview stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
    NSData *tutorialsHtmlData = [string dataUsingEncoding:NSUTF8StringEncoding];

    TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];

    NSString *tutorialsXpathQueryString = @"//span[@id='app_customer_name']";

    NSArray *nodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

    for (TFHppleElement *element in nodes) {
        userName = [element valueForKey:@"text"];
        [[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"userName"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSLog(@"username==%@", userName);
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"name" object:userName];

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [webData setLength: 0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
  [self loadCookies];
}

-(void)doFurtherProcessingWithResult{
   //NSLog(@"do furtherprocessing with result");
    arrNavigation = [[NSMutableArray alloc] init];
    NSError *error = nil;
    NSData *objectData = [dataFromApi dataUsingEncoding:NSUTF8StringEncoding];
    id collection = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
    //    id mainCollection = collection;

    if(error){
       NSLog(@"JSON data received is not in correct form");
    }

    NSArray *categories = [collection objectForKey:@"categories"];

    for(NSObject *category in categories){
        NSArray *children = [category valueForKey:@"children"];
       //NSLog(@"child====%@", children);

        NSString *htname = [category valueForKey:@"name"];
        NSAttributedString * attrtitle = [[NSAttributedString alloc] initWithData:[htname dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

        NSString *title = attrtitle.string;
        NSString *link = [category valueForKey:@"path"];
        NSString *icon = [category valueForKey:@"icon"];
        NSString *image = [category valueForKey:@"image"];
        NSMutableArray *sub = [[NSMutableArray alloc] init];

        for (NSObject *child in children){
            NSString *titlestr = [child valueForKey:@"name"];
            NSAttributedString * attrsubtitle = [[NSAttributedString alloc] initWithData:[titlestr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
            NSString *title = attrsubtitle.string;
            //NSLog(@"title--------------------");
            NSString *link = [child valueForKey:@"path"];
            NSDictionary *subdic = [NSDictionary dictionaryWithObjects:@[title, link] forKeys:@[@"title",@"link"]];
            [sub addObject:subdic];
        }
        NSDictionary *dic = [NSDictionary dictionaryWithObjects:@[title,link,icon,image,sub] forKeys:@[@"title",@"link",@"icon",@"image",@"sub"]];
       // NSLog(@"dic===has sub=%@", dic);
        [arrNavigation addObject:dic];

    }
    //NSLog(@"viewcontroller-----%lu", (unsigned long)arrNavigation.count);
    [[NSUserDefaults standardUserDefaults] setObject:arrNavigation forKey:@"sideMenu"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //NSLog(@"categories------%@", categories);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadMenu" object:nil];

}

在我的SideMenuVC中,我正在检查首选项是否显示为已登录,请致电用户名,否则保持注销状态。

@implementation SideMenuVC

- (void)viewDidLoad {
    [super viewDidLoad];

    preferences = [[NSUserDefaults alloc] init];
    islogedin = [preferences objectForKey:@"islogedin"];
    userName = @"";
    if([preferences objectForKey:@"userName"]){
        userName = [preferences objectForKey:@"userName"];
    }
    [self reloadMenu];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadMenu) name:@"reloadMenu" object:nil];
    if([islogedin isEqualToString:@"true"]){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setName:) name:@"name" object:nil];
        NSLog(@"User Loggedin")
    } else {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLogout:) name:@"name" object:nil];
        NSLog(@"User Loggedout")
    }
}

-(void)setName:(NSNotification *)notification{
    NSLog(@"logged in & received--------");
    NSString *name = [notification object];
    NSLog(@"the name is %@", name)
    NSString *msg = [NSString stringWithFormat:@"Welcome %@", name];
    [signinBtn setTitle:msg forState:UIControlStateNormal];
    logoutBtn.hidden = NO;
    islogedin = @"true";
}

-(void)setLogout:(NSNotification *)notification{
    NSLog(@"loggedout--------");
    //NSString *name = [notification object];
    NSString *msg = [NSString stringWithFormat:@"Hello, Sign In"];
    [signinBtn setTitle:msg forState:UIControlStateNormal];
    logoutBtn.hidden = YES;
    islogedin = @"false";
}

-(void)reloadMenu{
    arrNavigation = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"sideMenu"]];
    openSection = arrNavigation.count;
    [leftPanel reloadData];
}

-(void)clearCookies{
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"cookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in cookies)
    {
        [cookieStorage deleteCookie: cookie];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

检查islogedin = [preferences objectForKey:@"islogedin"];时,返回始终为null,而返回值应为TRUE或FALSE,并始终调用-(void)setLogout:

请提供任何帮助,我做错了什么以及如何解决此问题。在此先感谢!

1 个答案:

答案 0 :(得分:0)

我看不到将“ islogedin”值保存为首选项的任何地方。 也许在您的SideMenuVC中添加一些代码来保存它们

-(void)setName:(NSNotification *)notification{
...
islogedin = @"true"; //code
[preferences setObject:islogedin forKey:@"islogedin"];}


-(void)setLogout:(NSNotification *)notification{
...
islogedin = @"false"; // your code
[preferences setObject:islogedin forKey:@"islogedin"];}

顺便说一句,在两个文件中,第一个vc中的一个变量是“ isLoggedin”,而第二个类中的一个变量是“ islogedin”。看到不同。它可能会被忽略。