2

I want to make an app that makes HTTP request to a website periodically. The app has to run in the background, but can wake up or show a notification, depending on a response of request. Like a message of WhatsApp, but I don't have a webserver, only the device check values of the http get request.

piet.t
  • 11,718
  • 21
  • 43
  • 52
user11211835
  • 164
  • 2
  • 16
  • 7
    You can't. iOS doesn't support that kind of background scheduling. You should have your server send a push notification. It is much more efficient in terms of battery and network than polling, even if you could do it – Paulw11 Jun 10 '19 at 09:48
  • @Paulw11 okay , Thank you replying , every one min send data to server ,it's possible local notification??, can please send me some sample GitHub example – user11211835 Jun 10 '19 at 09:54
  • Yes, you could use location updates. Is your app intended for the App Store? If it is and you don't have a legitimate need for location it will be rejected. Using location updates continuously will severely impact battery life. – Paulw11 Jun 10 '19 at 09:59
  • It is possible, check this, It may help you. https://stackoverflow.com/questions/56522243/how-to-run-ios-app-in-background-forever/56522674#56522674 – Imran Jun 10 '19 at 10:02
  • @Imran , Thank you , I will check that solution. – user11211835 Jun 10 '19 at 10:21
  • 7
    If Apple detects that you are creating a "useless" VPN extension to bypass their system, your app and your developer account may get banned permanently. – ekscrypto Jun 12 '19 at 11:47

3 Answers3

6

The only way to do that is using a Silent push notification(see the Docs HERE and HERE), it will wake up your app on background and give you a chance to execute some code for a bit of time. But unfortunately it wont work with local notification, need to be a push notification.

Obs: Note that your time is limited to execute the background task, as the doc says

Your app has 30 seconds to perform any tasks and call the provided completion handler

And if you send too much push, the iOS can punish your application by giving it a small priority to execute your task, or even simply don't executing it

Romulo BM
  • 671
  • 8
  • 16
4

If you use silent push notification, you should know that silent push have some limit for frequency send.

https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns

Check to see if silent notifications are being throttled. APNs sends a limited number of silent notifications—notifications with the content-available key—per day. In addition, if the device has already exceeded its power budget for the day, silent notifications are not sent again until the power budget resets, which happens once a day. These limits are disabled when testing your app from Xcode.

And don't get to application if application force-quit.

If you need guaranteed delivery, you should use VoIP push notification.
But you need reason for Apple, why you need VoIP push.

But you're way drain battery non stop, and it not friendly for you're users.

Update: Now after receive VoIP push, you should show call screen - other-way next VoIP push will be ignored of iOS

Eysner
  • 584
  • 4
  • 15
-1

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)")
    }
}
Narasimham
  • 182
  • 1
  • 10
  • 4
    this does not answer anything that are asked on the question, it's only a AppDelegate with FCM configuration and some other random configurations. Looks like you only copy and paste your entire file here, without any explanation. – Romulo BM Jun 24 '19 at 20:25