Why isn't my WKWebView resizing properly inside my subview? - swift

I am creating a minimal WebKit browser for a Mac OS App using the following Swift code to load the new WKWebView into an Custom View Object.
When I run the App the web page loads correctly and fills the window, however if the window is resized the subview does not resize with the window.
Any Help would be most appreciated.
import Cocoa
import WebKit
import AppKit
#NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var customView: NSView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
var url = NSURL(string:"http://www.google.com/")
var request = NSURLRequest(URL:url!)
var theWebView:WKWebView = WKWebView(frame: customView.bounds)
self.customView.autoresizingMask = NSAutoresizingMaskOptions.ViewWidthSizable | NSAutoresizingMaskOptions.ViewHeightSizable
self.customView.addSubview(theWebView)
theWebView.loadRequest(request)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}

Related

Can't see anything in Web.load(URLRequest(url: URL(string: "https://google.com")!))

I am trying to make a macOS app using Xcode 12.4 , that opens webpages. When I try to use Web.load(URLRequest(url: URL(string: "https://google.com")!)) , I see an empty window.
I use a WKWebView in Main.storyboard
Here is the ViewController.swift code:
import Cocoa
import WebKit
let webView = WKWebView()
class ViewController: NSViewController {
#IBOutlet weak var Search: NSSearchField!
#IBOutlet weak var Web: WKWebView!
var web: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
Web.load(URLRequest(url: URL(string: "https://google.com")!))
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
I just found the simplest solution to this problem: remove the App Sandbox! More information about this here: https://developer.apple.com/forums/thread/92265

Mac OSX app not loading URL in Webkit View

I am trying to load a URL inside a Webkit View in a Mac OX app using Swift.
This is how my code looks like right now:
import Cocoa
import AppKit
import Foundation
import CoreData
import WebKit
class ViewController: NSViewController, WKUIDelegate {
#IBOutlet weak var rightBox: NSView!
#IBOutlet weak var leftBox: NSView!
#IBOutlet var myWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
// Do any additional setup after loading the view.
}
override func viewWillAppear() {
leftBox.layer?.backgroundColor = NSColor.blue.cgColor
rightBox.layer?.backgroundColor = NSColor.red.cgColor
let myURL = URL(string: "https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
myWebView.load(myRequest)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
When I run the code, I only see blank white box.
I have tried placing the url loading code both in the viewDidLoad as well as viewWillAppear. Same result.
I am trying to figure out what I might be doing wrong.
Any suggestions?
Thanks
Have you enabled outgoing connections for your application?
Had it been an http:// URL you'd also have to turn on NSAllowsArbitraryLoads in your Info.plist.

Parse PFUser not registering subclass

I am trying to use Parse PFUser in a software for OSX desktop. When I try to use it PFUser.query() it gives a message: Failed to set (contentViewController) user defined inspected property on (NSWindow): The class PFUser must be registered with registerSubclass before using Parse.
It is happening without registering the class.
I tried it registering the class this way: PFUser.registerSubclass() but it still doesn't work.
I will use the default PFUser without adding any fields to it, so I don't need to create a custom class to be my PFUser.
I tried to use PFUser.enableAutomaticUser() without success
Code below:
AppDelegate.swift
import Cocoa
import Parse
import Bolts
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let APP_ID = "app_id"
let CLIENT_KEY = "client_key"
let SERVER = "https://parseserver.com/"
func applicationDidFinishLaunching(_ aNotification: Notification) {
PFUser.registerSubclass()
let configuracaoParse = ParseClientConfiguration {
$0.applicationId = self.APP_ID
$0.clientKey = self.CLIENT_KEY
$0.server = self.SERVER
}
Parse.initialize(with: configuracaoParse)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
ViewController.swift
import Cocoa
import Parse
class ViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var senhaSecureTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
contaUsuarios()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func entrarButtonClicked(_ sender: NSButton) {
}
func contaUsuarios() {
let query = PFUser.query()
query?.countObjectsInBackground(block: {
(count, error) -> Void in
let numeroUsers = Int(UInt32(count))
if numeroUsers > 0 {
}
print(numeroUsers)
})
}
}
Reading some content on the internet I discovered that in OSX the ViewController is launched before the AppDelegate finishes loading, so I initialized the Parse connection and subclassing in the ViewController's viewDidLoad instead of AppDelegate and it is working just fine.

MASShortcut no such module

I've been try use MASShortcut and following the instructions there I've added it using cocoapods. I then added it to my <proj>-Bridging-Header.h file and imported it in my main swift file but I keep getting the error
No such module 'MASShortcut'
Here's my setup:
AppDelegate.swift:
import Cocoa
import Carbon
import MASShortcut
var kShortCut: MASShortcut!
#IBOutlet weak var shortcutView: MASShortcutView!
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
override func awakeFromNib() {
... omitted ...
}
override func viewDidLoad() {
super.viewDidLoad()
shortcutView.shortcutValueChange = { (sender) in
let callback: (() -> Void)!
if self.shortcutView.shortcutValue.keyCodeStringForKeyEquivalent == "k" {
self.kShortCut = self.shortcutView.shortcutValue
callback = {
print("K shortcut handler")
}
} else {
callback = {
print("Default handler")
}
}
MASShortcutMonitor.sharedMonitor().registerShortcut(self.shortcutView.shortcutValue, withAction: callback)
and my Podfile:
target 'myapp' do
# Comment this line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'MASShortcut', '~> 2'
# Pods for myapp
target 'myappTests' do
inherit! :search_paths
# Pods for testing
end
end
and finally proj-Bridging-Header.h:
#import <Cocoa/Cocoa.h>
#import <MASShortcut/Shortcut.h>
Here's what the AppDelegate should sort of look like. Note the absense of any import MASShorcut.
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var kShortCut: MASShortcut!
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var shortcutView: MASShortcutView!
override func awakeFromNib() {
shortcutView.shortcutValueChange = { (sender) in
let callback: (() -> Void)!
if self.shortcutView.shortcutValue.keyCodeStringForKeyEquivalent == "k" {
self.kShortCut = self.shortcutView.shortcutValue
callback = {
print("K shortcut handler")
}
} else {
callback = {
print("Default handler")
}
}
MASShortcutMonitor.shared().register(self.shortcutView.shortcutValue, withAction: callback)
}
}
}
The bridging header should look like this:
#ifndef Testin_Bridging_Header_h
#define Testin_Bridging_Header_h
#import <MASShortcut/Shortcut.h>
#endif /* Testin_Bridging_Header_h */
Shortcut.h imports all the other header files. Testin was the name of my app (to test of course)
Some other tips:
Make sure you set the bridging header in your application's build settings.
Try building from the MASShortcut scheme if it doesn't build the framework initially.
The AppDelegate doesn't have lifecycle events, you need to use either NSViewController or NSWindowController subclasses to use lifecycle methods (ie viewDidLoad).

Nil value when referring to IBOutlets - swift, Cocoa

I am having an issue where my NSTextField IBOutlets are showing up as nil, even though they are connected to the storyboard. In the simplified example below, I have a button that, when pressed, should list the string value of the 3 text labels.
Here is the code for the button:
import Foundation
import Cocoa
class ViewController: NSObject{
#IBAction func pushButton(sender: AnyObject) {
let oneText = Texts()
oneText.listTextFields()
}
}
Here is the code for the NSTextField list:
import Foundation
import Cocoa
class Texts: NSObject{
#IBOutlet weak var l1: NSTextField!
#IBOutlet weak var l2: NSTextField!
#IBOutlet weak var l3: NSTextField!
var textArray = [NSTextField]()
func listTextFields (){
self.textArray = [self.l1,self.l2,self.l3]
for var i = 0; i < textArray.count; i++ {
let text = textArray[i]
print(text.stringValue)
}
}
}
I have verified that the IBOutlets are all connected, but I get a "fatal error: unexpectedly found nil while unwrapping an Optional value" message when I run the program and press the button. Looking at the debugger, it appears that the tree NSTextfields are "nil."
What am I doing wrong?
You're not loading Texts from your storyboard, so it knows nothing about your outlets. Texts() creates a new instance of the object, which you then call the method on.
You presumably have an existing Texts object somewhere in interface builder, ViewController should have an outlet to that.