Skip to content

Instantly share code, notes, and snippets.

@SMR
Forked from RameshRM/BackgroundFetch.swift
Created April 20, 2017 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SMR/3d817d7511f8e4f15c774abee5c30289 to your computer and use it in GitHub Desktop.
Save SMR/3d817d7511f8e4f15c774abee5c30289 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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment