How to detect URL schemes with .handlesExternalEvents and NSAppleEventManager simultaneously - swiftui

I have a SwiftUI-based Mac app with multiple WindowGroups.
1. Opening different SwiftUI WindowGroups using URL schemes
To open those windows I am using URL schemes (like described here):
WindowGroup {
// ...
}
.handlesExternalEvents(matching: Set(arrayLiteral: "primaryWindow"))
... and then calling:
NSWorkspace.shared.open(URL(string: "myapp://primaryWindow")!)
☑️ This works just fine!
2. Detecting URLs called from outside the app
I also need to be able to recognise and handle URL schemes called from outside the app, like myapp://somePath?someParameter=1. I found this solution and set an event handler within my AppDelegate:
func applicationWillFinishLaunching(_ notification: Notification) {
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleGetURL(event:reply:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) )
}
☑️ This works just fine, too, and my #selector method is called like you would expect.
3. Problem: How to use .handlesExternalEvents and .setEventHandler simultaneously?
🛑 Here’s where the problem starts: After calling .setEventHandler my WindowGroups no longer react on called URLs and I remain unable to open new windows.
That somehow makes sense since I’ve registered an event handler in AppDelegate specifically for kAEGetURL but I have no idea how to implement both features simultaneously. Looking forward for your advice!

Related

How do I fetch HomeKit values for usage in iOS 14 Widgets?

I am writing a HomeKit app that successfully shows live data from my supported accessories in-app. I can read single values (HMCharacteristic.readValue) or use notifications to stay updated (HMCharacteristic.enableNotification).
Now I want to implement Widgets that show this data on the user's Home Screen. This consists of four steps:
A dynamic Intent fetches all the registered (and supported) Accessories from the HMHomeManager and enables the user to select one of them to be shown on the Widget.
Inside the IntentTimelineProvider's getTimeline function I can then again use the HMHomeManager to retrieve the Accessory I want to display on the Widget (based on the Accessory's UUID which is stored inside the getTimeline's configuration parameter - the Intent).
Still inside the getTimeline function I can choose the Services and Characteristics I need for displaying the Accessory's Widget from the HMHomeManager.
Up until here everything works fine.
However, when I try to read the values from the Characteristics I chose before using HMCharacteristic.readValue, the callback contains an error stating
Error Domain=HMErrorDomain Code=80 "Missing entitlement for API."
The Widget's Info.plist contains the 'Privacy - HomeKit Usage Description' field and the Target has the HomeKit capability.
After some research I came up with the following theory: Obviously the whole WidgetKit API runs my code in background. And it seems like HomeKit does not allow access from a background context. Well, it does allow access to Homes/Services/Characteristics, but it does not allow reading or writing on Characteristics (I guess to make sure App developers use HomeKit Automations and don't try to implement custom automations that are controlled by some background process of their app running on the iPhone).
My (simplified) getTimeline code:
func getTimeline(for configuration: SelectAccessoryIntent, in context: Context, completion: #escaping (Timeline<Entry>) -> ()) {
// id stores the uuid of the accessory that was chosen by the user using the dynamic Intent
if let id = configuration.accessory?.identifier {
// Step 2.: fetch the accessory
// hm is a HMHomeManager
let hm = HomeStore.shared.homeManager
// take a short nap until the connection to the local HomeKit instance is established (otherwise hm.homes will create an empty array on first call)
sleep(1)
let accessories = hm.homes.flatMap({ h in h.accessories })
if let a = accessories.filter({ a in a.uniqueIdentifier.uuidString == id }).first {
// a holds our HMAccessory
// Step 3.: select the characteristic I want
// obviously the real code chooses a specific characteristic
let s: HMService = a.services.first!
let c: HMCharacteristic = s.characteristics.first!
// Step 4.: read the characteristic's value
c.readValue(completionHandler: {err in
if let error = err {
print(error)
} else {
print(c.value ?? "nil")
}
// complete with timeline
completion(Timeline(entries: [RenderAccessoryEntry(date: Date(), configuration: configuration, value: c.value)], policy: .atEnd))
})
}
}
}
}
My questions:
First: Is my theory correct?
If so: What can I do? Are there any entitlements that allow me to access HomeKit in background or similar? Do I need to perform the readValue call elsewhere? Or is it just impossible to use the HomeKit API with WidgetKit with the current versions of HomeKit/WidgetKit/iOS and best I can do is hope they introduce this capability at some point in the future?
If not: What am I missing?

ember-data 2.0 and Offline

