Could not store value in safari browser localstorage using swift - 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.

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:
Build a Safari App Extension
Inject a script into a webpage
Pass message between your Safari app extension and injected script

Related

Embed web inside Mac executable

I need to embed a web inside a MAC executable, so that the html is inside the executable (and not loaded from an external server). It should also be possible to print the contents of the webview.
I have tried with Xcode and Swift, but when printing the webview it looks blank, there are lots of entries in Stack Overflow and seems to be no solution for this in swift.
I have also tried Xojo.com, but the contents are outside the executable visible to the user and must be hidden inside.
Any guidance?
CODE:
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var WEBVW: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let url = Bundle.main.url ( forResource: "index"
, withExtension: "html"
, subdirectory: "www")
{
let path = url.deletingLastPathComponent();
self.WEBVW.loadFileURL ( url
, allowingReadAccessTo: path);
WEBVW.printView(self)
}
}
}
IMAGE: Program running and printing: https://postimg.cc/Lqsddv1T
Many thanks

Configuring Interface Builder's new WKWebView object

As some of you may have noticed, Apple recently implemented the WKWebView (from WebKit) as an object in the Interface Builder; however, I am having difficulty with properly implementing it. I am still able to implement it by code, but implementing it via the Interface Builder has proven to be a bit of a pain.
The WKWebView appears blank on launch, and although the NSTextField appears to work when configured, the WKWebView continues to remain blank and doesn't even call upon didStartProvisionalNavigation, didCommit or didFinish when implemented (whereas, when done programatically, this continues to work).
Interface Builder Screenshot
Interface Builder Menu Options
Note: I did attempt to implement it using the WebConfiguration as well, but no luck either. Now I'm just trying to keep the code as simplistic as possible to get a better understanding as to why this is not working.
ViewController.swift
import Cocoa
import WebKit
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// Configure Window Appearance
window!.titlebarAppearsTransparent = true
window!.isMovableByWindowBackground = true
window!.title = ""
window!.backgroundColor = NSColor.white
}
}
class ViewController: NSViewController, WKUIDelegate, WKNavigationDelegate {
let myURL = "https://google.com"
#IBOutlet var webView: WKWebView!
#IBOutlet var pageTitle: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Load Homepage URL in WebView
webView.load(URLRequest(url: URL(string: myURL)!))
}
}
So as it turns out, the WKWebView refuses to become active while there is an entitlements file in your project. In my case, I had the App Sandbox enabled with the following settings:
com.apple.security.network.server – YES
com.apple.security.files.user-selected.read-write – YES
Once deleting the entitlements file and removing it entirely from the project, the WKWebView began to work again.

Deep link into macOS app is not recognized

I'm trying to implement a deep link into an macOS application, but nothing seems to work.
So far, my AppDelegate.swift contains the following
func application(app: NSApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
print("opened by link");
return true
}
I also configured the info.plist with URLSchemes beeing my bundle identifier and URLIdentifier beeing simply zst
In a simple html-file I use the following code to test the deep link
Test
My app gets opened (or becomes active when already running), but the print statement is not executed.
What am I doing wrong here?
Thanks to #Ssswift I found a solution.
Used this code:
How do you set your Cocoa application as the default web browser?
and converted it to swift with: https://objectivec2swift.com
works with Swift 3
in AppDelegate.swift added these lines
func applicationDidFinishLaunching(_ aNotification: Notification) {
var em = NSAppleEventManager.shared()
em.setEventHandler(self, andSelector: #selector(self.getUrl(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func getUrl(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
// Get the URL
var urlStr: String = event.paramDescriptor(forKeyword: keyDirectObject)!.stringValue!
print(urlStr);
}

Loading HTML into Webview from a string, OS X

I would like to create some formatted text using HTML in my OS X program. I am programing in swift. I created a web view and set up a simple test.
import Cocoa
import RealmSwift
import WebKit
class invociegenerator: NSViewController {
#IBOutlet var InvoiceView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
var htmlString:String! = "<br /><h2>Hello World!!</h2>"
InvoiceView.loadHTMLString(htmlString, baseURL: nil)
// Do view setup here.
}
}
I receive an error saying "WebView does not have a member named 'LoadHTMLString'" I must be missing something, is it possible to load from a string in an OS X program? There are plenty of tutorials online but the all focus on iOS.
"loadHTMLString" is a method on a WebFrame object not WebView. However, Webview does have a method that returns the mainFrame for the webview. So you could just call mainFrame on the webview like this.
InvoiceView.mainFrame.loadHTMLString(htmlString, baseURL: nil)

Handle browser's Notification in Swift webview application

I have very little knowledge about Swift, xCode or Objective-C but I have read/watch a lot of tutorials and my only intention is to create a webview with notification in webkit wrapper such as this Cocoa application provided by xCode.
Currently I have my code that can pretty much run when I build it.
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://irccloud.com"
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
}
override func webView(sender: WebView!, runJavaScriptAlertPanelWithMessage message: String!, initiatedByFrame frame: WebFrame!) {
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Now, if I access irccloud url directly I'm able to receive both sound and banner notification, but I'm wondering how can I make this notification able to display like native Mac app written in Swift?
This app able to do that, but it's in Objective-C https://github.com/jnordberg/irccloudapp