Emit socket event in applicationWillTerminate - ios

I am trying to emit a socket event in applicationWillTerminate in AppDelegate. I have used socket.io.
I believe I am able to successfully emit the event.
Following are the logs I get in the console :
2018-10-08 20:29:45.663856+0530 SOCKET_POC[4718:303986] LOG SocketIOClient{/}: Emitting: 23["device-disconnect","{\"QrcodeID\":\"2a758b00-314f-d69d-a10b-24fca56693ed\",\"UniqueID\":\"E15C087D-626F-4F10-B0B3-7567DA76EF51\"}"], Ack: false
2018-10-08 20:29:49.561608+0530 SOCKET_POC[4718:304214] LOG SocketEngine: Writing ws: 23["device-disconnect","{\"QrcodeID\":\"123\",\"UniqueID\":\"123\"}"] has data: false
2018-10-08 20:29:49.561675+0530 SOCKET_POC[4718:304214] LOG SocketEngineWebSocket: Sending ws: 23["device-disconnect","{\"QrcodeID\":\"123\",\"UniqueID\":\"123\"}"] as type: 4
Please find the code below :
func applicationWillTerminate(_ application: UIApplication) {
print(SocketHandler.instance?.socket.status)
if let uniqueId = UserDefaults.standard.value(forKey: Constants.USER_DEFAULT_KEYS.UINQUE_ID) as? String {
CommonFunctions().emitResultOnDeviceDisconnect(qrcode: "\(Variables.QRCodeID)", uniqueId: uniqueId)
print(SocketHandler.sharedInstance().socket.status)
}
I have even printed the status of my socket which always prints connected.
But when I see the logs at the server(backend), they don't receive my emitted socket event at all.

In your AppDelegate.Swift,
change your "applicationDidEnterBackground(_ application: UIApplication)" to Following code ==>
func applicationDidEnterBackground(_ application: UIApplication) {
var bgTask: UIBackgroundTaskIdentifier = 0;
bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
print("The task has started")
application.endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
})
}
And keep your logic of "applicationWillTerminate" as it is.

If you want to fire socket event as soon as you kill the application, you need to create a background task as from the apple's developer documentation.
optional func applicationWillTerminate(_ application: UIApplication)
You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.
What you can do is create a background task to fire the socket event so that if we are supposed to receive a callback, we can get in time.
Please follow the following code to resolve the problem you are facing:
Add this property in your Appdelegate
var taskIdentifier: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
Add the following methods
func startBackgroundTask() {
taskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in
self?.endBackgroundTask()
})
// Only to check if the task is in invalid state or not for debugging.
assert(task != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
UIApplication.shared.endBackgroundTask(taskIdentifier)
taskIdentifier = UIBackgroundTaskInvalid
}
func applicationWillTerminate(_ application: UIApplication) {
if let uniqueId = UserDefaults.standard.value(forKey: Constants.USER_DEFAULT_KEYS.UINQUE_ID) as? String {
CommonFunctions().emitResultOnDeviceDisconnect(qrcode: "\(Variables.QRCodeID)", uniqueId: uniqueId)
}
self.startBackgroundTask()
}
I hope this will solve your problem. In case of any issues please feel free to as in loop.
Thanks.

Related

Trying to use BGAppRefreshTask and getting error No task request with identifier <decode: missing data> has been scheduled

I kept getting the error
No task request with identifier <decode: missing data> has been scheduled
in my debugger output so I decided to try running the example code provided by Apple here and got the same error. I've tried multiple computers and Xcode versions, multiple example projects from different sources and nothing has worked.
My AppDelegate.swift file:
import UIKit
import Firebase
import BackgroundTasks
#main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
BGTaskScheduler.shared.register(forTaskWithIdentifier: “redacted.identifier”, using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
BGTaskScheduler.shared.cancelAllTaskRequests()
scheduleAppRefresh()
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "redacted.identifier")
request.earliestBeginDate = Date(timeIntervalSinceNow: 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh()
let db = Firestore.firestore()
db.collection("devices").document(UIDevice.current.identifierForVendor!.uuidString).setData([
"batteryLevel": UIDevice.current.batteryLevel*100
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("success")
task.setTaskCompleted(success: true)
}
}
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
}
I am testing background fetch by running
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:#"redacted.identifier"]
in the Xcode console, after which the error above occurs.
Console output:
Simulating launch for task with identifier redacted.identifier
No task request with identifier <decode: missing data> has been scheduled
A couple of potential issues:
This happens when testing on the simulator. Use a physical device.
Make sure your Info.plist has a “Permitted background task scheduler identifiers” (i.e. BGTaskSchedulerPermittedIdentifiers) entry with the identifier for your background task.
Make sure you set your breakpoint immediately after the BGTaskScheduler.shared.submit(...) line and that you perform the _simulateLaunchForTaskWithIdentifier after submit was called. I.e., make sure you are even getting to the submit call. (See next point.)
Notably, the Apple example (and your example) are scheduling it in applicationDidEnterBackground(_:). But if you are using a UIWindowSceneDelegate (i.e. in your SceneDelegate), then the app delegate’s applicationDidEnterBackground(_:) is not called, but rather the scene delegate’s sceneDidEnterBackground(_:) is. I put the scheduling of the BGAppRefreshTaskRequest in the scene delegate’s sceneDidEnterBackground(_:).
I got the same issue when I tested on a Device.
Go to Device Settings > General > Background App Refresh and turn on Background App Refresh. This issue has gone after it.
There is one another case that isn't mentioned in other answers, if you're trying to submit different or more than 1 refresh tasks you might be hitting the error case below. Issue is, currently the mentioned error isn't thrown in Xcode 13.1, so it looks like submitting request works, but basically it doesn't.
Apple doc: There can be a total of 1 refresh task and 10 processing tasks scheduled at any time. Trying to schedule more tasks returns BGTaskScheduler.Error.Code.tooManyPendingTaskRequests.
It looks like applicationDidEnterBackground is never get called, check it out (add breakpoint).
func applicationDidEnterBackground(_ application: UIApplication) {
BGTaskScheduler.shared.cancelAllTaskRequests()
scheduleAppRefresh()
}
because of a scene-based configured lifecycle
If it's true, move your logic into SceneDelegate class
func sceneDidEnterBackground(_ scene: UIScene) {
BGTaskScheduler.shared.cancelAllTaskRequests()
scheduleAppRefresh()
}

iOS applicationWillResignActive task not performed until app becomes active again

I'm trying to use applicationWillResignActive() in order to sync some data to my Firestore database before the application enters the background.
func applicationWillResignActive(_ application: UIApplication) {
self.uploadWantToPlay()
}
When I call my upload function from applicationWillResignActive() it runs but no data is added to Firestore before the next time the application becomes active.
When I for testing purposes instead run the same function from one of my ViewControllers the data is added instantly to Firestore.
I've also tried calling the function from applicationDidEnterBackground(), I've tried running it in it's own DispatchQueue. But it's had the same result.
How can I run this function as the user is about to leave the app and have it perform the database sync properly?
The functions handling the database sync;
func uploadWantToPlay() {
print ("Inside uploadWantToPlay")
if let wantToPlay = User.active.wantToPlayList {
if let listEntries = wantToPlay.list_entries {
let cleanedEntries = listEntries.compactMap({ (entry: ListEntry) -> ListEntry? in
if entry.game?.first_release_date != nil {
return entry
} else {
return nil
}
})
let gamesToUpload = cleanedEntries.filter {
$0.game!.first_release_date! > Int64(NSDate().timeIntervalSince1970 * 1000)
}
DatabaseConnection().writeWantToPlayToDatabase(user: User.active,wantToPlay: gamesToUpload)
}
}
}
func writeWantToPlayToDatabase(user: User, wantToPlay: [ListEntry]) {
firebaseSignIn()
let deviceId = ["\(user.deviceId)": "Device ID"]
for entry in wantToPlay {
let wantToPlayGameRef = fireStore.collection(WANTTOPLAY).document("\(entry.game!.id!)")
wantToPlayGameRef.updateData(deviceId) {(err) in
if err != nil {
wantToPlayGameRef.setData(deviceId) {(err) in
if let err = err {
Events().logException(withError: err, withMsg: "DatabaseConnection-writeWantToPlayToDatabase(user, [ListEntry]) Failed to write to database")
} else {
print("Document successfully written to WantToPlayGames")
}
}
} else {
print("Document successfully updated in WantToPlayGames")
}
}
}
}
According to the Apple documentation
Apps moving to the background are expected to put themselves into a
quiescent state as quickly as possible so that they can be suspended
by the system. If your app is in the middle of a task and needs a
little extra time to complete that task, it can call the
beginBackgroundTaskWithName:expirationHandler: or
beginBackgroundTaskWithExpirationHandler: method of the UIApplication
object to request some additional execution time. Calling either of
these methods delays the suspension of your app temporarily, giving it
a little extra time to finish its work. Upon completion of that work,
your app must call the endBackgroundTask: method to let the system
know that it is finished and can be suspended.
So, what you need to do here is to perform a finite length task while your app is being suspended. This will buy your app enough time to sync your records to the server.
An example snippet:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundTask: UIBackgroundTaskIdentifier!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
self.registerBackgroundTask()
// Do your background work here
print("Do your background work here")
// end the task when work is completed
self.endBackgroundTask()
}
func registerBackgroundTask() {
self.backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.endBackgroundTask()
}
assert(self.backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
print("Background task ended.")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
}
For further information refer to this article.