I am creating a new ember app. I want to use the newest version of ember-data. (ember-data 2.0). I want it to be a mobile webapp. Therefore it must handle variable network access and even offline.
I want it to store all data locally and use that data when it goes offline so the user gets the same experience regardless of the network connectivity.
Is ember-data 2.0 capable of handling the offline case? Do I just make an adapter that detects offline/online and then do....?
Or do I have to make my own in-between layer to hide the offline handling from ember-data?
Are there any libraries out there that has this problem solved? I have found some, but are there any that is up to date with the latest version of ember-data?
If device will go offline and user will try to transition to route, for which model is not loaded yet, you will have an error. You need to handle these situations yourself. For example, you may create a nice page with error message and a refresh button. To do this, you need:
First, In application route, create error action (it will catch errors during model hook), and when error occurs, save transition in memory. Do not try to use local storage for this task, it will save only properties, while we need an actual transition object. Use either window.failedTransition or inject in controllers and routes a simple object, which will contain a failed transition.
actions: {
error: function (error, transition) {
transition.abort();
/**
* You need to correct this line, as you don't have memoryStorage
* injected. Use window.failedTransition, or create a simple
* storage, Iy's up to you.
*/
this.get('memoryStorage').set('failedTransition', transition);
return true; //This line is important, or the whole idea will not work
}
}
Second, Create an error controller and template. In error controller define an action, retry:
actions: {
retry: function () {
/**
* Correct this line too
*/
var transition = this.get('memoryStorage').getAndRemove('failedTransition');
if (transition !== undefined) {
transition.retry();
}
}
}
Finally, In error template display a status and an error text (if any available) and a button with that action to retry a transition.
This is a simple solution for simple case (device gone offline just for few seconds), maybe you will need something way more complex. If you want your application to fully work without a network access, than you may want to use local storage (there is an addon https://github.com/funkensturm/ember-local-storage) for all data and sync it with server from time to time (i.e sync data every 10 sec in background). Unfortunately I didn't try such things, but I think it is possible.

QT QWebEnginePage::setWebChannel() transport object

I'm using the QT WebEngine framework to display web pages. I'm injecting javascript into a page when it loads, and want to allow the javascript to be able to access a QT object. Apparently, to do this a QWebChannel must exist that establishes some IPC between chromium (the javascript) and the rest of my C++/QT project. I came across the QWebEnginePage::setWebChannel (QWebChannel *channel) function, however I can't find any examples of its use. The documentation (http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel) mentions that qt.webChannelTransport should be available in the javascript context, but I don't see where that is established in qwebchannel.js (https://github.com/qtproject/qtwebchannel/blob/dev/src/webchannel/qwebchannel.js). I've seen the WebChannel examples (http://doc.qt.io/qt-5/qtwebchannel-examples.html) and would like to avoid WebSockets if possible.
Below is how I tried to implement the web channel.
Whenever a page loads I establish a channel and inject the javascript in C++:
QWebChannel *channel = new QWebChannel();
channel->registerObject(QStringLiteral("jshelper"), helper);
view->page()->runJavaScript(qwebjs); //this is qwebchannel.js
view->page()->setWebChannel(channel);
view->page()->runJavaScript(myfunction); //function that calls QT object (jshelper)
In Javascript:
new QWebChannel(qt.webChannelTransport, function(channel) { ... });
Which results in the channel not being connected properly (assuming this is because of qt.webChannelTransport, as it was working when I was using WebSockets). Any pointers to examples of QWebChannel being set up with QWebEnginePage this way is also appreciated.
Short answer: add <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script> to your html page (before you call new QWebChannel of course), and remove the line view->page()->runJavaScript(qwebjs); //this is qwebchannel.js from your C++ code.
Long answer:
I too had a ton of trouble figuring out how to use QWebChannel without WebSockets correctly -- managed to get it working after digging around in Qt 5.5 source code and mailing lists (documentation is still lacking). Note that this only works with the new Qt 5.5.
Here's how to use QWebChannel:
// file: MyWebEngineView.cpp, MyWebEngineView extends QWebEngineView
QWebChannel *channel = new QWebChannel(page());
// set the web channel to be used by the page
// see http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel
page()->setWebChannel(channel);
// register QObjects to be exposed to JavaScript
channel->registerObject(QStringLiteral("jshelper"), helper);
// now you can call page()->runJavaScript(...) etc
// you DON'T need to call runJavaScript with qwebchannel.js, see the html file below
// load your page
load(url);
And on the JS side:
<!-- NOTE: this is what you're missing -->
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
<!-- it's a good idea to initialize webchannel after DOM ready, if your code is going to manipulate the DOM -->
document.addEventListener("DOMContentLoaded", function () {
new QWebChannel(qt.webChannelTransport, function (channel) {
var jshelper = channel.objects.jshelper;
// do what you gotta do
});
});
</script>
Also make sure you've added QT += webenginewidgets webchannel to your .pro file else this won't build!
Bonus: you can debug your JavaScript from the comfort of Chrome Dev Tools now! Just add this somewhere in your Qt code (ideally in your application startup):
#ifdef QT_DEBUG
qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "23654");
#endif
Then start your application, navigate to http://localhost:23654 in Chrome, and you'll get a fully-functional JS debugger, profiler, console, etc :)
Follow-up (19/04/2016): if your remote debugger isn't working, note that the qputenv call must also occur before any calls to QWebEngineSettings or any other WebEngine-related class, because these trigger the WebEngine "zygote" process immediately (the zygote is the parent QtWebEngineProcess from which all future QtWebEngineProcesses are forked) and then qputenv cannot affect it. Spent a few hours tracking this down.

Ember.js router events as functions not working

I have set up some basic routing in my app by using the examples at http://emberjs.com/guides/outlets/#toc_the-router
Within the root I have some events that trigger from view actions e.g:
gotoStepOne: Ember.Route.transitionTo('stepOne'),
gotoStepTwo: Ember.Route.transitionTo('stepTwo'),
gotoStepThree: Ember.Route.transitionTo('stepThree'),
gotoStepFour: Ember.Route.transitionTo('stepFour'),
gotoStepFive: Ember.Route.transitionTo('stepFive'),
Full example router code at http://jsfiddle.net/hellosmithy/WdjXT/
This all works fine at the moment. The problem is that I'd like to add other code into these events. For example:
gotoStepOne: function() {
if (someCondition) {
Ember.Route.transitionTo('stepOne');
}
someOtherFunction();
}
However doing this breaks the routing without throwing any errors. It just no longer transitions.
Specifically I only want transitions to happen if a certain state is met - something has been selected or input by the user at each stage before they can proceed. Is there a workaround for this, or should I be abstracting this functionality elsewhere?
The way I understand the router is, that it is the representation of the application's state.
Specifically I only want transitions to happen if a certain state is met - something has been selected or input by the user at each stage before they can proceed.
So the user inputting or selecting something puts your application in a certain state which is reflected by the router.
IMHO it should be something like this in a view (or controller):
userDidSomething: function(condition) {
if (condition) {
App.get('router').send('stepOne');
}else{
someOtherFunction();
}
}

How to get the document CDHtmlDialog after Asp.Net AJAX UpdatePanel

When the page displayed in our CDHtmlDialog does an Asp.Net AJAX UpdatePanel we get a navigate event, but everything after that seems to be lost. We don't have a document anymore or get any mouse events on the page.
Looks like I made the original post as an unregistered user, so I don't think I can edit it. We were able to work around the original issue, but it came up again in a different context (really starting to hate CDHTMLDialog).
Here is the cause of the problem:
Javascript calls are causing a Navigate event, and CDHtmlDialog::OnBeforeNavigate gets called and disconnects and deletes the IHTMLDocument2. Unfortunately it's not a true Navigate since the page never changed. This means CDHtmlDialog::OnNavigateComplete is never called to get the document back.
To make matters worse, when I override CDHtmlDialog::OnBeforeNavigate I find the URL string is unreadable (bug)?
The simplest (best?) solution:
We need to intercept the Before Navigate event, and only call the CDHtmlDialog's _OnBeforeNavigate2 if the URL isn't a javascript action:
BEGIN_EVENTSINK_MAP(CMyHTMLDlg, CDHtmlDialog)
ON_EVENT(CMyHTMLDlg, AFX_IDC_BROWSER, DISPID_BEFORENAVIGATE2, OnBeforeNavigate2, VTS_DISPATCH VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_PBOOL)
END_EVENTSINK_MAP()
void CMyHTMLDlg::OnBeforeNavigate2(LPDISPATCH pDisp, VARIANT* URL,VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData,VARIANT* Headers, BOOL* Cancel)
{
...
if (URL != NULL)
{
// Check if navigation is to a folder..
CString url = CString(*URL);
if(url.Left(11) != _T("javascript:"))
{
_OnBeforeNavigate2(pDisp, URL, Flags, TargetFrameName, PostData, Headers, (BOOL*)Cancel);
// If dynamic linking MFC then the above handler doesn't exist. Need to call OnBeforeNavigate direct.
// This is from a code site, and it compiles, but I've never tested it to see if it works.
//CDHtmlDialog::OnBeforeNavigate(pDisp,(LPCSTR)URL);
}
}
}
Most of this is pretty standard for setting up a CDHtmlDialog subclass, and it's pretty simple actually, but it took me a bit to figure out how to handle JavaScript. Unfortunately, I'm not sure how this will work if the JavaScript is making dynamic changes to the page itself.
A couple notes:
If the navigation needs to be completely canceled here, then set *Cancel = TRUE and don't call _OnBeforeNavigate2. Be careful here because this also cancels any JavaScript actions.
It wasn't clear until I saw the source, but CDHtmlDialog::_OnBeforeNavigate2 just calls CDHtmlDialog::OnBeforeNavigate.