2

我正在构建一个小型 REST 服务来授权用户进入我的应用程序。

在某一时刻,我用来授权用户的 UIWebView 将转到https://myautholink.com/login.php。此页面发送带有授权令牌的 JSON 响应。关于这个页面的事情是它通过我的授权表通过 GET 接收一些数据。我无法使用 PHP 会话,因为您通过以下方式到达此页面:

header("location:https://myautholink.com/login.php?user_id=1&machine_id=machine_id&machine_name=machine_name&app_id=app_id");

由于标头函数发送标头,我不能同时做session_start();

我可以使用委托方法毫无问题地获取 UIWebView 的请求 URL:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSURLRequest *request = [webView request];
    NSLog(@"%@", [[request URL] relativeString]);
    if([[[request URL] absoluteString] isEqualToString:SPAtajosLoginLink])
    {
        //Store auth token and dismiss auth web view.
    }
}

问题是没有一个 NSURL 方法似乎返回没有参数的“干净”链接。我查看了所有与 NSURL url-string 相关的方法:

- (NSString *)absoluteString;
- (NSString *)relativeString; // The relative portion of a URL.  If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString

但是 absoluteString 始终是带有 GET 参数的完整 URL,而 relativeString 始终是 nil。

我为此挠头,似乎找不到解决方案。任何帮助将不胜感激。

4

3 回答 3

11

与其搞乱你自己的字符串操作,不如交给NSURLComponents

NSURLComponents *components = [NSURLComponents componentsWithURL:url];
components.query = nil;     // remove the query
components.fragments = nil; // probably want to strip this too for good measure
url = [components URL];

在 iOS 6 及更早版本上,您可以引入KSURLComponents以实现相同的结果。

于 2013-10-21T09:53:14.087 回答
6

示例:http ://www.google.com:80/a/b/c;params?m=n&o=p#fragment

使用 NSURL 的这些方法:

         scheme: http
           host: www.google.com
           port: 80
           path: /a/b/c
   relativePath: /a/b/c
parameterString: params
          query: m=n&o=p
       fragment: fragment

或者,在 iOS 7 中,构建一个 NSURLComponents 实例,然后使用方法方案、用户、密码、主机、端口、路径、查询、片段,将部分 URL 提取为字符串。然后重新构建基本 URL。

NSString* baseURLString = [NSString stringWithFormat:@"%@://%@/%@", URL.scheme, ...
NSURL *baseURL = [NSURL URLWithString:baseURLString];
于 2013-10-13T20:23:17.240 回答
5

要为 iOS 7 及更高版本更新此答案:

NSURLComponents *components = [NSURLComponents componentsWithURL: url resolvingAgainstBaseURL: NO];
components.query = nil;     // remove the query
components.fragment = nil; // probably want to strip this too for good measure
url = [components URL];

另请注意,没有“片段”属性。这只是“片段”。

否则,这个方法很棒。比担心将 URL 与字符串操作正确地重新组合在一起要好得多。

于 2016-05-10T00:15:20.807 回答