NSURLSession background configuration benefits on macOS - macos

On iOS it’s critical to init a NSURLSession with a background configuration to get the benefit of uploading and downloading while the app is background:
Example in Swift 2:
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("SomeSessionName");
NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil);
On OSX 10.10+, is there any benefit to using a background session configuration with the intention to continually upload or download even when the app is not currently in focus? In my experience, a default session configuration is far less vulnerable to bugs:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration();
NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil);

On OS X, background download tasks continue to run even after the user quits the app (as long as the user doesn't force-quit the app, IIRC). Unlike iOS, it doesn't relaunch your app in the background when the download finishes; your app will instead find out that the download finished after the user manually relaunches the app and your app reassociates itself with the existing named background sessions.
So the most common reason for using them on OS X would be for things like games that download large data sets. You could kick off the download in the background and let the user continue playing the game (without the expanded levels or whatever), and the download would continue even if the user quits the game, but the next time the user runs the game, the download would be available for installation.
That said, it is significantly less critical on OS X, because you have the option of forking a child process that keeps running and downloading.

Related

Location Service is not running in ios and android background for Xamarin

I am developing an app in Xamarin Forms which will show thing live position of the user on a map and all the users having the app can track other users movement.
Right now the app is working fine in android. But in the iOS foreground, android background it stops after some time. It is not at all running in ios background when I put the app in the background it stops showing the location and stops fully.
Please share some idea to keep the app live in background and foreground mode for the whole day.
Generally speaking, mobile OSs will stop your apps, when they are in the background for some time. How strict the OSs are depends on the OS and the version. iOS has "always" been very strict about it, Android has been a bit more loose in older versions, but is quite restrictive in newer versions. Anyway, getting the location in background is quite a common use case and OSs are providing you options to do it nevertheless, if you ask them politely.
iOS
As of iOS 11, there is a distinction between updating the location when in use and when in background. The user can choose which one to grant and you'll have to handle it appropriately.
According to this guide you'll have to add the NSLocationAlways key to your Info.plist to contimue getting the location when in background.
Android
From the Android developer guide
In an effort to reduce power consumption, Android 8.0 (API level 26) limits how frequently background apps can retrieve the user's current location. Apps can receive location updates only a few times each hour.
Anyway
The system distinguishes between foreground and background apps.
An app is considered to be in the foreground if any of the following is true:
It has a visible activity, whether the activity is started or paused.
It has a foreground service.
...
According to this, you can create a foreground service, see here more about it
For this reason, foreground services must show a status bar notification with a priority of PRIORITY_LOW or higher, which helps ensure that the user is aware of what your app is doing.
So if you are starting a foreground service that is shown in notification bar, you should be able to retrieve updates, even if your apps main Activity is not in foreground.

Can I keep a Watch app running in background?

I know iOS allows background tasks to run and, for example, continue to receive location updates, but is it possible to do this in a watch app?
In Xcode 9.3, I have configured my app for "background modes" and selected location, and that has created for the WatchKitExtension's an Info.plist, an entry for "Required background modes" of "App registers for location updates".
But my watch app still suspends when the screen turns off, and when it is in the dock.
The App Programming Guide for watchOS, however seems to exclude the possibility of running in the background to receive location updates as it only allows background processing for four classes of activity:
Background App Refresh Tasks. Use a WKApplicationRefreshBackgroundTask object to ...
Background Snapshot Refresh Tasks. Use a WKSnapshotRefreshBackgroundTask object to update ...
Background Watch Connectivity Tasks. Use a WKWatchConnectivityRefreshBackgroundTask object to receive data sent by your iOS app ...
Background NSURLSession Tasks. ...
Other posts to SO indicate it's not possible, but proving a negative is difficult, so I'm asking again:
Am I "flogging a dead horse" by trying to keep the watch App operating in the background for receiving location updates, or is Xcode is making promises that WatchOS won't deliver.
I'm delighted to be able to report that the horse I have been flogging for the past two weeks was not dead after all!
I have discovered an additional state in which my watch app will continue to run in the Background which does not require HKWorkoutSession.
These settings did the trick:
locationManager.allowsBackgroundLocationUpdates = true
and in watchKitExtension info.plist:
set UIBackgroundModes (Required background modes) to location (App registers for location updates)
And I repeat: I am NOT using healthKit
Now my app continues to run even when the screen is off and when the app is out of the Dock.
No, it is not possible.
As the WatchKit Programming Guide clearly states, WatchKit apps cannot use background execution except for 3 use cases:
Network operations using URLSession
Playing audio using WKAudioFilePlayer or WKAudioFileQueuePlayer
Run a workout using HKWorkoutSession
You cannot receive location updates in the background, according to the WatchKit Programming Guide, that should be done in the iOS app that is connected to your watchOS application.

OS X: Launching app from dock is a no-op if app is already running headless (via NSApplicationActivationPolicyProhibited)

My app can run with a UI and run headless, chosen via a command-line argument. (I don't want to build two separate apps.) When running headless, I'm calling:
[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
during app initialization, and don't show any windows.
This all works fine, and I can run the app headed (via the dock) and headless (via another app passing the command-line argument) at the same time. The little dot shows up next to the dock icon only for the headed app. Good. The problem happens if the headless app is launched first. In that state (no dot in the dock), any clicking on the app icon (or launching via Spotlight or the Finder) does nothing, or sometimes brings up "You can’t open the application “Foo” because it is not responding." Presumably the OS thinks the app is already running headed, and is trying to activate it. Is there a way to convince it to ignore that background app and launch a new instance?
Quitting the background app allows the app to launch normally again from the dock.
I don't want to set LSBackgroundOnly in the plist, because that would require two separate apps unless I changed the setActivationPolicy to NSApplicationActivationPolicyRegular in the case of the headed app. But I've read that doing that causes various other bugs, like the menu bar not always showing up.
Any ideas?
I'm on OS 10.10.5 (the oldest OS I need to support). Thanks for any help!
Update: I just noticed that when clicking on the dock and it appears to do nothing, if there are no app windows open I can see that it actually unhides my app's main window (which was created hidden) but doesn't bring it to the front (presumably it notices that NSApplicationActivationPolicyProhibited is set, though that wasn't enough to prevent it from showing the window!).
Update 2: At this point, I'd settle for a way to notify the user that the reason the app isn't launching is that they need to quit the other app that has sublaunched the headless process. Of course this code would need to be in the headless app, since the headed doesn't even launch.
It looks like you can call setActivationPolicy from applicationShouldHandleReopen and set the policy back to NSApplicationActivationPolicyRegular at that time. I made a test app with the following code and it seems to behave as you describe you would like it to above (although I've only run it on 10.11.5):
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
if NSUserDefaults.standardUserDefaults().stringForKey("background") == "true" {
NSApp.setActivationPolicy(.Prohibited)
print("launched in background")
}
}
func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
NSApp.setActivationPolicy(.Regular)
return true
}
}

Close other applications using swift

Is there a way to close running applications in swift? For instance, if the application I create needs to close safari.
Here's a Swift 5 version for closing running applications without using AppleScript (AppleScript is a perfect way but it isn't the only way), Safari is used as the example in this case:
let runningApplications = NSWorkspace.shared.runningApplications
if let safari = runningApplications.first(where: { (application) in
return application.bundleIdentifier == "com.apple.Safari" && application.bundleURL == URL(fileURLWithPath: NSWorkspace.shared.fullPath(forApplication: "Safari")!)
}) {
// option 1
safari.terminate()
// option 2
kill(safari.processIdentifier, SIGTERM)
}
SIGTERM instead of SIGKILL, referencing from here
Of course, make sure you notify the user of this activity since this may cause negative impact on the user-experience (for example, user-generated contents in the targeted application are not saved before terminating)
It is certainly possible via an applescript directly IF:
your app is not running sandboxed (note that if you plan to distribute it via the App Store, your app will be sandboxed)
OR
your app has the necessary entitlements to use applescript: com.apple.security.scripting-targets (apple needs to approve that AND you need to know which apps to target. this isn't a blanket permission)
then
https://apple.stackexchange.com/questions/60401/how-do-i-create-an-applescript-that-will-quit-an-application-at-a-specific-time
Can you execute an Applescript script from a Swift Application
if you aren't going for App Store complicity anyways, you might also use NSTask directly
scripts / code snippets:
How to force kill another application in cocoa Mac OS X 10.5
Can you execute an Applescript script from a Swift Application
short & sweet: technically yes, 'politically' maybe :D

How to deal with Mac OS X Helper/Main app architecture regarding core data, shared preferences and notifications?

I'm having some architectural doubts about a project (Mac OS X app) I'm working on. It basically consists of two elements: a daemon that runs in the background gathering some data and a viewer used to represent the gathered data.
The daemon should be visible in the status bar (no dock icon) and includes a small menu accessible via the status bar. It saves data in a core data store. One of the menu items is a link which opens the viewer. When this viewer is opened, a normal GUI application should start including a dock icon and menubar. The viewer is also opened when opening the application itself (by double-clicking on the icon).
After some experimenting, I figured out the best way to achieve this functionality is by creating two applications, the main application representing the viewer and a helper utility representing the daemon. One of the reasons I did it this way is that it isn't possible to switch between LSUIElement values instantly to force the daemon/viewer state.
Now I have some questions about this architecture:
Both the daemon and viewer application uses the same core data store to save and retrieve data. When having a multi-threaded application I know multiple NSManagedObjectContext objects are needed to correctly synchronize data. What about having multiple applications using the same core data store simultaneously? Is this even possible without having the risk of conflicts, locks, etc.? How do I guarantee consistency?
The daemon should always start when the viewer starts. I achieved this by simply looping through all open processes and checking if the bundle identifier of the daemon is listed. If not, the daemon is started using NSWorkspace's launchApplication. This works fine. Now when the user quits the daemon, the viewer should also stop. What is the best way for the viewer to be notified of the daemon stopping? I can periodically check active processes and quit the viewer if the daemon is gone but that sounds a bit odd. I would rather choose some kind of notification that I'll send when the viewer is about to close. But since this notification should be sent and captured between apps I don't know which simple notification service is available. Any thoughts?
The application is sandboxed as it will be distributed on the Mac App Store. Starting apps with NSWorkspace's launchApplication causes the target app to run in the same sandboxed environment as the source which I think is not a problem at all because running both applications in the same sandbox feels better and probably is. But imagine this scenario: the daemon is started automatically at login (using SMLoginItemSetEnabled) and the user double-clicks Viewer.app. As the daemon is already running (again, this is checked by looping through active processes) it won't be started. Now we have the daemon and the viewer running in different sandboxes right? Will this cause any problems regarding preferences, core data store, etc.?
I would like to use NSUserDefaults for basic configuration, can I somehow interchange this data between the daemon and the viewer? Again, both applications will have different bundle identifiers.
Thanks in advance for your help, appreciated!
There isn't one right answer to this problem, but here's how I'd approach it:
Both the daemon and viewer application uses the same core data store to save and retrieve data.
Because sharing a Core Data store between processes isn't supported (as far as I know), I'd have the daemon expose an XPC Service. Instead of opening the Core Data store itself, the viewer would use an NSXPCConnection to access the data via the daemon.
Assuming the viewer never runs without the daemon, it can use SMLoginItemSetEnabled, like you mentioned in the question, to register a mach service for the daemon, and then connect to that service.
There's sample code that goes over the details of setting that up here on Apple's website (summary: the daemon needs to be at App.app/Contents/Library/LoginItems/daemon.bundle.id.app), and you might also want to read this blog post that discusses some extra requirements imposed by sandboxing (summary: make extra sure that your Team ID is in the daemon's bundle identifier).
The daemon should always start when the viewer starts.
All set: once you register the daemon with SMLoginItemSetEnabled, launchd will start it (if necessary) when the viewer connects to its XPC Service.
Now when the user quits the daemon, the viewer should also stop.
The viewer can use the NSXPCConnection to find out when the daemon quits. The daemon can also use SMLoginItemSetEnabled to un-register itself before it quits, so that it doesn't get relaunched.
I would like to use NSUserDefaults for basic configuration, can I somehow interchange this data between the daemon and the viewer? Again, both applications will have different bundle identifiers.
Use a suite for this:
// To read or write:
NSUserDefaults* suiteDefaults = [[NSUserDefaults alloc] initWithSuiteName:#"com.example.app.shared"];
[suiteDefaults setObject:[NSDate date] forKey:#"launchTime"];
// Add the suite to -standardUserDefaults to make reading easier:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults addSuiteNamed:#"com.example.app.shared"];
To work with sandboxing, the viewer and the daemon must share an App Group. You can even use KVO to observe changes to shared keys.

Resources