Applying NSDiffableDataSourceSnapshot to UICollectionViewDiffableDataSource causes 'NSInternalInconsistencyException' - uicollectionview

I am trying to implement a UICollectionViewDiffableDataSource for my collectionView. My code compiles fine, however I keep running into this error the first time I apply a snapshot to it, with the following error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: self.supplementaryViewProvider || (self.supplementaryReuseIdentifierProvider && self.supplementaryViewConfigurationHandler)'
Here is my code:
var groups: [Group] = [Group]()
var dataSource: UICollectionViewDiffableDataSource<Section, Group>!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
self.groups = DummyData.groups
setupDataSource()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
performSearch(searchQuery: nil)
}
// MARK: - Helper Functions
func performSearch(searchQuery: String?) {
let filteredGroups: [Group]
if let searchQuery = searchQuery, !searchQuery.isEmpty {
filteredGroups = groups.filter { $0.contains(query: searchQuery) }
} else {
filteredGroups = groups
}
var snapshot = NSDiffableDataSourceSnapshot<Section, Group>()
snapshot.appendSections([.main])
snapshot.appendItems(filteredGroups, toSection: .main)
dataSource.apply(snapshot, animatingDifferences: true, completion: nil)
}
func setupDataSource() {
dataSource = UICollectionViewDiffableDataSource <Section, Group>(collectionView: collectionView) { (collectionView: UICollectionView, indexPath: IndexPath, group: Group) -> UICollectionViewCell? in
guard let cell = self.collectionView.dequeueReusableCell(
withReuseIdentifier: String(describing: MyGroupsCollectionViewCell.self), for: indexPath) as? MyGroupsCollectionViewCell else {
fatalError("Cannot create new cell") }
cell.configure(withGroup: group)
return cell
}
}
If needed, I can post the full call stack.

Found the answer. I was using the storyboard to create my collectionView and accidentally had the attribute for Section Header set to true. Because of this, the collectionView needed to pull the view for the section header for somewhere, but I never told it where, hence the
parameter not satisfying: self.supplementaryViewProvider || (self.supplementaryReuseIdentifierProvider && self.supplementaryViewConfigurationHandler)
Here's a good article I found on it for anyone in the future who runs into this issue:
https://medium.com/#jamesrochabrun/uicollectionviewdiffabledatasource-and-decodable-step-by-step-6b727dd2485

Related

Swift and #objc methods: How do I transform a method so that it can be represented by #objc?

