Untitled

mail@pastecode.io avatar
unknown
swift
4 months ago
1.8 kB
20
Indexable
// I start with scheduling my first task:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {

    print("scheduling bg song task...")

    scheduleBackgroundFetchNewSong()

    print("done.")        

    return true
}

// This is logic that runs in `scheduleBackgroundFetchNewSong`:
BGTaskScheduler.shared.getPendingTaskRequests { requests in

    guard requests.isEmpty else {
        print("there is \(requests.count) task(s) pending to run -- returning for now.")
        return
    }        

    let request = BGAppRefreshTaskRequest(identifier: "com.app.backgroundFetch.newSong")

    // calculate the run time

    let todayRunTime = getTaskRunTime()
    
    request.earliestBeginDate = todayRunTime
    
    do {
    
        print("submitting request.")
        
        try BGTaskScheduler.shared.submit(request)
        
        print("bg task scheduled!")
    
    } catch {
    
        print("could not schedule background fetch new song: \(error)")
    
    }

}

// And finally, this is get getTaskRunTime:
let now = Date()
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)

// tell iOS that it can begin running this at 11 PM every night.
components.hour = 23
components.minute = 0
components.second = 0

// get today's 11:00 pm.
if let todayTaskRunTime = Calendar.current.date(from: components) {

print("calculated run time: \(todayTaskRunTime)")
// if it's already past the run time today, schedule for tomorrow
if now > todayTaskRunTime {

    return Calendar.current.date(byAdding: .day, value: 1, to: todayTaskRunTime)

} else {
    // otherwise, schedule for today at desired time
    return todayTaskRunTime
}


Leave a Comment