Spotify SDK player not working: Error Domain=com.spotify.ios-sdk.playback Code=1 "The operation failed due to an unspecified issue."

I am currently developing an iOS app to login to my Spotify account and play songs in there.
This is my code:
import UIKit
import AVKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
SPTAudioStreamingDelegate {
var window: UIWindow?
let kClientId = "hidden------my client ID"
let kRedirectUrl = URL(string: "spotify-study2-login://return-after-login")
var session: SPTSession?
var player: SPTAudioStreamingController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// set up Spotofy
SPTAuth.defaultInstance().clientID = kClientId
SPTAuth.defaultInstance().redirectURL = kRedirectUrl
SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope] as [AnyObject]
let loginUrl = SPTAuth.defaultInstance().spotifyAppAuthenticationURL()
application.open(loginUrl!)
return true
}
// handle auth
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if SPTAuth.defaultInstance().canHandle(url) {
SPTAuth.defaultInstance().handleAuthCallback(withTriggeredAuthURL: url, callback: { error, session in
if error != nil {
print("*** Auth error: \(String(describing: error))")
}
// Call the -loginUsingSession: method to login SDK
self.loginUsingSession(session: session!)
})
return true
}
return false
}
func loginUsingSession(session: SPTSession) {
// Get the player Instance
player = SPTAudioStreamingController.sharedInstance()
if let player = player {
player.delegate = self
// start the player (will start a thread)
try! player.start(withClientId: kClientId)
// Login SDK before we can start playback
player.login(withAccessToken: session.accessToken)
let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
self.player?.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
if error != nil {
print("*** failed to play: \(String(describing: error))")
return
} else {
print("play")
}
})
}
}
// MARK: SPTAudioStreamingDelegate.
func audioStreamingDidLogin(audioStreaming: SPTAudioStreamingController!) {
let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
player!.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
if error != nil {
print("*** failed to play: \(String(describing: error))")
return
} else {
print("play")
}
})
}
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.
//log
print("func applicationWillResignActive has been called")
}
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.
//log
print("func applicationDidEnterBackground has been called")
}
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.
//log
print("func applicationWillEnterForeground has been called")
}
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.
//log
print("applicationDidBecomeActive")
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
//log
print("func applicationWillTerminate has been called")
}
}
When I run the debugger, I found an error message saying:
Error Domain=com.spotify.ios-sdk.playback Code=1 "The operation failed
due to an unspecified issue." UserInfo={NSLocalizedDescription=The
operation failed due to an unspecified issue.}
This error message came from the part below:
// MARK: SPTAudioStreamingDelegate.
func audioStreamingDidLogin(audioStreaming:
SPTAudioStreamingController!) {
let urlStr = "spotify:track:3yMPqvbPNaL5DUDOmwEr6l" // a song I choose. I already confirmed this song really exsits.
player!.playSpotifyURI(urlStr, startingWith: 0, startingWithPosition: 0, callback: { error in
if error != nil {
print("*** failed to play: \(String(describing: error))")
return
} else {
print("play")
}
})
}
In addition, I also found
2017-11-19 19:31:04.050872+0900 SpotifyStudy2[756:110616] Caching
allowed 1
from the part below:
// Login SDK before we can start playback
player.login(withAccessToken: session.accessToken)
Googling about this problem cost me lots of time but still I haven't found a nice answer to solve this.
If you have any idea what this error specifically means, your answer will help me so much...! Thank you in advance.
I was facing the same issue, and I have resolved using belove code
do {
try SPTAudioStreamingController.sharedInstance()?.start(withClientId: SPTAuth.defaultInstance().clientID, audioController: nil, allowCaching: true)
SPTAudioStreamingController.sharedInstance().delegate = self
SPTAudioStreamingController.sharedInstance().playbackDelegate = self
SPTAudioStreamingController.sharedInstance().diskCache = SPTDiskCache() /* capacity: 1024 * 1024 * 64 */
SPTAudioStreamingController.sharedInstance().login(withAccessToken: "Token here")
} catch _ {
print("catch")
}

