Untitled

mail@pastecode.io avatar
unknown
swift
3 years ago
2.8 kB
1
Indexable
Never
struct HotspotTimelineProvider: TimelineProvider {
    
    typealias Entry = HotspotTimelineEntry
    let service = Service.shared
    
    func placeholder(in context: Context) -> HotspotTimelineEntry {
        HotspotTimelineEntry.placeholder 
    }
    
    func getSnapshot(in context: Context, completion: @escaping (HotspotTimelineEntry) -> Void) {
        if context.isPreview {
            completion(HotspotTimelineEntry.placeholder)
        } else {
            fetchData { result in
                switch result {
                case .success(let entry):
                    completion(entry)
                     
                case .failure(_):
                    completion(HotspotTimelineEntry.placeholder)
                }
            }
        }
    }
    func getTimeline(in context: Context, completion: @escaping (Timeline<HotspotTimelineEntry>) -> Void) {
        fetchData { result in
            switch result {
            case .success(let entry):
                let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 10)))
                completion(timeline)
            case .failure(_):
                let timeline = Timeline(entries: [HotspotTimelineEntry.placeholder], policy: .after(Date().addingTimeInterval(60 * 2)))
                completion(timeline)
            }
        }
    }
    
    private func fetchData(completion: @escaping (Result<HotspotTimelineEntry, Error>) -> ()) {
        service.fetchRequest(APIKey: "1v5a755imf0n24hqjkgspk18b582soa74fmy981tmrhkluhfhm", SerialNumber: "110991628214200969") { result in
            switch result {
            case .success(let heliumData):
                let entry = HotspotTimelineEntry(date: Date(), hotspots: .init(connected: heliumData.data?.connected, dialable: heliumData.data?.dialable, ipPublic: heliumData.data?.ipPublic, ipEthLocal: heliumData.data?.ipEthLocal, ipWifiLocal: heliumData.data?.ipWifiLocal, syncList: heliumData.data?.syncList, p2PAddress: heliumData.data?.p2PAddress, blockStatus: heliumData.data?.blockStatus, uptime: heliumData.data?.uptime, relay: heliumData.data?.relay, sn: heliumData.data?.sn, address: heliumData.data?.address, heliumOnline: heliumData.data?.heliumOnline, name: heliumData.data?.name, owner: heliumData.data?.owner, p2PAddressUpdateAt: heliumData.data?.p2PAddressUpdateAt, producedAt: heliumData.data?.producedAt, version: heliumData.data?.version, sdPercentage: heliumData.data?.sdPercentage, synced: heliumData.data?.synced, online: heliumData.data?.online, isHealth: heliumData.data?.isHealth, relayed: heliumData.data?.relayed, networkStatus: heliumData.data?.networkStatus))
            case .failure(let error):
                completion(.failure(error))
                
            }
        }
    }
}