0

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
      }
  }
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Part_Time_Nerd
  • 994
  • 7
  • 26
  • 56

1 Answers1

2

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.

File System Basics

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • That is what I thought the error message was saying, but in the link that I posted with my OP there are numerous examples of people using the [Int:String] combination. How are they able to do it? – Part_Time_Nerd Nov 12 '20 at 17:14
  • You can create a dictionary in Swift with any key that conforms to `Hashable` protocol but you can not create a JSON from it unless you convert the keys from `Int` to `String`. I would also add a character prefix such as `"k1"`, `"k2"` and so on. – Leo Dabus Nov 12 '20 at 17:18