iOS Swift download lots of small files in background

In my app I need to download files with the following requirements:
download lots (say 3000) of small PNG files (say 5KB)
one by one
continue the download if the app in background
if an image download fails (typically because the internet connection has been lost), wait for X seconds and retry. If it fails Y times, then consider that the download failed.
be able to set a delay between each download to reduce the server load
Is iOS able to do that? I'm trying to use NSURLSession and NSURLSessionDownloadTask, without success (I'd like to avoid starting the 3000 download tasks at the same time).
EDIT: some code as requested by MwcsMac:
ViewController:
class ViewController: UIViewController, URLSessionDelegate, URLSessionDownloadDelegate {
// --------------------------------------------------------------------------------
// MARK: Attributes
lazy var downloadsSession: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier:"bgSessionConfigurationTest");
let session = URLSession(configuration: configuration, delegate: self, delegateQueue:self.queue);
return session;
}()
lazy var queue:OperationQueue = {
let queue = OperationQueue();
queue.name = "download";
queue.maxConcurrentOperationCount = 1;
return queue;
}()
var activeDownloads = [String: Download]();
var downloadedFilesCount:Int64 = 0;
var failedFilesCount:Int64 = 0;
var totalFilesCount:Int64 = 0;
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
startButton.addTarget(self, action:#selector(onStartButtonClick), for:UIControlEvents.touchUpInside);
_ = self.downloadsSession
_ = self.queue
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// MARK: User interaction
#objc
private func onStartButtonClick() {
startDownload();
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// MARK: Utils
func startDownload() {
downloadedFilesCount = 0;
totalFilesCount = 0;
for i in 0 ..< 3000 {
let urlString:String = "http://server.url/\(i).png";
let url:URL = URL(string: urlString)!;
let download = Download(url:urlString);
download.downloadTask = downloadsSession.downloadTask(with: url);
download.downloadTask!.resume();
download.isDownloading = true;
activeDownloads[download.url] = download;
totalFilesCount += 1;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// MARK: URLSessionDownloadDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if(error != nil) { print("didCompleteWithError \(error)"); }
failedFilesCount += 1;
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let url = downloadTask.originalRequest?.url?.absoluteString {
activeDownloads[url] = nil
}
downloadedFilesCount += 1;
[eventually do something with the file]
DispatchQueue.main.async {
[update UI]
}
if(failedFilesCount + downloadedFilesCount == totalFilesCount) {
[all files have been downloaded]
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// MARK: URLSessionDelegate
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let completionHandler = appDelegate.backgroundSessionCompletionHandler {
appDelegate.backgroundSessionCompletionHandler = nil
DispatchQueue.main.async { completionHandler() }
}
}
}
// --------------------------------------------------------------------------------
}
AppDelegate:
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
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:.
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: #escaping () -> Void) {
backgroundSessionCompletionHandler = completionHandler
}
}
Download:
class Download: NSObject {
var url: String
var isDownloading = false
var progress: Float = 0.0
var downloadTask: URLSessionDownloadTask?
var resumeData: Data?
init(url: String) {
self.url = url
}
}
What's wrong with this code:
I'm not sure that the background part is working. I followed this tutorial: https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started. It says that the app screenshot should be updated if I press home and then double tap home to show the app switcher. Does not seems to work reliably. It is updated when I re-open the app though. Having an iPhone since yesterday, I don't know if this is the normal behavior?
the 3000 downloads are started in the startDownload method. The maxConcurrentOperationCount of the queue does not seem to be respected: downloads are running concurrently
the downloadsSession.downloadTask(with: url); call takes 30ms. Multiplied by 3000, it takes 1mn30, that's a big problem :/ . Waiting a few seconds (2-3) would be ok.
I can't set a delay between two downloads (that's not a big problem. Would be nice though, but if I can't it will be OK)
Ideally, I would run the startDownload method asynchronously, and download the files synchronously in the for loop. But I guess I can't do that in background with iOS?
So here is what I finally did:
start the download in a thread, allowed to run for a few minutes in background (with UIApplication.shared.beginBackgroundTask)
download files one by one in a loop with a custom download method allowing to set a timeout
before downloading each file, check if UIApplication.shared.backgroundTimeRemaining is greater than 15
if yes, download the file with a timeout of min(60, UIApplication.shared.backgroundTimeRemaining - 5)
if no, stop downloading and save the download progress in the user defaults, in order to be able to resume it when the user navigates back to the app
when the user navigates back to the app, check if a state has been saved, and if so resume the download.
This way the download continues for a few minutes (3 on iOS 10) when the user leaves the app, and is pause just before these 3 minutes are elapsed. If the user leaves the app in background for more than 3 minutes, he must come back to finish the download.

