2013-10-13 48 views
2

我正在構建一個小的REST服務來授權用戶進入我的應用程序。如何從URL中去除查詢(用於GET參數)?

在某一點上,我用來授權用戶的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字符串相關的方法:

- (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總是完整的URL與GET參數和relativeString始終是零。

我抓着我的頭,我似乎無法找到解決方案。任何幫助將不勝感激。

回答

10

不是說說你自己的字符串處理得一塌糊塗,移交給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帶給達到同樣的效果。

5

例子: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]; 
+1

謝謝。爲了好奇,我最終重建了這樣的字符串:'NSString * basicPathString = [NSString stringWithFormat:@「%@://%@:%@%@」,requestUrl.scheme,requestUrl.host,requestUrl.port, requestUrl.path];' –

+0

感謝您爲我帶來'NSURLComponents'! –

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]; 

另外請注意,沒有「片段」屬性。這只是'片段'。

否則,這種方法很好。比擔心使用字符串manip正確地重新組織URL要好得多。