Tushant Khatiwada
Tushant Khatiwada

Reputation: 43

Could not store value in safari browser localstorage using swift

I am using WebKit to store the email in the safari browser local storage. However, I am getting an error of

thread 3: Fatal error: Unexpectedly found nil while unwrapping an Optional value

One way to store value in localstorage is using UserDefaults but this way the value is not stored in safari local storage thus i used the below way

import SafariServices
import WebKit

class SafariExtensionViewController: SFSafariExtensionViewController {
    @IBOutlet weak var webView: WKWebView!
    static let shared = SafariExtensionViewController()
    override func viewDidLoad() {
        self.preferredContentSize = NSSize(width: 300, height: 250)
        message.stringValue = ""
        emailMessage.stringValue = ""
        passwordMessage.stringValue = ""
    }
    @IBAction func userLogin(_ sender: Any) {
     let providedEmailAddress = email.stringValue
      self.webView.evaluateJavaScript("localStorage.setItem(\"email\", \"value\")") { (result, error) in

         self.webView.reload()                           
     }
    }
}

my question is, how do i store the value in safari browser localstorage from swift so i can access that from javascript as well.

Upvotes: 0

Views: 1418

Answers (1)

ezaji
ezaji

Reputation: 304

You didn't connect webView outlet (that is marked as Implicitly Unwrapped Optional) from storyboard so you got this error.

You can use CoreData, UserDefaults, FileManager, even simple SQLite to store what you want.

EDIT:

A Safari app extension can read and modify your webpage content. Also it allows you to access data in your browser.

Complete the following steps to make Safari App Extension:

  1. Build a Safari App Extension
  2. Inject a script into a webpage
  3. Pass message between your Safari app extension and injected script

Upvotes: 1

Related Questions