fix: Rework init to avoid crash when server returns null values

This commit is contained in:
Andrea Busi
2025-04-25 22:31:44 +02:00
parent 471ccc9e4a
commit fa05d6b5c4
2 changed files with 26 additions and 6 deletions
@@ -61,8 +61,14 @@
- (void)scaricaDatiReteSmartphone
{
[[ServerRequest defaultServerConnectionSingleton] inviaInformazioniAlServerWithURL:[NSURL URLWithString:EQNServerUrlDownloadSmartphoneNetwork] richiesta:EQNTipoChiamataDownloadDati success:^(id result) {
self.rete_smartphone = [[EQNReteSmartphone alloc] initWithInfo:result];
// Parsiamo la risposta (assicurandoci che non contenga valori nulli)
EQNReteSmartphone *rete = [EQNReteSmartphone fromResponse:result];
if (rete != nil) {
self.rete_smartphone = rete;
} else {
NSLog(@"[EQNManager] Impossibile parsare la risposta di DownloadSmartphoneNetwork");
}
[self performSelectorOnMainThread:@selector(scaricaAreaCheck) withObject:nil waitUntilDone:YES];
} failure:^(NSError * error) {
@@ -21,13 +21,27 @@ class EQNReteSmartphone: NSObject {
let top10kAvailable: Int
let top100kAvailable: Int
// MARK: - Class
// Sometimes the response returns a broken response, with all values to null.
// In order to avoid crashes due to ObjC-Swift bridging, we need to take a generic nullable object,
// and then cast to the expected type (a dictionary).
@objc static func from(response: Any?) -> EQNReteSmartphone? {
if let info = response as? [[String: Any]?] {
return .init(info: info)
}
return nil
}
// MARK: - Init
@objc init(info: [[String: Any]]) {
private init(info: [[String: Any]?]) {
// merge array in a single dictionary
let allValues = info.reduce([:]) { (result, dictionary) -> [String: Any] in
return result.merging(dictionary, uniquingKeysWith: { (_, new) in new })
}
let allValues = info
.compactMap { $0 }
.reduce([:]) { (result, dictionary) -> [String: Any] in
return result.merging(dictionary, uniquingKeysWith: { (_, new) in new })
}
self.counterLastDayAlerts = allValues.integer(forKey: "eq", orDefault: 0)
self.counterTotalAlerts = allValues.integer(forKey: "eq_p", orDefault: 0)