In the next codelines i try to log into a moodle system via POST. This works quite well, if i leave the two lines commented, i can see the webpage after login. But when i try to navigate to the next webpage, which is in a protected area, I always get to see the login-page.

So my question is, how can i navigate to the protected page an display it in the webview?

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[defaults stringForKey:@"loginpage"]]];

    [request setHTTPMethod:@"POST"];

    NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",
                 [defaults stringForKey:@"username"],[defaults stringForKey:@"password"]];
    NSLog(@"Post is: %@",post);

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSLog(@"postData is: %@",postData);

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSLog(@"postLength is: %@",postLength);

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setHTTPBody:postData];

    NSLog(@"request is: %@", [request allHTTPHeaderFields]);


    [self.webview loadRequest:request];

    //if i do not comment the next two lines, the loginpage is displayed in the webview.
    //Otherwise the correct page with username after login is displayed.
    //request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[defaults stringForKey:@"displaypage"]]];

    //[self.webview loadRequest:request];

    NSLog(@"Done");
有帮助吗?

解决方案

The loadRequest method is asynchronous, meaning that when the method returns, it's very likely that it hasn't finished loading the first web page. So when you uncomment those two lines, probably the second request is being executed while the first one hasn't finished.

You should execute the second request in the UIWebViewDelegate's webViewDidFinishLoad: method.

其他提示

After setting the delegate in the storyboard, the following code did the job:

    -(void)webViewDidFinishLoad:(UIWebView *)webView {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[defaults stringForKey:@"displaypage"]]];
    [self.webview loadRequest:request];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top