如何区分新的和以前的通知

时间:2017-09-21 14:40:15

标签: api swift3 notifications

我有一个API,如果帐户中有任何活动,则返回通知。我第一次收到通知。我将这些通知显示在UITableView中。如果用户单击表中的任何通知,它将重定向到引用视图并从表列表中删除该通知。

现在我想要的是,如果用户离开通知视图时列出了例如4通知,并且如果向API添加了2个新通知,那么那些2应该具有灰色背景颜色而其他4应该具有白色背景颜色当用户返回时到notificationView。

这一切都来自相同的API,所以我很困惑如何完成这个结果。你可以说它的Facebook通知类型。我是否需要对API端进行任何更改,这可以指示我是否添加了任何新通知,还是我还缺少其他任何内容?我知道有可用的推送通知,但我在这里没有使用它。如果我使用它会解决问题吗?我很迷茫。请提出任何建议。

更新:这是我的代码:

struct UserNotification {

    let id : Int?
    let timeStamp : String?
    let message : String?

    init(json:[String:Any]) {
        self.id = (json["Id"] as? Int)
        self.timeStamp = (json["TimeStamp"] as? String)
        self.message = (json["Message"] as? String)
    }
}

var notificationsArray : [UserNotification] = []

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.FetchNotifications()
}

func FetchNotifications(){


        URLSession.shared.dataTask(with: jsonUrlString!) { (data, response, error) in

            guard let data = data else { return }

            do {
                if let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {

                    self.notificationsArray.removeAll()
                    for notifications in jsonData {
                        let details = UserNotification(json: notifications)
                        self.notificationsArray.append(details)
                    } 
                }
            } catch {
                print(error.localizedDescription)
            }
            if (response as? HTTPURLResponse) != nil  {
                DispatchQueue.main.async {

                    self.notificationTableView.reloadData()
                }
            }
        }.resume()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let Cell = self.notificationTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomNotificationCell
//        Cell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)

    let temp = notificationsArray[indexPath.item]
    // Setting id, time and message to labels 

}

1 个答案:

答案 0 :(得分:0)

好吧,既然没有API可以支持这一点,你就不能让这个信息跨设备/多屏幕(如果用户在一台设备上打开通知,你将无法在没有其他形式的其他设备上告诉这个通信)。

需要保存以后的应用会话信息

您可以使用UserDefaults.standard在同一台设备上保存以后会话的状态。 创建格式为notificationsStatus的{​​{1}}字典。在开始新会话时读取它并在其中写入新的更新状态。

保存:

[Id:read]

读:

var notificationsStatus = ["101":true,"102":false]
let defaults:UserDefaults = UserDefaults.standard
defaults.set(notificationsStatus, forKey: "notifications")

然后使用read / unread相应地为单元格着色

需要保存同一会话的信息

使用一些保存通知状态的结构。 这可以通过多种方式完成,但主要思想是创建一个在离开控制器并操纵其中的日期时不会被释放的对象。