在我的应用程序中,我需要根据购物车项目数量显示徽章值,并且我在视图控制器中实现了以下行,我使用JSON和徽章值来获得数据每当显示视图控制器时都不会加载,并且在删除后不更新值,并且徽章值在应用程序开始时没有显示,因为我是Swift 3的新手,我不在哪里实施,任何人都可以帮助我如何清除问题 ?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
// print(jsonObj!.value(forKey: "Detail"))
self.itemsArray = (jsonObj!.value(forKey: "Detail") as? [[String: AnyObject]])!
print(self.itemsArray.count)
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
let key = "productPrice"
for array in self.itemsArray{
if let value = array[key] {
let cart = String(describing: value)
let endIndex = cart.index(cart.endIndex, offsetBy: -2)
let truncated = cart.substring(to: endIndex)
self.totalcartPrice.append(truncated)
print(self.totalcartPrice)
var sum = 0.00
for numbers in self.totalcartPrice{
sum += Double(numbers)!
}
print(sum)
self.increment = Int(sum)
self.total = String(sum) + "0KD"
let tabItems = self.tabBarController?.tabBar.items as NSArray!
let tabItem = tabItems?[1] as! UITabBarItem
self.appDelegate.badgeValue = String(Int(self.itemsArray.count))
}
}
})
}
}).resume()
}
func deleteButtonAction(button : UIButton) {
let buttonPosition = button.convert(CGPoint(), to: tableDetails)
let index = tableDetails.indexPathForRow(at: buttonPosition)
self.itemsArray.remove(at: (index?.row)!)
self.tableDetails.deleteRows(at: [index!], with: .automatic)
tableDetails.reloadData()
let tabItems = self.tabBarController?.tabBar.items as NSArray!
let tabItem = tabItems?[1] as! UITabBarItem
self.appDelegate.badgeValue = String(Int(self.itemsArray.count))
if (tableView(tableDetails, numberOfRowsInSection: 0) == 0){
tableDetails.isHidden = true
emptyView.isHidden = false
}
}
您需要让rootviewController从AppDelegate更新徽章。像这样
let rootViewController = self.window?.rootViewController as!UITabBarController!
let tabArray = rootViewController?.tabBar.items as NSArray!
let tabItem = tabArray.objectAtIndex(1) as! UITabBarItem
tabItem.badgeValue = "34"