Я обновляю приложение для веб-просмотра до последней версии iOS SDK для поддержки iOS 12.0.Я использовал для вызова сеанса и информацию для входа через куки и NSURLConnection , поэтому, если пользователь вошел в систему, верните имя пользователя в sidemenu.После обновления 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];
}
Вmy 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"];
возврат всегда равен нулю, в то время как он должен быть ИСТИНА или ЛОЖЬ и всегда вызывать-(void)setLogout:
Любая помощь, пожалуйста, что я сделал не так и как решить эту проблему.Спасибо заранее!