无法在Swift 5中解析ISO日期

时间:2019-12-03 20:21:19

标签: swift date decode

我正在尝试在Swift 5.1中解码从我的Node.JS后端发送的日期,但似乎无法修复它。我创建了一个JSONDecoder(),将其dateDecodingStrategy设置为.iso8601,但仍然给我以下错误:

  

由于数据格式不正确,因此无法读取。 (localizedDescription)

这是我要解析的请求

{ 
   "parties":[ 
      { 
         "location":{ 
            "type":"Point",
            "coordinates":[ 
               50.92,
               4.0587
            ]
         },
         "participants":[ 
            "5db8838eaffe445c66076a88"
         ],
         "declines":[ 

         ],
         "_id":"5dd0264902611d001e968396",
         "name":"DnD: Into the Abyss",
         "date":"2020-03-13T00:00:00.000Z",
         "maxSize":3,
         "gameId":"5dd0229102611d001e968392",
         "createdAt":"2019-11-16T16:39:37.878Z",
         "updatedAt":"2019-11-16T16:39:37.878Z",
         "__v":0
      }
   ]
}

代码

    func getPartiesNearYou(maxDistance: Int, userId: String, latitude: Double, longitude: Double) {
        let urlString = "\(url)getPartiesNearYou?distance=\(maxDistance)&lat=\(latitude)&long=\(longitude)&userId=\(userId)"
        print("URL", urlString)
        performRequest(with: urlString) {data, response, error in
            if error != nil {
                self.delegate?.didFail(with: error!)
                return
            }

            if let safeData = data {
                let decoder = JSONDecoder()
                    decoder.dateDecodingStrategy = .iso8601
                do {
                    let decodedContainer = try decoder.decode(PartiesNetworkContainer.self, from: safeData)
                    self.delegate?.updateParties(self, decodedContainer.parties)
                } catch {
                    self.delegate?.didFail(with: error)
                }
            }
        }
    }

聚会结构

public struct Party: Codable {

    var _id: String?
    var name: String
    var date: Date
    var maxSize: Int = 4
    var participants: [String]
    var gameId: String
    var location: Location
    var declines: [String]

    init(id _id:String?, name: String, date: Date, maxSize: Int, participants: [String], gameId: String, location: Location, declines: [String]) {
        self._id = _id
        self.name = name
        self.date = date
        self.maxSize = maxSize
        self.participants = participants
        self.gameId = gameId
        self.location = location
        self.declines = declines
    }

}

0 个答案:

没有答案