-2

I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

struct SocketEventHandler {
    let event: String
    let id: UUID
    let callback: NormalCallback

    func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) {
        callback(items, SocketAckEmitter(socket: socket, ackNum: ack))
    }
}


let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray)")
        AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])")
        let response  = dataArray[0] as! Dictionary<String, Any> **// APP CRASHES ON THIS LINE**
}

Response :-

[
    {
        "status": "A",
        "acceptorId": 126,
        "id": 94,
        "createdAt": "2017-06-05T09:50:42.000Z",
        "updatedAt": "2017-06-05T09:52:26.000Z",
        "userId": 126,
        "friendId": 401
    }
]

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

Scorpion
  • 6,831
  • 16
  • 75
  • 123

2 Answers2

2

May be you are having 2d array means the elements of dataArray are also Array not Dictionary.

if let response = dataArray[0] as? [[String: Any]], let dictionary = response.first {

    print(dictionary["status"])
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
2

Make a breakpoint on sentence crashes, and then use following command to check what exactly the dataArray is:

po print(dataArray)
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33