ios - 使用 UIWebView 进行基本身份验证

标签 ios objective-c iphone swift basic-authentication

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

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

我不知道我的代码哪里出错了:

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
}

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

最佳答案

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

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)"
    }
} 

关于ios - 使用 UIWebView 进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069966/

相关文章:

iphone - 需要有关 iPhone 应用程序国际化的帮助

ios - Spotify 播放列表 ios sdk swift 问题

iphone - 关于 iAd 在 iPad 和 iPhone 上显示的问题

iphone - PhoneGap + iOS 防止默认滚动操作从输入文本字段开始

ios - 在 UIView 顶部添加阴影

ios - NSCache 持有指向用 imageWithData : and does not remove from memory on unload 实例化的 UIImage 的强指针

ios - 如何在单击按钮时隐藏/显示日期选择器?

iphone - 按下后退按钮时执行操作

ios - UITableView 自定义单元格在滚动时复制 UIButton

ios - iOS8 中 UITextField 默认的 borderColor 是什么?