Skip to content

Instantly share code, notes, and snippets.

@RameshRM
Last active March 8, 2022 14:36
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save RameshRM/8ca0a1be512520a5240e to your computer and use it in GitHub Desktop.
Save RameshRM/8ca0a1be512520a5240e to your computer and use it in GitHub Desktop.
Swift Background Fetch
Step 1: Enable capabilities "background fetch"
Step2 : Setup AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
return true;
}
Step 3: Register application event in AppDelegate.swift, to register completion handler
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
println("Complete");
completionHandler(UIBackgroundFetchResult.NewData)
getData();
}
func getData() -> Void{
var url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=xxxxxx&limit=20";
var request = NSURLRequest(URL: NSURL(string: url));
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var moviesResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary;
var movies: [NSDictionary]=[];
movies = moviesResult["movies"] as [NSDictionary];
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Testing notifications on iOS8"
localNotification.alertBody = "Movie Count : \(movies.count)"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 1)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
}
@daniel-goldman
Copy link

daniel-goldman commented Feb 6, 2017

Your performFetchWithCompletionHandler is incorrect. According to this code, the completionHandler gets called before your getData(); it is likely your getData() will never run.

You should be passing the completionHandler as a parameter to getData() (must be the last parameter if you have more than one) and then called inside your NSURLConnection.sendAsynchronousRequest callback once its work is done.

@vipulbansal
Copy link

No, daniel u are interpreting it wrong, mate

@BorisNikolic
Copy link

@vipulbansal please explain?

@bstien
Copy link

bstien commented Mar 14, 2017

@RameshRM @SirobChilokin From Apple docs:

When this method is called, your app has up to 30 seconds of wall-clock time to perform the download operation and call the specified completion handler block. In practice, your app should call the completion handler block as soon as possible after downloading the needed data. If you do not call the completion handler in time, your app is terminated.

In this context, 'this method' is referring to application(_:performFetchWithCompletionHandler:), not the completion handler.

Edit: Tagged the wrong guy at the top :) The answer from @daniel-goldman is correct.

@notNewlyBorn
Copy link

@daniel-goldman @bstien Can we please have a correct version of the code? Thanks in advance :)

@m760622
Copy link

m760622 commented Mar 6, 2018

This ia for swift 3 not 4
what to do?

@m-montoya
Copy link

Though this is all quite old, for anyone else wondering about @daniel-goldman comment, getData() should be changed over to

func getData(_ completion: () -> Void) { completion() }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment