2015-02-10 108 views
0

我是Swift的新手。在用戶授權我的應用程序使用其帳戶後,我需要獲取重定向URL的幫助。重定向URL包含我將交換令牌的auth_code。如何在Swift中捕獲重定向URL(在OAuth2的授權步驟之後)

我在圈子裏試圖用NSURLSessionDataDelegate紡:

class MySessionDelegate: NSObject, NSURLSessionDataDelegate { 
    func URLSession(_: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection: NSHTTPURLResponse, newRequest: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) { 
     println(newRequest) 
     println("hello") 
    } 
} 

,但它不被稱爲:

var authUrl = NSURL(string: "https://www.linkedin.com/uas/oauth2/authorization?response_type=\(responseType)" + 
      "&client_id=\(apiKey)" + 
      "&state=\(randomState)" + 
      "&redirect_uri=\(redirectUrl)") 

var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: MySessionDelegate(), delegateQueue: nil) 
var request = NSMutableURLRequest(URL: authUrl!) 

myWebView.loadRequest(request) 

我加入一個NSURLProtocol打印請求(我可以看到在控制檯中重定向URL),但這適用於會話中不是最佳的所有請求:

var requestCount = 0 

class urlProtocol: NSURLProtocol { 
override class func canInitWithRequest(request: NSURLRequest) -> Bool { 
    println("Request #\(requestCount++): URL = \(request.URL.absoluteString)") 
    return false 
    } 
} 

提前致謝。

回答

0

如果你真的在你的URLSession上運行任務,你的方法可以在UIWebView之外工作。使用UIWebView,您並未使用(至少是直接使用)URLSession API。就像你用NSURLProtocol所說的那樣,你會捕獲每一個通過網絡的請求。

UIWebView有一個您可能可以使用的委託。你必須確保你是viewController是UIWebView的委託,然後從UIWebViewDelegate協議實現這個方法。

optional func webView(webView: UIWebView, 
         shouldStartLoadWithRequest request: NSURLRequest, 
         navigationType: UIWebViewNavigationType) -> Bool 

{ 
    return true 
} 

請求將有網址在裏面,但導航類型將有UIWebViewNavigation.Other。您可以決定返回true還是false,具體取決於您是否希望webView實際加載請求。在典型的重定向場景中,您會看到您使用myWebView.loadRequest(request)創建的第一個請求。如果用戶點擊鏈接或與頁面交互,則可能會看到其他請求,但其導航類型不是UIWebViewNavigationType.Other,而是.LinkClicked.FormSubmitted