As Swift is my first programming language and also seeing that I have no Objective C experience...
I'm having difficulty understanding #objc in relation to methods.
How do I use the #objc syntax to conform to my methods?
Is there another way to select a method without using the #selector syntax?
Here is the code that I'm having difficulty with(mainly the #objc attempt at the startGame method):
import UIKit
#objc class ViewController: UITableViewController {
var allWords = [String]()
var usedWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .add, target: self, action:
#selector(promptForAnswer))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New
Word", style: .plain, target: self, action: #selector(startGame))
if let startWordsURL = Bundle.main.url(forResource: "start",
withExtension: "txt") {
if let startWords = try? String(contentsOf: startWordsURL) {
allWords = startWords.components(separatedBy: "\n")
}
}
if allWords.isEmpty {
allWords = ["silkworm"]
}
#objc func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
{
startGame()
}
A few observations:
You do not need #objc in your view controller declaration.
The two action/selector methods should bear #objc qualifier.
I would suggest that you give these two methods descriptive names that clearly indicate that they are called when the user taps on a particular button, e.g.:
#objc func didTapNewWord(_ sender: UIBarButtonItem) {
...
}
#objc func didTapAdd(_ sender: UIBarButtonItem) {
...
}
Note, I also added a parameter to these methods. That makes it entirely unambiguous that they are button handlers. You do not need to do that, but now you can glance at the code and immediately grok what the method is for.
Obviously, you will change the code that adds these target actions accordingly:
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(didTapAdd(_:)))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New Word",
style: .plain,
target: self,
action: #selector(didTapNewWord(_:)))
Be careful with the placement of braces. Swift allows you to declare functions inside functions. So make sure that these selector methods are instance methods of the view controller, and not, for example, private functions declared inside another function (i.e. viewDidLoad).
If you start to lose track of the braces, you can select all the code in this file and press control+i (or in Xcode menus, “Editor” » “Structure” » “Re-Indent”). If you have missing braces somewhere, the re-indentation of the code will make this jump out at you.
So pulling that together, you get something like:
// ViewController.swift
import UIKit
class ViewController: UITableViewController {
var allWords = [String]()
var usedWords = [String]()
override func viewDidLoad() {
super.viewDidLoad()
configureButtons()
fetchData()
}
}
// MARK: - Actions
extension ViewController {
#objc func didTapNewWord(_ sender: UIBarButtonItem) {
startGame()
}
#objc func didTapAdd(_ sender: UIBarButtonItem) {
...
}
}
// MARK: - UITableViewDataSource
extension ViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
...
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
}
}
// MARK: - Private utility methods
private extension ViewController {
func configureButtons() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(didTapAdd(_:)))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "New Word",
style: .plain,
target: self,
action: #selector(didTapNewWord(_:)))
}
func fetchData() {
guard
let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt"),
let startWords = try? String(contentsOf: startWordsURL).components(separatedBy: "\n"),
!startWords.isEmpty
else {
allWords = ["silkworm"]
return
}
allWords = startWords.filter { !$0.isEmpty }
}
func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}
}
A few final observations on my code sample (not directly related to your question, but just to explain why structured it like I did):
I like to put methods into extensions, so that they are in logical groups. This makes it easier to follow what is going on at a glance. You can also collapse/expand these extensions so that while you are editing, you can focus on the relevant code.
The MARK comments just puts nice section headers in the Xcode jump bar, again, making it easier to jump about in one’s code.
I personally don't put anything in the action methods except a call to some method with the “business logic”. This separates the “view” code (the handling of the button) from the business logic. Some day, you may start using view models or presenter objects, so embracing this separation of responsibilities now will make that eventual transition easier. It will also make it easier to write unit tests when you get around to that (e.g. you write unit tests for the "start game" logic, not not the tapping of a button).
I think you have syntax error in the #objc method. It should be:
#objc
func functionName() {
}
for you it will be:
#objc
func startGame() {
title = allWords.randomElement()
usedWords.removeAll(keepingCapacity: true)
tableView.reloadData()
}

How do I check the currently loaded view controller ? (ObjC + Swift)

In my app I have a function where I want it to print something depending on the current view controller that is loaded. I do this by setting a global variable (Bool) and then toggling the flags in the view controller classes. From my main class I have something like this:
var FirstViewControllerisVisible: Bool = false
var SecondViewControllerisVisible: Bool = false
var ThirdViewControllerisVisible: Bool = false
#objc func PlayAgainfunc(_ sender: Any) {
if counter % 15 == 0 {
if FirstViewControllerisVisible == true {
print("First View Controller is visible")
} else if SecondViewControllerisVisible == true {
print("Second View Controller is visible")
} else if ThirdViewControllerisVisible == true {
print("Third View Controller is visible")
}
}
counter += 1
}
Then, in those classes I can set the flags like this:
override func viewDidAppear(_ animated: Bool) {
FirstViewControllerisVisible = true
}
override func viewDidDisappear(_ animated: Bool) {
FirstViewControllerisVisible = false
}
This worked great when it was exclusively Swift, but the problem with global variables is that they can't be accessed by Objective-C. I can't find a way to set flags in my ObjC classes and then check if true or false. For instance, If I tried:
- (void)viewDidAppear:(BOOL)animated; {
[(FirstViewControllerisVisible) == true];
}
- (void)viewDidDisappear:(BOOL)animated; {
[(FirstViewControllerisVisible) == false];
}
I would get the error 'use of undeclared identifier' because my global vars declared in Swift are Swift only.
After the view controller has loaded, you can
if let viewController = UIApplication.shared.keyWindow?.rootViewController {
print(type(of: viewController))
}
add below mentioned extension. you will get the desired result.
extension UIApplication {
/// will return currently showing view controller
static var topMostViewController: UIViewController? {
return UIApplication.shared.keyWindow?.rootViewController?.visibleViewController
}
}
extension UIViewController {
/// The visible view controller from a given view controller
var visibleViewController: UIViewController? {
if let navigationController = self as? UINavigationController {
return navigationController.topViewController?.visibleViewController
} else if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.visibleViewController
} else if let presentedViewController = presentedViewController {
return presentedViewController.visibleViewController
} else {
return self
}
}
}
and access it like:
let viewController = UIApplication.topMostViewController
Happy Coding

