IOS开发(8)WKWebView解决ajax请求无JSESSIONID问题

开发IOS过程中,现在普遍都是混合的方式开发,免不了使用wkwebview控件,这个控件相比uiwebview好处不是一星半点,具体自行百度。总感觉IOS挺高大尚,等自己用wkwebview来开发的时候,大一堆的坑,网上帖子也是一大抄,身为小白的无,尝试了网络上说的各种方法,均没有解决自己的问题。最后还是和一个临时加为QQ好友的哥们讨论下解决的。

我的问题是这样的,使用wkwebview后,页面内部的ajax请求访问数据,没有携带jsessionid,这样就导致我的后台告诉我没有登录认证。解决方式:

1.登录的时候吧jsessionid缓存到本地

- (IBAction)login:(id)sender {
    NSDictionary *parameters = @{@"account": @"admin", @"password": @"password"};

    [[WITHttpTool sharedManager] POST:@"user/login" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *result =  [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",result);

        NSHTTPURLResponse  *response =  (NSHTTPURLResponse *)task.response;
        NSString  *cookie = [response allHeaderFields][@"Set-Cookie"];
        NSString  *valueString = [[NSUserDefaults standardUserDefaults] objectForKey:@"userCookie"];
        if (valueString != @"") {
            if ([cookie rangeOfString:@"Expires="].location!=NSNotFound) {
                cookie = [cookie componentsSeparatedByString:@"Expires="][0];
                cookie = [cookie componentsSeparatedByString:@";"][0];
            }
            NSUserDefaults *saveDef = [NSUserDefaults standardUserDefaults];
            [saveDef setValue:cookie forKey:@"JSESSIONID"];
            [saveDef synchronize];
        }

        WITOrderFoodViewController *wm = [[WITOrderFoodViewController alloc] init];
        self.view.window.rootViewController = wm;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

}

2.加载wkwebview的时候把缓存到本地jsessionid设置上去,这样ajax请求就会携带jsessionid。

- (void)viewDidLoad {
    [super viewDidLoad];

    WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
    // 设置偏好设置
    configuration.preferences = [[WKPreferences alloc] init];
    // 默认为0
    configuration.preferences.minimumFontSize = 10;
    // 默认认为YES
    configuration.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO,表示不能自动通过窗口打开
    configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;

    // 通过JS与webview内容交互
    configuration.userContentController = [[WKUserContentController alloc] init];

    //获取本地缓存JSESSIONID数据
    NSString  *cookieValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"JSESSIONID"];
    //NSLog(@"值是%@",cookieValue);
    //拼接Cookie
    NSString *cookie = [NSString stringWithFormat:@"document.cookie = '%@;path=/restaurant/';",cookieValue];
    //NSLog(@"cppkies = %@", cookie);

    //通过oc 调用js 方法设置cookies
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookie
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];

    [configuration.userContentController addUserScript:cookieScript];

    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) configuration:configuration];
    self.webView.navigationDelegate = self;
    [self.view addSubview: self.webView];

    NSString *url = @"http://192.168.10.158:8010/restaurant/mobile/ios/orderFood 

";
    NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: url] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //添加请求cookies
    [requestObj addValue:cookieValue forHTTPHeaderField:@"Cookie"];

    //添加view
    [self.view addSubview: self.webView];

    // 加载请求
    [self.webView loadRequest:requestObj];

}

这样就搞定了。没有网上说的那么麻烦。不过这只是个demo,具体还要更具app要求更改。就这么一个问题浪费了我小一天的时间。

你可能感兴趣的:(IOS)