Untitled

mail@pastecode.io avatar
unknown
swift
2 years ago
5.4 kB
7
Indexable
Never
// khai bao cac struct
struct ChartPriceObject : Decodable{
  var bid:String; //string or double
}


struct ChartObject : Decodable{
  var price: String;  // string or double
  var chart : [ChartPriceObject];
  var change: Double;
}

struct ObjectData : Decodable{
  var name: String //fullName token
  var symbol: String //code token
  var chart: ChartObject
}

struct Response : Decodable{
  var status: Int;
  var data: [ObjectData];
}


var fakeData: [ObjectData] = [
  ObjectData(name:"Bitcoin",symbol: "BTC",chart:ChartObject(price: "47534.24961000", chart: [ChartPriceObject(bid:"100000")], change: 0.0135301449169416)),
  ObjectData(name:"Ethereum",symbol: "ETH",chart:ChartObject(price: "3365.41788000", chart: [], change: 0.07247405701859577)),
  ObjectData(name:"Binance Coin",symbol: "BNB",chart:ChartObject(price: "437.82705000", chart: [], change: 0.058723610774083834)),
  ObjectData(name:"XRP",symbol: "XRP",chart:ChartObject(price: "0.87274395", chart: [], change:0.04846292947558761)),
  ObjectData(name:"Cardano",symbol: "ADA",chart:ChartObject(price: "1.19617200", chart: [], change: 0.0748422001803426)),
  ObjectData(name:"Solana",symbol: "SOL",chart:ChartObject(price: "1.19617200", chart: [], change: 0.11378754283410597))
]
var responeDefault = Response(status: 200, data: []);



struct Provider: IntentTimelineProvider {
  //data truoc khi call api
  func placeholder(in context: Context) -> SimpleEntry {
    SimpleEntry(date: Date(), configuration: ConfigurationIntent(), data: [], isPreview: true)
  }
  //data call api with preview
  func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ())  {
    
    let urlString = "https://api.invest.vndc.io/api/v1/currency?query=top100&hasChart=true&userId=6277729709709442974&limit=6&baseCurrency=USDT"
    let url = URL(string: urlString)!
    let header = [
      "Content-Type": "application/json",
      "Accept": "application/json",
    ]
    let urlRequest = NSMutableURLRequest(url: url)
    urlRequest.httpMethod = "GET"
    urlRequest.allHTTPHeaderFields = header
    let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { data, urlResponse, error in
      
      if error != nil {
        // OH NO! An error occurred...
        let entry = SimpleEntry(date: Date(), configuration: configuration, data:fakeData, isPreview: true)
        completion(entry)
        return
      }
      do {
        let json = try JSONDecoder().decode(Response.self, from: data!);
        let entry = SimpleEntry(date: Date(), configuration: configuration, data:json.data, isPreview: false)
        completion(entry)
      } catch {
        //json error
        let entry = SimpleEntry(date: Date(), configuration: configuration, data:fakeData, isPreview: false)
        completion(entry)
        return
      }
    }
    task.resume();
    
  }
  //data call interval
  func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
    var entries: [SimpleEntry] = [];
    let entryDate = Date();
    let afterValue = Calendar.current.date(byAdding: .minute,value: 1, to: Date())!;
    
    let urlString = "https://api.invest.vndc.io/api/v1/currency?query=top100&hasChart=true&userId=6277729709709442974&limit=6&baseCurrency=USDT"
    let url = URL(string: urlString)!
    let header = [
      "Content-Type": "application/json",
      "Accept": "application/json",
    ]
    let urlRequest = NSMutableURLRequest(url: url)
    urlRequest.httpMethod = "GET"
    urlRequest.allHTTPHeaderFields = header
    let task = URLSession.shared.dataTask(with: urlRequest as URLRequest) { data, urlResponse, error in
      
      if error != nil {
        // OH NO! An error occurred...
        let entry = SimpleEntry(date: entryDate, configuration: configuration, data:fakeData, isPreview: true)
        entries.append(entry)
        let timeline = Timeline(entries: entries, policy: .after(afterValue));
        completion(timeline)
        return
      }
      do {
        let json = try JSONDecoder().decode(Response.self, from: data!);
        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
        let _data = jsonObj["data"] as? [[String: Any]] ?? []
        let objName = _data[0]["name"];
        
        
        let entry = SimpleEntry(date: entryDate, configuration: configuration, data: json.data, isPreview: false)
        entries.append(entry)
        let timeline = Timeline(entries: entries, policy: .after(afterValue));
        completion(timeline)
      } catch {
        //json error
        let entry = SimpleEntry(date: entryDate, configuration: configuration, data:fakeData, isPreview: true)
        entries.append(entry)
        let timeline = Timeline(entries: entries, policy: .after(afterValue));
        completion(timeline)
        return
      }
    }
    task.resume();
  }
}

func formatDataModel(data: [[String: Any]])-> [ObjectData]{
  let result = [ObjectData]();
//  for i in data{
//    let name = i["name"] as? String;
//    let symbol = i["symbol"] as? String;
//    let price = i.chart.price as? String;
//    let change = i["chart"]["change"] as? Double;
//    var obj = ObjectData(name: name! , symbol: symbol!, chart: ChartObject(price: price!, chart: [], change: change!));
//    result.append(obj)
//  }
  return result
  
}