您可以安排特定时间的本地通知,以及用户何时看到该通知以及是否希望他可以通过点击该通知来打开您的应用 . 那时,您将能够知道,用户已经点击了通知,因此应用程序已打开,您可以进行网络调用以获取数据并在应用程序内显示 . This will not require any background calls therefor and only make a network call to an action by a user.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Tapped in notification")
}
//This is key callback to present notification while the app is in foreground
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Notification being triggered")
//You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
//to distinguish between notifications
if notification.request.identifier == "SampleRequest" {
completionHandler( [.alert,.sound,.badge])
}
}
3 回答
如果要显示
weather forecast
,推送通知是您的最佳选择 .更多关于此:https://stackoverflow.com/a/41901767/3901620
您可以安排特定时间的本地通知,以及用户何时看到该通知以及是否希望他可以通过点击该通知来打开您的应用 . 那时,您将能够知道,用户已经点击了通知,因此应用程序已打开,您可以进行网络调用以获取数据并在应用程序内显示 . This will not require any background calls therefor and only make a network call to an action by a user.
另一种选择:您可以创建应用程序的小部件(如Weather Widget) . 每当用户进入小部件区域时,您将获得代表呼叫并进行网络呼叫以获取最新的天气数据 . 如果用户想要了解更多信息,他只需点按它即可打开您的应用 . 然后,一切都掌握在你手中 .
您的选择:只要用户在特定日期打开您的应用并为其设置通知,您就可以始终获得动态内容 . 但这不是可以建议的,因为用户可能无法获得更新的数据 .
推送通知:但是,如果您想通过服务器将动态数据发送到您的应用,则可能不需要这种情况 . 这始终是最好的选择 .
我创造了一个功能 . 在您需要的时候,它将在特定时间调用您的函数 . 我正在创建一个时钟应用程序,所以我需要在用户创建警报时触发本地通知 . 在通知中心委托方法中,您可以处理您的响应并调用您想要的任何方法 .
在AppDelegate方法中: - 只要用户点击您的通知或者您的通知何时出现,您就可以处理 . 由您决定要做什么 .
// MARK: - 通知代表