【问题标题】:Basic authentication with UIWebView使用 UIWebView 进行基本身份验证
【发布时间】:2015-06-26 09:45:36
【问题描述】:

我在 SO 上阅读了很多关于如何应用基本身份验证的帖子。

我已经生成了这段代码,但它没有显示登录页面,只显示了一个白页。我使用的凭据在浏览器中工作,所以这不是问题。我的代表没事。

我不知道我的代码在哪里失败:

override func viewDidLoad() {
    super.viewDidLoad()
    webView.delegate = self
    self.loadPage()
}

func loadPage() {
    let url = "mypage.com/auht/Logon.do"
    let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 12)
    webView.loadRequest(request)
}

// MARK: NSURLConnectionDelegate Delegates

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
    if challenge.previousFailureCount == 0 {
        authenticated = true
        let credential = NSURLCredential(user: "m.rinaldi13", password: "299792,458km/s", persistence: NSURLCredentialPersistence.ForSession)
        challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
    } else {
        challenge.sender.cancelAuthenticationChallenge(challenge)
    }
}

// MARK: Web View Delegates

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if authenticated == nil {
        authenticated = false
        NSURLConnection(request: request, delegate: self)
        return false
    }
    return true
}

任何帮助/提示将不胜感激!

【问题讨论】:

    标签: ios objective-c iphone swift basic-authentication


    【解决方案1】:

    我自己找到解决方案,排除所有这些无聊的段落。

    func doRequestWithBasicAuth(completion : (success : Bool, html: String?, error : NSError?) -> Void) {
        if let user = self.user {
            let loginString = NSString(format: "%@:%@", user.login!, user.pwd!)
            let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
            let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
            let url = NSURL(string: user.service!.getURL())
            let request = NSMutableURLRequest(URL: url!)
            request.HTTPMethod = "POST"
            request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                if error == nil {
                    let htmlString = NSString(data: data, encoding: NSUTF8StringEncoding)
                    completion(success: true, html: htmlString as? String, error: nil)
                } else {
                    completion(success: false, html: nil, error: error)
                }
            }
        } else {
            completion(success: false, html: nil, error: NSError())
        }
    }
    

    那么你就可以这样在web view上均匀的显示页面了:

    self.doRequestWithBasicAuth({ (success, html, error) -> Void in
        if error == nil {
           self.webView.loadHTMLString(string: html, baseURL: <yourNSURL>)
        }
    })
    

    显然你可以(不得不)美化代码,比如为模型用户创建一个类:

    class User {
        var login: String?
        var pwd: String?
    
        func valueForHeaderFieldAuthorization() -> String {
            let loginString = NSString(format: "%@:%@", user.login!, user.pwd!)
            let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
            let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
            return "Basic \(base64LoginString)"
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2015-08-12
      • 2017-06-13
      • 2013-05-30
      • 2016-05-31
      • 2017-10-06
      • 2013-09-14
      • 2010-12-11
      • 2016-08-24
      • 2017-08-01
      相关资源
      最近更新 更多