Worklight initialization for Android always clears WebView history - ibm-mobilefirst

I noticed cordovaInitCallback is called each time Worklight/Cordova is initialized in an Android app. In particular, it calls Cordova's "clearHistory" to wipe out the WebView history. This has been an issue when I try to make use of window.history in a multi-page app since the history is always reset during the initializtion from page to page.
Since the comment suggests that the purpose for this clearHistory call is to prevent going back to an old page in a direct update scenario, could the condition be strengthened over an Android environment check so that it is only called if a direct update has just taken place? One case, for example, I can think of is when connectOnStartup=false, then direct update would not occur.
wlclient.js:
var cordovaInitCallback = function(returnedData) {
onEnvInit(options);
if (WL.Client.getEnvironment() == WL.Env.ANDROID) {
if (returnedData !== null && returnedData !== "") {
WL.StaticAppProps.APP_VERSION = returnedData;
}
// In development mode, the application has a settings
// widget in which the user may alter
// the application's root url
// and here the application reads this url, and replaces the
// static prop
// WL.StaticAppProps.WORKLIGHT_ROOT_URL
// __setWLServerAddress for iOS is called within
// wlgap.ios.js's wlCheckReachability
// function because it is an asynchronous call.
// Only in Android we should clear the history of the
// WebView, otherwise when user will
// press the back button after upgrade he will return to the
// html page before the upgrade
if (**WL.Env.ANDROID == getEnv()**) {
cordova.exec(null, null, 'Utils', 'clearHistory', []);
}
}
I am currently using Worklight 5.0.5, and have checked this same condition exists in 5.0.5.1.
Thanks!

The architectural design of Worklight is SPA (Single Page Application).
cordovaInitCallback should be called only once in the life cycle of the application.
That said, you can, if you wish, override it.

Related

Issue when model changes within AJAX call in ngx-admin

I downloaded the latest build of ngx-admin (https://github.com/akveo/ngx-admin), and served it up locally. In the ./#core/data/users.service.ts file I have added the following method
getHeroes (): Observable<any[]> {
return this.http.get<any[]>('http://localhost:63468/api/clubs/heroes');
}
That endpoint just returns some JSON like so:
[{"id":11,"name":"Mr. Nice"},{"id":12,"name":"Mr. Nice2"},{"id":13,"name":"Mr. Nice3"},{"id":14,"name":"Mr. Nice4"},{"id":15,"name":"Mr. Nice5"},{"id":16,"name":"Mr. Nice6"},{"id":17,"name":"Mr. Nice7"},{"id":18,"name":"Mr. Nice8"},{"id":19,"name":"Mr. Nice9"},{"id":20,"name":"Mr. Nice0"}]
In ./#theme/components/header/header.component.ts I have added a click handler method:
getHero() {
this.userService.getHeroes()
.subscribe(heroes => {
debugger;
this.hero = heroes[0]
});
}
In ./#theme/components/header/header.component.html I added a button and click event like:
<button (click)="getHero()">
add hero
</button>
{{hero?.name}}
I have done this to the same example project on Angular.io (https://angular.io/tutorial/toh-pt6).
The issue is:
In the ngx-admin application, once that debugger line is hit, the this.hero = heroes[0] is properly set with the data I expect. Once the execution leaves that line of code, the view is not updated. If I inject private ref: ChangeDetectorRef, and call this.ref.detectChanges(); immediately after this.hero = heroes[0], then the view is properly updated. However, in the angular.io example of heroes, the view is properly updated within the context of the subscribe call. In that application no this.ref.detectChanges(); is required.
Is there something in the ngx-admin project that is messing up the Angular change detection?

macOS Swift: How to properly add application as Login Item

I have spent about one day (maybe a little more) on trying to add my application to Login Item in the order it starts up at macOS launch (user login).
The first approach was the newest one; I check this tutorial on youtube:
https://www.youtube.com/watch?v=2mmWEHUgEBo&t=660s
So following this steps, I have done:
Add new project inside my main project that I have named Launcher
I am using Automatic Signing (as version of my Xcode) is different
In Project Settings > Capabilities I toggled App Sandbox to ON.
In Build Phases I have added this:
My Launcher has Skip Install = YES
Code in my Launcher app looks like this (I have even previously use Swift to do the same)
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
NSArray *pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
NSString *path = [NSString pathWithComponents:pathComponents];
[[NSWorkspace sharedWorkspace] launchApplication:path];
[NSApp terminate:nil];
}
Finally, I have magic code in Main App to enable app as Login Item
if(!SMLoginItemSetEnabled("click.remotely.Remotely-Click-Server-Launcher"
as CFString, Bool(checkboxButton.state as NSNumber) ) ) {
let alert: NSAlert = NSAlert()
alert.messageText = "Remotely.Click Server - Error";
alert.informativeText = "Application couldn't be added as
Login Item to macOS System Preferences > Users & Groups.";
alert.alertStyle = NSAlertStyle.warning;
alert.addButton(withTitle:"OK");
alert.runModal();
}
I have made Archive, and then have different options to Export:
I couldn't decide which one to choose, so I tried all of them.
"Save for Mac App Store Deployment" - made Installation package that has installed in /Applications/ directory but the app never runs.
"Developer-Id signed," "Development-signed" , "macOS App" all makes file in a directory that I exported to Applications directory, but no one works.
When I click the checkbox button, I could see some window blinking for a while on the screen (Launcher program). When I log out and log in the same window blinking effect appears but Launcher didn't start the Main application. When I click checkbox button again (and turn off Login Item) this blinking effect on user login (system startup) doesn't happen again. So it seems that this addition of Launcher program as Login Item works, but this Launcher couldn't start the Main app. Moreover when I go to /Applications/Main.app/Contents/Library/LoginItems/Launcher.app and click it manually then Launcher app launch Main application correctly (so the path was correct).
So what's going wrong?
Then I consider implementation of deprecated approach using
kLSSharedFileListSessionLoginItems
I have thought it must work it just add something in System Preferences this
window below.
But it also could go wrong!
I have chosen implementation in Swift (all examples/tutorials I have found was in Objective-C) So I have written something like this:
class LoginItemsList : NSObject {
let loginItemsList : LSSharedFileList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue();
func addLoginItem(_ path: CFURL) -> Bool {
if(getLoginItem(path) != nil) {
print("Login Item has already been added to the list.");
return true;
}
var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
print("Path adding to Login Item list is: ", path);
// add new Login Item at the end of Login Items list
if let loginItem = LSSharedFileListInsertItemURL(loginItemsList,
getLastLoginItemInList(),
nil, nil,
path,
nil, nil) {
print("Added login item is: ", loginItem);
return true;
}
return false;
}
func removeLoginItem(_ path: CFURL) -> Bool {
// remove Login Item from the Login Items list
if let oldLoginItem = getLoginItem(path) {
print("Old login item is: ", oldLoginItem);
if(LSSharedFileListItemRemove(loginItemsList, oldLoginItem) == noErr) {
return true;
}
return false;
}
print("Login Item for given path not found in the list.");
return true;
}
func getLoginItem(_ path : CFURL) -> LSSharedFileListItem! {
var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
// Copy all login items in the list
let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue();
var foundLoginItem : LSSharedFileListItem?;
var nextItemUrl : Unmanaged<CFURL>?;
// Iterate through login items to find one for given path
print("App URL: ", path);
for var i in (0..<loginItems.count) // CFArrayGetCount(loginItems)
{
var nextLoginItem : LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem; // CFArrayGetValueAtIndex(loginItems, i).;
if(LSSharedFileListItemResolve(nextLoginItem, 0, &nextItemUrl, nil) == noErr) {
print("Next login item URL: ", nextItemUrl!.takeUnretainedValue());
// compare searched item URL passed in argument with next item URL
if(nextItemUrl!.takeRetainedValue() == path) {
foundLoginItem = nextLoginItem;
}
}
}
return foundLoginItem;
}
func getLastLoginItemInList() -> LSSharedFileListItem! {
// Copy all login items in the list
let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue() as NSArray;
if(loginItems.count > 0) {
let lastLoginItem = loginItems.lastObject as! LSSharedFileListItem;
print("Last login item is: ", lastLoginItem);
return lastLoginItem
}
return kLSSharedFileListItemBeforeFirst.takeRetainedValue();
}
func isLoginItemInList(_ path : CFURL) -> Bool {
if(getLoginItem(path) != nil) {
return true;
}
return false;
}
static func appPath() -> CFURL {
return NSURL.fileURL(withPath: Bundle.main.bundlePath) as CFURL;
}
}
I have used this to turn on/off Login Item by clicking in the checkbox
let loginItemsList = LoginItemsList();
if( checkboxButton.state == 0) {
if(!loginItemsList.removeLoginItem(LoginItemsList.appPath())) {
print("Error while removing Login Item from the list.");
}
} else {
if(!loginItemsList.addLoginItem(LoginItemsList.appPath())) {
print("Error while adding Login Item to the list.");
}
}
I have run it in Debug mode (Xcode Play button) and try to archive it and export to /Applications folder if it matters, but this approach also doesn't work.
Console-printed messaged. Error means that the function Inserting Login Item returns nil.
So after that I even try to implement this (from some stackoverflow example) using Objective-C (as there is many Unmanaged<> in Swift)
So I added new .m and .h file and Bridging-Header.h and then a code like this:
- (void)enableLoginItemWithURL:(NSURL *)itemURL
{
LSSharedFileListRef loginListRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (loginListRef) {
// Insert the item at the bottom of Login Items list.
LSSharedFileListItemRef loginItemRef = LSSharedFileListInsertItemURL(loginListRef,
kLSSharedFileListItemLast,
NULL,
NULL,
(__bridge CFURLRef) itemURL,
NULL,
NULL);
if (loginItemRef) {
CFRelease(loginItemRef);
}
CFRelease(loginListRef);
}
}
Simple (just insertion) without any bells and whistles.
It also has the same issue that LSSharedFileListInsertItemURL returns nil and Login Item is not added to System Preferences > Users & Groups > Login Items.
So any idea why I cannot make this work?
UPDATE 1
I have tried to implement application using first approach (helper Launcher application inside Main application) on another computer iMac (MacOS Sierra and the newest XCode 8.3) and it seems to work there correctly so maybe there is something wrong with my OS or Xcode (provisioning profiles, signing of app or whatever) On MacBook Air where this approach doesn't work I am using OS X El Capitan 10.11.5 and Xcode 8.0.
Watch how it works here:
https://youtu.be/6fnLzkh5Rbs
and testing
https://www.youtube.com/watch?v=sUE7Estju0U
The second approach doesn't work also on my iMac returning the nil while doing LSSharedFileListInsertItemURL. So I don't know why that is happening.
Watch how it works here:
https://youtu.be/S_7ctQLkIuA
UPDATE 2
After upgrade to macOS Sierra 10.12.5 from El Capitan 10.11.5 and using Xcode 8.3.2 instead of Xcode 8.0.0 the second approach also happens to work correctly and is adding Login Items to System Preferences > Users & Groups > Login Items
IMPORTANT! To work this approach with LSSharedFileListInsertItemURL needs to disable App Sandboxing! Like in the video below:
https://youtu.be/UvDkby0t_WI
I also struggled with this a few years ago and ended up making a package for it that makes it much easier to add "launch at login" functionality for sandboxed apps.
Instead of lots of manual steps, you just need:
import LaunchAtLogin
LaunchAtLogin.isEnabled = true
Since macOS 13 Ventura, we can finally use a new SMAppService.
import ServiceManagement
try SMAppService.mainApp.register()
See SMAppService documentation for more details.
For the ServiceManagement approach, sometimes it doesn't work in your development machine because there is another copy of the app in your Xcode's DerivedData. The system don't know which app to launch. So go to ~/Library/Developer/Xcode/DerivedData and delete your development copy could help.
The above solution of Login Item programming problem works correctly both using modern approach with ServiceManagement.framework, and old (deprecated) approach with inserting Login Item into System Preferences > Users & Groups > Login Items. See my UPDATE 1 and UPDATE 2 remarks.
Dear Michal I have had the same problem about log in items. Log in items can be added in two ways; one from LSSharedFileListItemRef which will be shown in Login item of preferences but this approach will only work for non-sandboxing app and if you are making sandbox app then you should go for another way of using ServiceManagement framework.
You can have look over below link which specify everything - :
Launching your app on system start
I am adding another reference of adding app on log in - :
Approach for sandbox app with helper application
May be you are having trouble implementing app on log in item but follow the steps appropriately and you will succeed.

Handling Windows 8 lifecycle

i have run into a problem, that my app sometimes Activates and sometimes Launches when i open something via:
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = false;
bool success = await Windows.System.Launcher.LaunchFileAsync(sampleFile, options);
When app re-activates it shows the same window - when i went to an external app using LaunchFileAsync - this is nice.
But sometimes the app launches, i see a SplashPage and app is beginning from the MainPage. - how can i make this also to return to the page, that i left when used LaunchFileAsync?
Example:
I have a MainPage and a BlankPage1
So here is my page on suspend+shutdown (terminate) 8 buttons:
On Restore 0 buttons, I WANT TO SAVE MY VIEW XAML CODE when app gets killed by system:
It depends entirely on the conditions of your application shutdown. Was it suspended and terminated automatically by the OS ? or did you close it yourself ? (ex : ALT-F4)
You can see here the application lifecyle : http://msdn.microsoft.com/en-us/library/windows/apps/hh464925.aspx
If you want your application to restore its previous state on a user shutdown, I think you can enable it on your OnLaunched method in you App.xaml.cs :
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated
|| args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
{
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
}
}
Then, if your Page extends LayoutAwarePage, you have two methods, SaveState and LoadState.
These methods are called automatically when navigating from or to the frame (including suspending/restoring/opening...).
If you save your data behind your buttons in your SaveState method, you can restore it in the LoadState method (and thus redraw your buttons). There is a detailled exemple here : http://msdn.microsoft.com/en-us/library/windows/apps/hh986968.aspx

React to every app activation in Windows Store app

I have a Windows Store app with Live Tile updates using Background Task. When I activate the app by any means (click on the live tile, switch back to the app, etc..) I want to clear the live tile (I have a number there that I want to change to zero).
To be more concerete, I run the app, I switch to another app or desktop, then I switch ti the star screen and I see a number on the Live Tile. I click the Live Tile, I am taken to the app and I want the Live Tile to clear. The same functionality as the Email app.
I tried the OnActivated method in App.xaml.cs but it does not seem to get called at any time (I put a throw new NotImplementeExeption there and the app never crashes).
You should put it in the OnLaunched method, you just need to determine where.
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
var rootFrame = new Frame();
// Do not repeat app initialization when already running, just ensure that
// the window is active
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
{
//....
}
if (args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
{
/....
}
if (!String.IsNullOrEmpty(args.Arguments))
{
//....
}
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//....
}
if (args.PreviousExecutionState == ApplicationExecutionState.NotRunning)
{
//.....
}
TileUpdateManager.CreateTileUpdaterForApplication().Clear();
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
// Create a Frame to act navigation context and navigate to the first page
if (!rootFrame.Navigate(typeof(MainPage)))
{
throw new Exception("Failed to create initial page");
}
// Place the frame in the current Window and ensure that it is active
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
If you look at the code, there are several reasons of why your App is closed/suspended. So, determine in which cases you want to run de code for updating the number in the Live Tile, put it inside that if, and it should work.
I guess that the better place for such actions is the OnLaunched method. It called every time you appication start.
update: Hmm, seems you should react on both OnActivated and OnLaunched methods:
OnLaunched - Invoked when the application is launched. Override this
method to perform application initialization and to display initial
content in the associated Window.
On the application start OnLaunched will be called. But when you switch to another app and then go back OnActivated should be called:
OnActivated - Invoked when the application is activated by some means other than normal launching.

How to distinguish requests coming from LoadHtmlString from webpage requests in event ShouldStartLoad?

I have built offline functionality into my UIWebView so that pages that have been loaded are still available when the iPhone is put into airline mode. The basic algorithm is:
1) detect NavigationType LinkClicked and in this case load the requested page from the offline cache;
2) when the offline cache finishes loading the requested URL then it triggers the offlineRequestSuccess notification;
3) my webview handles this notification and loads the response string into the webview.
Here is my code for doing this:
public class UIMobileformsWebView : UIWebView
{
private UIMobileformsWebView () : base()
{
UIWebView self = this;
this.ShouldStartLoad = (webview, request, navigationType) => {
if (navigationType == UIWebViewNavigationType.LinkClicked) {
OfflineRequest.GetInstance().FetchUrl(request.URL);
return false;
}
return true;
};
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("offlineRequestSuccess"), new Action<NSNotification>(OfflineRequestSuccess));
}
void OfflineRequestSuccess (NSNotification notification)
{
ASIHTTPRequest theRequest = (ASIHTTPRequest)notification.Object;
String response = System.IO.File.ReadAllText(theRequest.DownloadDestinationPath);
this.LoadHtmlString(response, theRequest.URL);
}
}
For those that only know Objective C, you can see the same type of mechanism explained in the answer to this question:
Question about UIWebview when tapping links
This basic algorithm works well for most of my webpages, but has an issue with requests made from javascript rather than from clicking a link. If my javascript does window.location.href = URL then the navigation type that I see in the ShouldStartLoad event is type Other, not LinkClicked. Because of this, these requests do not get sent through to my offline cache. The requests coming through from LoadHtmlString also have navigation type of Other, so based on the navigation type I cannot distinguish the requests from LoadHtmlString and javascript requests in my page.
So basically, I am needing to change this line of code:
if (navigationType == UIWebViewNavigationType.LinkClicked) {
to something that beter distinguishes requests coming from my webpages and the request coming from LoadHtmlString in OfflineRequestSuccess. Anyone got any ideas how I could beter make this distinction?
You can easily distinguish these if you set a boolean property of the delegate to true when you use LoadHtmlString and reset it when you finished. The web view is not aware of the property and it won't set it to true. If it the property is YES, it must be because of a LoadHtmlString request.