How to differentiate new and previous notifications

I have an API that returns notifications if any activity in account. I am working first time with notifications. I am displaying these notifications in to UITableView. If user clicks on any notification from the table it redirects to the referral view and delete that notification from the Table list.
Now what I want is, if user leave the notification view with for example 4 notification listed and if 2 new notifications are added to the API then those 2 should have grey background colour and other 4 should have white background colour when user returns to the notificationView.
It is all coming from same API so I am very confuse how to accomplish this result. Its kind of Facebook notifications you can say. Do I need to make any changes to API side which can indicate me if any new notifications are added or is there anything else I am missing ? I know there is push notifications available but I am not using it here. Will it solve the issue if I use it? I am very confused. Please, any suggestion will be much appreciated.
Update: Here is my code :
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
}
Well, since there is no API to support this, you cannot have this info cross device / multiscreen (if a user will open the notification in one device you will not be able to tell this this on another device without some other form communicating).
Need to save the info for a future app session
You can use UserDefaults.standard to save the state for a future session on the same device.
Create a notificationsStatus dictionary with the format [Id:read]. Read it when starting a new session and write in it the new updates statuses.
Save:
var notificationsStatus = ["101":true,"102":false]
let defaults:UserDefaults = UserDefaults.standard
defaults.set(notificationsStatus, forKey: "notifications")
Read:
notificationsStatus = defaults.value(forKey: "notifications")
and then use the read/unread to color the cells accordingly
Need to save the info for the same session
Use some structure where you save the state of a notification.
This can be done in multiple ways but the main idea is to create an object that doesn't get deallocated when leaving the controller and manipulate the date in it.

Cannot Import Protocol from Sinch Framework - SinRegionInfo

