Checking back from the background - ios

I have a webview on Android that always checks if there is internet coming back from the background checking if the connection status has changed if it is offline the application sends the user to a "reconnect and try again" screen using the code below:
protected void onResume() {
super.onResume();
mWebView.onResume();
if (isConnected(getApplicationContext())){
} else {
Intent i = new Intent(MainActivity.this, off.class);
startActivity(i);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
}
So far I have made a version for ios of this webview but I could not reproduce this check when the app returns from the background, how do I reproduce this "onresume" in ios swift? (the code that checks the connection state I already have)

In AppDelegate use the following method:
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
print("Enter foreground")
}

Subscribe for UIApplication.willEnterForegroundNotification and check the connection immediately after it's fired.

Related

iOS requestTrackingAuthorization callback is not on the main thread

The iOS ATT Alert needs to be shown on startup before an app starts, so the remaining app code needs to be run in the completion handler (eg initialising advert code and starting the main game).
However, this crashes because the completion handler callback is not on the main thread (after the alert is actually shown and Allow or Ask App Not to Track is selected).
In iOS (Xamarin C# code):
public override void OnActivated(UIApplication application) // RequestTrackingAuthorization must be called when app is Active
{
if (!this.shownAlert)
{
this.shownAlert=true;
Debug.WriteLine("1) ThreadId={0}", Environment.CurrentManagedThreadId); // ThreadId=1
ATTrackingManager.RequestTrackingAuthorization(delegate (ATTrackingManagerAuthorizationStatus trackingManagerAuthorizationStatus)
{
Debug.WriteLine("2) ThreadId={0}", Environment.CurrentManagedThreadId); // ThreadId=7
});
}
}
Prints:
1) ThreadId=1
2) ThreadId=7
And the similarly in Unity:
Debug.WriteLine("1) ThreadId={0}", Environment.CurrentManagedThreadId); // ThreadId=1
ATTrackingStatusBinding.RequestAuthorizationTracking(delegate (int status)
{
Debug.WriteLine("2) ThreadId={0}", Environment.CurrentManagedThreadId); // ThreadId=4
});
This seems like a bug to me. So how do all the apps and games out there get this to work? Somehow switch to the main thread in the callback? I don’t see any examples of this.

Why is my app crashing shortly after termination?

In my iOS app, I have several Firebase event listeners in place as the user performs different functions. I am encountering an issue where the app crashes (only sometimes) specifically when the user terminates it by double-tapping the home button and swiping up. In the applicationWillTerminate function of AppDelegate.swift, I simply remove all registered event listeners:
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
Home.globalEvents = []
removeListeners()
}
private func removeListeners()
{
UserService.userEventListener?.remove()
UserService.friendIDListener?.remove()
UserService.groupListener?.remove()
UserService.postListener?.remove()
Home.requestListener?.remove()
Home.eventsListener?.remove()
Home.inviteListener?.remove()
Home.requestCount = 0
Home.inviteCount = 0
Home.publicEventListener?.remove()
Home.privateEventListener?.remove()
ProfileFinder.requestListener?.remove()
}
This gives me the error message:
"Assertion failure in auto FSTLocalStore::releaseQuery:::(anonymous class)::operator()() const()"
Can anyone clue me in as to why what I'm doing is problematic? Thanks.

UI (sometimes) freezes during an operation on iOS

So, on my app I have a feed that I want to update every time the user returns to the app.
I'm calling a routine to do this on applicationWillEnterForeground of my AppDelegate.
Everything is working fine but, sometimes, my UI freezes during this operation.
I was able to find where this occurs using a label to show the progress of this routine. The label is updated on three major points:
Before starting the routine
Inside the routine
When the routine ends
Sometimes, this workflow works fine, and I'm able to see the progress through this label.
But sometimes, the label only shows the first message, and messages that happen inside the routine does not appear. Besides that, I can't do anything on my app, because the UI is frozen. Once the routine is over, everything comes back to normal.
Here's a simplified version of the flow my app executes to call this routine:
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let mainViewController = MainViewController()
func applicationWillEnterForeground(_ application: UIApplication) {
mainViewController.refreshLatestVideos()
}
}
class MainViewController: UITabBarController {
private var subscriptionsController: SubscriptionsController! // initialized on viewDidLoad
func refreshLatestVideos() {
subscriptionsController.refreshLatestVideos(sender: nil)
}
}
class SubscriptionsController: UITableViewController {
private var subscriptionsModelController: SubscriptionsModelController! // received on constructor
#objc func refreshLatestVideos(sender:UIButton!) {
showMessage(message: "Updating subscriptions...") // this message is always shown to me
subscriptionsModelController.loadLatestVideos()
}
}
class SubscriptionsModelController {
func loadLatestVideos() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
DispatchQueue.global(qos: .userInitiated).async {
// bunch of requests with Just
...
// update message
showMessage(message: "Updating subscription x of y") // this message sometimes doesn't appear, because the UI is frozen
// another requests
...
// update message
showMessage(message: "Updates completed")
}
}
}
As you can see, I'm executing the update inside the global queue, so I'm not blocking the main thread.
And again, this freezing of the UI only happens sometimes.
Is there any point which I can look at to find what's going on? Is it possible that the main thread is being blocked by something else?
Dispatch updating the UI to the main thread:
DispatchQueue.main.async { showMessage(message: "Updates completed") }
Everytime you anyhow access/modify the UI, do it on the main thread to avoid having unexpected problems (link to one of several resources on this topic, I suggest you google up and read more).
That applies to the rest of the code as well, if there is something that is related to UI, do the same for it - e.g., if after finishing the task you call tableView.reloadData, do it on the main thread too.

