Swift Running Code in Periodically Background

How to automatically trigger code in background in Swift?

What you are trying to do is call a function when the app is closed or in the background. Taking a step back, the user isn't actually using your app at this time. So because of that, your app shouldn't really be running functions either. I believe this is done on purpose so that the phone can allocate resources to apps/functions that the user is actively using.

So there is no way to just call a function when the app is closed. But going off your points above:

  1. I think using applicationDidBecomeActive or applicationDidFinishLaunching is probably your best bet. These are functions within the AppDelegate and you can call the functions within the methods directly. The applicationDidBecomeActive will execute every time the app appears on the screen. If you're only need it on one screen, you may be able to just call in the viewDidAppear / viewWillAppear of the ViewController instead.

  2. Idk anything about significantTimeChangeNotification so I don't want to tell you it won't work, but I would guess the notification would not execute if the app is closed.

  3. Background App Refresh is basically what you are trying to do, however, even if you implement it.. it will only execute when the app is the background. If the app is completely closed, the background fetch won't be called. So I would assume that most of the time it wouldn't be called anyway.

How make iOS app running on background Every one minute in Swift?

It's Possible using Silent Push notifications ,you can this answer.

import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var dataManager = DataManager()
var reloadSign = false;

let gcmMessageIDKey = "gcm.message_id"

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
// Override point for customization after application launch.

IQKeyboardManager.shared.enable = true
DropDown.startListeningToKeyboard()

FirebaseApp.configure()
Messaging.messaging().delegate = self

UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]

// //Solicit permission from user to receive notifications
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (_, error) in
guard error == nil else{
print(error!.localizedDescription)
return
}
}
//
// //get application instance ID
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
}
}

application.registerForRemoteNotifications()

return true
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
let proj = Project()
proj.checkData()

}

// Print full message.
print(userInfo)

}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

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.
}

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.

}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

let ud = UserDefaults.standard
ud.set( true, forKey: "isTerminated");
ud.synchronize()

}

func crashlyticsDidDetectReport(forLastExecution report: CLSReport, completionHandler: @escaping (Bool) -> Void) {
completionHandler(true)
}

}

extension AppDelegate: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

// Change this to your preferred presentation option
completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler()
}

}

extension AppDelegate: MessagingDelegate{

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")

let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}

How to execute a method every second on a background thread so it doesn't affect the performance of the app

Use Grand Central Dispatch :

DispatchQueue.global(qos: .background).async {
getDatabaseInfo()
}

iOS do scheduled operation in background or when app active

There is no way to execute a function at regular intervals, even when the app is backgrounded/killed by the user.

The most reliable solution for executing a function at regular intervals even when the app is backgrounded is to use push notifications scheduled for the specific time intervals (midnight each day in your case), which would wake up the app and let it update its data. However, this solution has its downsides, since you need a server to send the push notification from and the users device needs to be connected to the internet. Also, push notifications don't wake up the app in case the user manually killed it.

For your particular problem, the best solution would be to refactor your code in a way that you have a single function that can be used to retrieve data and hence this function could ensure the data is updated in case a certain time interval has passed since the last update.



Related Topics



Leave a reply



Submit