在UIWebView中保存用户名/密码以进行自动登录

时间:2018-01-15 04:16:30

标签: ios swift xcode login uiwebview

我正在为一个网站开发一个简单的iOS应用程序。该应用程序使用UIWebView加载网站的登录页面。用户第一次加载页面时,需要登录。

我想存储用户名&密码,以便下次用户使用该应用程序时,它会自动登录。我在下面发布了我的代码。

import UIKit
import UserNotifications
import WebKit
import Foundation

class WebViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet weak var myWebView: UIWebView!
    var delegate = UIApplication.shared.delegate as! AppDelegate
    let baseURL = "http://g-order.id"
    var preferences = UserDefaults.standard
    var currentSubscribeKey:String = ""
    var currentStatusKey:String = ""

    //memanggil fungsi checking internet connection
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        currentSubscribeKey = delegate.currentSubscribeKey
        currentStatusKey = delegate.currentStatusKey


        if Reachability.isConnectedToNetwork() == true {

        } else {
            //let alertController = UIAlertController(title: "Tidak ada koneksi internet", message: "Cek koneksi internet anda..", preferredStyle: .alert)
            //let defaultAction = UIAlertAction(title: "Tutup", style: .default, handler: nil)
            //alertController.addAction(defaultAction)
            //present(alertController, animated: true, completion: nil)
        }
    }

    @IBAction func Produk(_ sender: Any) {
        let url = URL(string: "http://g-order.id")
        myWebView.loadRequest(URLRequest(url: url!))
    }

    @IBAction func Login(_ sender: Any) {
        let url = URL(string: "http://g-order.id/profile")
        myWebView.loadRequest(URLRequest(url: url!))
    }

    @IBAction func kembali(_ sender: Any) {
        myWebView.goBack()
    }

    @IBAction func buttonNotif(_ sender: Any) {
        //buat notifikasi kalo bisa ditaroh di function atau button
        let content = UNMutableNotificationContent()
        content.title = "udah mau habis waktunya"
        content.subtitle = "waktu"
        content.body = "the 5 second are ready"
        content.badge = 1

        //content cumik
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: NSNotification.Name(rawValue: "OpenLinkNotification"), object: nil)

        myWebView.delegate = self


        //nampilin web
        let url = URL(string: "\(baseURL)/login")
        myWebView.loadRequest(URLRequest(url: url!))

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    public func methodOfReceivedNotification(notification: NSNotification){
        let url = notification.object as! NSURL
        myWebView.loadRequest(URLRequest(url: url as URL))
    }

    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        let path = webView.request?.mainDocumentURL?.absoluteString
        switch path! {
        case "\(baseURL)/login":
            print("first time")
        case "\(baseURL)/home":
            let htmlString:String = webView.stringByEvaluatingJavaScript(from: "document.getElementById('user-email').innerHTML")!
            preferences.set("login", forKey: currentStatusKey)
            preferences.set(htmlString, forKey: currentSubscribeKey)
            delegate.pusher.nativePusher.subscribe(interestName: htmlString)
            print(htmlString)
            preferences.synchronize()

        default:
            print("others")
        }
    }


    func webView(_ webView: UIWebView,
                 shouldStartLoadWith request: URLRequest,
                 navigationType: UIWebViewNavigationType) -> Bool {
        let path = request.url!.absoluteString
        if (path == "\(baseURL)/logout") {
            if (preferences.object(forKey: currentStatusKey) != nil) {
                let currentStatus = preferences.object(forKey: currentStatusKey) as? String ?? ""
                if (currentStatus == "login") {
                    preferences.set("logout", forKey: currentStatusKey)
                    preferences.synchronize()
                }
            }
        }
        return true
    }


}

0 个答案:

没有答案