I have a project that I have built where I am trying to include the sinch framework for making SMS verification. I added Sinch to the project VIA cocoapods, and also by manually adding the folder/framework to my xcode file system.
The problem i'm having right now is that my version of the CountrySelectionViewController.swift cannot access the SinRegionInfo protocol defined inside of the Sinch framework... i'm not sure what is going wrong. An example of the code/error inside CountrySelectionViewController.swift is here:
var entries: Array<SINRegionInfo> = []; ---> Use of undeclared type 'SinRegionInfo'
The strange part is that everything seems to be the same in my project as it is in the sample project, but in the sample project, there is no problem accessing the protocol.
CountrySelectionViewController.swift
import UIKit
import SinchVerification
class CountrySelectionViewController : UITableViewController {
var isoCountryCode: String?
var onCompletion: ((String) -> Void)?
var entries: Array<SINRegionInfo> = [];
override func viewDidLoad() {
super.viewDidLoad();
let regionList = PhoneNumberUtil().regionList(forLocale: Locale.current);
entries = regionList.entries.sorted(by: { (a: SINRegionInfo, b: SINRegionInfo) -> Bool in
return a.countryDisplayName < b.countryDisplayName;
})
}
override func viewWillAppear(_ animated: Bool) {
let row = entries.index { (region: SINRegionInfo) -> Bool in
return region.isoCountryCode == isoCountryCode;
}
if row != nil {
tableView.selectRow(at: IndexPath.init(row: Int(row!), section: 0), animated: animated, scrollPosition: .middle);
}
}

Create and Respond to a Hyperlink within a NSTableView Text Cell

I have a program that has a NSTableView populated with files to be uploaded. Once the file is sent, the Text Cell with the file's name gets a hyperlink placed into it (the array data is given an NSMutableString with an NSLinkAttributeName attribute). How do I allow users to click this link to open the webpage in their default browser?
After much searching and trying multiple methods, this is what I came up with as a solution.
Creating a custom class that extends NSTableViewCell:
class TableViewCellCursor: NSTableCellView {
internal var active = false
//MARK: - View Life Cycle
override func awakeFromNib() {
superview?.awakeFromNib()
self.createTrackingArea()
}
//MARK: - IBActions
override func mouseEntered(theEvent: NSEvent) {
if (NSCursor.currentCursor() == NSCursor.arrowCursor() && active) {
NSCursor.pointingHandCursor().set()
}
}
override func mouseExited(theEvent: NSEvent) {
if (NSCursor.currentCursor() == NSCursor.pointingHandCursor() && active) {
NSCursor.arrowCursor().set()
}
}
//Informs the receiver that the mouse cursor has moved into a cursor rectangle.
override func cursorUpdate(event: NSEvent) {
if (active) {
NSCursor.pointingHandCursor().set()
}
}
//MARK: - Util
func createTrackingArea() {
var focusTrackingAreaOptions:NSTrackingAreaOptions = NSTrackingAreaOptions.ActiveInActiveApp
focusTrackingAreaOptions |= NSTrackingAreaOptions.MouseEnteredAndExited
focusTrackingAreaOptions |= NSTrackingAreaOptions.AssumeInside
focusTrackingAreaOptions |= NSTrackingAreaOptions.InVisibleRect
var focusTrackingArea:NSTrackingArea = NSTrackingArea(rect: NSZeroRect,
options: focusTrackingAreaOptions,
owner: self, userInfo: nil)
self.addTrackingArea(focusTrackingArea)
}
}
Checking first responder status when the NSTableView selection changes. This is necessary because the table's selection can be changed, even when it is not the firstResponder:
func tableViewSelectionDidChange(aNotification: NSNotification) {
if (self.firstResponder == filesToTransferTable) {
changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
} else {
changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
}
}
func changeSelectedRowTextColorTo(selectedColor: NSColor, unselectedColor: NSColor) {
let selectedRows = filesToTransferTable.selectedRowIndexes
for (index, tableEntry) in enumerate (tableData) {
if tableData[index]["FileName"] is NSMutableAttributedString {
var name = tableData[index]["FileName"] as! NSMutableAttributedString
var range = NSMakeRange(0, NSString(string:name.string).length)
name.beginEditing()
name.removeAttribute(NSForegroundColorAttributeName, range: range)
if (selectedRows.containsIndex(index)) {
name.addAttribute(NSForegroundColorAttributeName, value:selectedColor, range:range)
} else {
name.addAttribute(NSForegroundColorAttributeName, value:unselectedColor, range:range)
}
name.endEditing()
tableData[index]["FileName"] = name
}
filesToTransferTable.reloadDataForRowIndexes(NSIndexSet(index: index), columnIndexes: NSIndexSet(index:0))
}
}
Adding KVO for checking when FirstResponder changes:
//This is somewhere in your code where you initialize things
//KVO for first responder behavior regarding tableView and updating attributedStrings' colors
self.addObserver(self, forKeyPath: "firstResponder", options: NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, context: nil)
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (change[NSKeyValueChangeNewKey] is NSTableView) {
changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
} else if (change[NSKeyValueChangeOldKey] is NSTableView) {
changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
}
}
Finally, checking if the main window (the app itself) is in focus (if this is not done, then the colors won't change appropriately when the window loses focus):
//Put these in the same place as the KVO code
NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidBecomeKey:",
name: NSWindowDidBecomeKeyNotification , object: self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "windowDidResignKey:",
name: NSWindowDidResignKeyNotification , object: self)
func windowDidBecomeKey(notification: NSNotification) {
if (self.firstResponder == filesToTransferTable) {
changeSelectedRowTextColorTo(NSColor.whiteColor(), unselectedColor: NSColor.blueColor())
} else {
changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
}
}
func windowDidResignKey(notification: NSNotification) {
if (self.firstResponder == filesToTransferTable) {
changeSelectedRowTextColorTo(NSColor.blackColor(), unselectedColor: NSColor.blueColor())
}
}
Text fields automatically support clicking on embedded links, but only if they are at least selectable (if not editable). So, set your text field to be selectable.