Created
July 5, 2018 19:18
-
-
Save marcioadr88/861ccffa41e40d6e9c082b1273b82451 to your computer and use it in GitHub Desktop.
Background fetch with Mailcore 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AppDelegate: UIResponder, UIApplicationDelegate { | |
func application(_ application: UIApplication, | |
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
let settings = UIUserNotificationSettings(types: UIUserNotificationType.alert, categories: nil) | |
UIApplication.shared.registerUserNotificationSettings(settings) | |
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) | |
return true | |
} | |
func applicationDidEnterBackground(_ application: UIApplication) { | |
print("applicationDidEnterBackground") | |
} | |
func application(_ application: UIApplication, | |
performFetchWithCompletionHandler completionHandler: | |
@escaping (UIBackgroundFetchResult) -> Void) { | |
fetchUpdates(completionHandler: completionHandler) | |
} | |
func fetchUpdates(completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { | |
let session = MCOIMAPSession() | |
session.hostname = "imap.gmail.com" | |
session.port = 993 | |
session.username = "[email protected]" | |
session.password = "********" | |
session.connectionType = .TLS | |
let requestKind = MCOIMAPMessagesRequestKind.headers | |
let folder = "INBOX" | |
let uids = MCOIndexSet(range: MCORange(location: 1, length: UInt64.max)) | |
let fetchOperation = session.fetchMessagesOperation(withFolder: folder, requestKind: requestKind, uids: uids) | |
fetchOperation?.start({ (error, fetchedMessages, _) in | |
if let error = error { | |
print("Error \(error.localizedDescription)") | |
completionHandler(.noData) | |
return | |
} | |
if let messages = fetchedMessages { | |
if messages.isEmpty { | |
print("No messages") | |
completionHandler(.noData) | |
} else { | |
print("New messages \(messages.count)") | |
let localNotification: UILocalNotification = UILocalNotification() | |
localNotification.alertAction = "App Name" | |
localNotification.alertBody = "\(messages.count) new messages" | |
localNotification.fireDate = NSDate(timeIntervalSinceNow: 1) as Date | |
UIApplication.shared.scheduleLocalNotification(localNotification) | |
completionHandler(.newData) | |
} | |
} else { | |
log.info("No messages (nil)") | |
completionHandler(.noData) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment