iOS跟踪UIWebView中的URL更改并获取它返回的数据



我是iOS开发的新手,在任何地方都找不到有助于解决问题的答案。我正在制作一个应用程序,用户必须首先使用UIWebView登录。一旦用户登录,他们就会被带到应用程序,但在后台,服务器为每个用户传递了一个唯一的身份验证密钥。实例用户登录URL www.example.com/login。成功登录后,URL将更改为www.example.com/key/jsaeglihndzlaskn,最后一位是我需要获得的密钥。我有一个方法可以获取URL的最后一段,但它采用的是起始URL,而不是更改的URL。

    NSString *absoluteString= _webView.request.URL.absoluteString;
    NSArray* foo = [absoluteString componentsSeparatedByString: @"/"];
    NSUInteger arrsize = [foo count];//count the size of array
    NSString* bar = foo[arrsize-1];//get last element

任何帮助都将不胜感激

编辑

这就是我的代码现在的样子,但它仍然不能像我需要的那样工作,任何帮助都将不胜感激。

NSString *urlString = @"https://probablyrational.com/alpha/dashboard/register/?callback=inline";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[_webView loadRequest:urlRequest];

NSString* absoluteString = [url absoluteString];
NSArray* foo = [absoluteString componentsSeparatedByString: @"/"];//explode() .split()
NSUInteger arrsize = [foo count];//count the size of array
NSString* bar = foo[arrsize-1];//get last element
NSLog(@"bar %@", bar);
//bar = "?callback=inline"
if ([foo[arrsize-2] isEqualToString:@"key"]) {
    // user is authenticated
    NSLog(@"bar %@", bar);

- (BOOL)_webView:(UIWebView *)_webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *URLString = [[request URL] absoluteString];
    if ([URLString isEqualToString:@"https://probablyrational.com/alpha/key"]) {
        // The user reached step 3!
    }
    return YES;
}

编辑2

我的代码现在正在运行,但仍然没有跟踪URL更改。。

        NSString *urlString = @"https://probablyrational.com/alpha/dashboard/register/?callback=inline";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:urlRequest];

    NSString* absoluteString = [url absoluteString];
    NSArray* foo = [absoluteString componentsSeparatedByString: @"/"];//explode() .split()
    NSUInteger arrsize = [foo count];//count the size of array
    NSString* bar = foo[arrsize-1];//get last element
    NSLog(@"bar %@", bar);
    //bar = "?callback=inline"
    if ([foo[arrsize-2] isEqualToString:@"key"]) {
        // user is authenticated
        NSLog(@"bar %@", bar);
    }
}
- (BOOL)webView:(UIWebView *)webView didFinishLoading:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *absoluteString = [[request URL] query];
    if ([absoluteString isEqualToString:@"https://probablyrational.com/alpha/key"]) {
        // The user reached step 3!
    ( NSLog(@"this is  the code you're looking for"));
    return YES;
    }
    else
    {
        ( NSLog(@"this is  not code you're looking for"));
        return 0;
    }
}

任何我如何让它发挥作用的线索都将是救命的,我在这一点上陷入了

您可以使用[foo lastObject];以获取最后一个组件。

最新更新