How to run operations in background while an iOS application is in foreground

I have a JSON file populated with strings data in Documents Directory. In user Interface of application there is a UIButton. On button press, a new string appends into the JSON file.
Now I am looking for any iOS Service that helps me to send these strings (from JSON file) to the server using swift. And this service should be totally independent of my code.
The point is when I press a UIButton, the first step is a string is saved to the JSON file then service should take this string and send it to server if Internet is available.
When a string sent successfully, it should be removed from the JSON file.
This service should track after every 30 seconds if there is any string saved into JSON file, then send it to server.
I Googled and found background fetch but It triggers performFetchWithCompletionHandler function automatically and I cannot know when iOS triggers it. I want to trigger this kind of service my self after every 30 seconds.
Review the Background Execution portion of Apple's App Programming Guide for iOS.
UIApplication provides an interface to start and end background tasks with UIBackgroundTaskIdentifier.
In the top level of your AppDelegate, create a class-level task identifier:
var backgroundTask = UIBackgroundTaskInvalid
Now, create your task with the operation you wish to complete, and implement the error case where your task did not complete before it expired:
backgroundTask = application.beginBackgroundTaskWithName("MyBackgroundTask") {
// This expirationHandler is called when your task expired
// Cleanup the task here, remove objects from memory, etc
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
// Implement the operation of your task as background task
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Begin your upload and clean up JSON
// NSURLSession, AlamoFire, etc
// On completion, end your task
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
What I have done is I just uses the approach discussed by JAL above.
these were the three methods which I used
func reinstateBackgroundTask() {
if updateTimer != nil && (backgroundTask == UIBackgroundTaskInvalid) {
registerBackgroundTask()
}
}
func registerBackgroundTask() {
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
[unowned self] in
self.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
NSLog("Background task ended.")
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
where updateTimer is of type NSTIMER class
The above functions are in my own created class named "syncService"
This class has an initialiser which is
init(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.reinstateBackgroundTask), name: UIApplicationDidBecomeActiveNotification, object: nil)
updateTimer = NSTimer.scheduledTimerWithTimeInterval(30.0, target: self, selector: #selector(self.syncAudit), userInfo: nil, repeats: true)
registerBackgroundTask()
}
Then I just called this class and the whole problem is solved.
DispatchQueue.global(qos: .background).async { // sends registration to background queue
}
Please refer NSURLSessionUploadTask might it help you.
Here is the swift 4 version of the answer by JAL
extension UIApplication {
/// Run a block in background after app resigns activity
public func runInBackground(_ closure: #escaping () -> Void, expirationHandler: (() -> Void)? = nil) {
DispatchQueue.main.async {
let taskID: UIBackgroundTaskIdentifier
if let expirationHandler = expirationHandler {
taskID = self.beginBackgroundTask(expirationHandler: expirationHandler)
} else {
taskID = self.beginBackgroundTask(expirationHandler: { })
}
closure()
self.endBackgroundTask(taskID)
}
}
}
Usage Example
UIApplication.shared.runInBackground({
//do task here
}) {
// task after expiration.
}

Resources