Can't set headers on my WKWebView POST request

前端 未结 7 1353
花落未央
花落未央 2020-12-04 12:50

I want to do a POST request to my WKWebView but the headers doesn\'t get set when I monitor the requests with Charles so the request fails. What is wrong here?<

7条回答
  •  时光取名叫无心
    2020-12-04 13:23

    workaround: trick by using html5 & javascript.

    Add a html5 file with content below to your xcode project. To post data by using javascript & h5 form:

    
        
            
        
        
        
    
    

    Load the h5 file to WKWebView:

    WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [[WKPreferences alloc]init];
    config.preferences.javaScriptEnabled = YES;
    WKWebView* webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:config];
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"JSPOST" ofType:@"html"];
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
    

    Prepare the parameters to post. ie. a string & an array of dictionary Note: when turn array to json string by using NSJSONSerialization, '\r' may be added automaticly. You must remove all the '\r' in the json string, or the javascript cannot be parsed correctly.

    // parameters to post
    NSString* name = @"Swift";
    NSArray* array = @[@{@"id":@"1", @"age":@"12"}, @{@"id":@"2", @"age":@"22"}];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\'"];
    // trim spaces and newline characters
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *postData = [NSString stringWithFormat: @"'name':'%@', 'contacts':'%@'", name, jsonString];
    // page url to request
    NSString *urlStr = @"http:api.example.com/v1/detail";
    // javascript to evalute
    NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", urlStr, postData];
    //NSLog(@"Javzascript: %@", jscript);
    

    Put this in the WKWebView's delegate: didFinishNavigation

    // call the javascript in step 3
    (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
         GCD_MAIN((^{
              [_web evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
                   if (error) {
                       NSLog(@"----------->>>>>>>>>>>>> evaluateJavaScript error : %@", [error localizedDescription]);
                   }
              }];
         }));
     }
    

提交回复
热议问题