Reputation: 1014
I am trying to use Swift to create a reference to an image and storing it in documents using a dictionary and JSON. I believe that I created the correct syntax for dictionary based on another SO answer that I found. The error message below happens when I press the button with function addButtonClicked
. What am i doing wrong?
Error message:
Invalid (non-string) key in JSON dictionary
// Inside UICollectionViewCell
var representedAssetIdentifier: String? = nil
// Inside UIViewController
var count: Int = 0
var dictionary: [Int:String] = [:]
@objc func addButtonClicked() {
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")
try JSONSerialization.data(withJSONObject: dictionary).write(to: fileURL)
} catch {
print("Error report: \(error.localizedDescription)")
}
let newViewController = PickerTest3()
self.navigationController?.pushViewController(newViewController, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? ImageCell {
let newCount = count
dictionary.updateValue(cell.representedAssetIdentifier!, forKey: newCount)
count += 1
selectedCells.append(indexPath)
cell.index = selectedCells.count
}
}
Upvotes: 1
Views: 1422
Reputation: 236260
The error message is pretty clear. You can not create a JSON string using a dictionary that has integer keys. You need to use strings.
Note: Not related to your question but you should not write any file directly to the application support directory:
Use this directory to store all app data files except those associated with the user’s documents. For example, you might use this directory to store app-created data files, configuration files, templates, or other fixed or modifiable resources that are managed by the app. An app might use this directory to store a modifiable copy of resources contained initially in the app’s bundle. A game might use this directory to store new levels purchased by the user and downloaded from a server. All content in this directory should be placed in a custom subdirectory whose name is that of your app’s bundle identifier or your company. In iOS, the contents of this directory are backed up by iTunes and iCloud.
Upvotes: 2