在我的应用程序中,我使用Facebook图表api下载数据,并希望在有新数据时发出通知。我想下载数据,将其与已存储在NSUserDefaults中的数据进行比较,如果不同则显示通知。
我在info.plist文件中允许后台提取,在我的appDelegate中,我添加了以下代码:
在didFinishLaunchingWithOptions()中:
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(30)
在performFetchWithCompletionHandler()
中(这不包括用于检查所提取的数据是否为新数据的代码,它只是一个测试)
let url = "https://graph.facebook.com/109315262061/posts?limit=20&fields=id,full_picture,picture,from,shares,attachments,message,object_id,link,created_time,comments.limit(0).summary(true),likes.limit(0).summary(true)&access_token=\(API_KEY)"
let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data, response, error) in
if error == nil
{
dispatch_async(dispatch_get_main_queue(), {
do
{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
ids.removeAll()
if let items = jsonData["data"] as? [[String:AnyObject]]
{
for item in items
{
if let id = item["id"] as? String
{
ids.append(id)
}
}
if ids.count == 20
{
print(jsonData)
let notification = UILocalNotification()
notification.alertBody = "You have new notifications!"
notification.alertTitle = "NSITConnect"
notification.fireDate = NSDate(timeIntervalSinceNow: 1)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
completionHandler(UIBackgroundFetchResult.NewData)
}
}
}
catch
{
}
})
}
}
task.resume()
下载操作成功,但我没有看到通知。我怎样才能解决这个问题?还有一种方法可以在强制关闭应用程序时下载数据,然后显示通知吗?如果这是一个愚蠢的问题,我很抱歉,我对这个概念还不熟悉!
答案 0 :(得分:0)
如果应用已经打开,则会显示通知,尝试创建警报以显示您的消息,或者创建自定义控制器/视图。
您可以检查您的应用当前是否处于活动状态,或者不是这样,然后创建通知或警报/自定义控制器。
application.applicationState == UIApplicationState.Active