iOS Ignoring enqueueSampleBuffer because status is failed

When I restart app from here: https://github.com/zweigraf/face-landmarking-ios picture from camera doesn't appear and printing error: "Ignoring enqueueSampleBuffer because status is failed".
The problem is probably in captureOutput from SessionHandler.swift
I find a solution! Thanks to Why does AVSampleBufferDisplayLayer fail with Operation Interrupted (-11847)?
If you had similar problem you need to set AVSampleBufferDisplayLayer each time app entering foreground. Like this:
//AppDelegate.swift
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
viewcontroller?.setLayer()
}
//ViewController.swift
func setLayer() {
sessionHandler.layer = AVSampleBufferDisplayLayer()
sessionHandler.layer.frame = preview.bounds
sessionHandler.layer.videoGravity = AVLayerVideoGravityResizeAspectFill
preview.layer.addSublayer(sessionHandler.layer)
}
and don't forget to remove sublayer:
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
viewcontroller?.sessionHandler.layer.removeFromSuperlayer()
}

Apple Watch Background Mode?

I am developing apple watch application. when i run the app it is working fine. Now my problem is when the app goes to background mode, the app on the apple watch app will closing automatically. I am writing small code in iPhone app:
func viewDidLoad() {
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
// In your WatchKit extension, the value of this property is true when the paired iPhone is reachable via Bluetooth.
// On iOS, the value is true when the paired Apple Watch is reachable via Bluetooth and the associated Watch app is running in the foreground.
// In all other cases, the value is false.
if session.reachable {
lblStatus.text = "Reachable"
}
else
{
lblStatus.text = "Not Reachable"
}
func sessionReachabilityDidChange(session: WCSession)
{
if session.reachable {
dispatch_async(dispatch_get_main_queue(), {
self.lblStatus.text = "Reachable"
})
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.lblStatus.text = "Not Reachable"
})
}
}
}
}
in WatchExtention Code is
func someFunc() {
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
if session.reachable {
ispatch_async(dispatch_get_main_queue(), {
self.lblStatus.setText("Reachable")
})
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.lblStatus.setText("Not Reachable")
})
}
func sessionReachabilityDidChange(session: WCSession)
{
if session.reachable {
dispatch_async(dispatch_get_main_queue(), {
self.lblStatus.setText("Reachable")
})
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.lblStatus.setText("Not Reachable")
})
}
}
}
}
Now when enter to background in apple Watch the iPhone app showing Not reachable why ?
It's the default behavior of the AppleWatch, mainly to spare with resources like battery.
session.reachable property is true only when Apple Watch is reachable via Bluetooth and the associated Watch app is running in the
foreground in all other cases, the value is false.
In your case the second option which caused the problem I suppose the bluetooth connection is working.
Anyway the question is what do you like to reach.
Actually the simple rule is that you couldn't wake up the Watch from the iPhone but you could wake up the iPhone app from the Watch.
Two ways with three options to reach the watch when it's counterpart is in the background: send a complication update or send a message (2 options) in the background which will be available for the Watch when it will awake again.
All of them are part of the WCSession Class.
The two options for sending messages are:
- updateApplicationContext:error:
You can use this method to transfer a dictionary of data to the counterpart Watch app.iPhone sends context data when the opportunity arises, means when the Watch app arises.The counterpart’s session on the Watch gets the data with the session:didReceiveUpdate: method or from the receivedApplicationContext property.
You may call this method when the watch is not currently reachable.
The other option is sending data in the background like
- transferUserInfo:
You can use this method when you want to send a dictionary of data to the Watch and ensure that it is delivered. Dictionaries sent using this method are queued on the other device and delivered in the order in which they were sent. After a transfer begins, the transfer operation continues even if the app is suspended.
BUT true for both methods that they can only be called while the session is active. Calling any of these methods for an inactive or deactivated session is a programmer error.
The complication solution is a little bit different but belongs to the same WCSession Class as the earliers.
-transferCurrentComplicationUserInfo:
This method is specifically designed for transferring complication user info to the watch with the aim to be shown on the watch face immediately.
Of course it's available only for iOS, and using of this method counts against your complication’s time budget, so it's availability is limited.
The complication user info is placed at the front of the queue, so the watch wakes up the extension in the background to receive the info, and then the transfer happens immediately.
All messages received by your watch app are delivered to the session delegate serially on a background thread, so you have to switch to the main queue in case you'd like to use or presenting them for UI.
The WWDC talk on WatchConnectivity discusses "reachability" and its nuances in quite a lot of detail, so you should definitely give it a watch.
TL;DR: reachable on the watch is for the most part only going to be true/YES when the watch app's UI is visible on the screen.

Resources