Skip to content

Commit

Permalink
Swift cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
nkalupahana committed Jan 18, 2025
1 parent 3ad0afc commit 4850665
Showing 1 changed file with 29 additions and 30 deletions.
59 changes: 29 additions & 30 deletions ios/App/Widgets/StreakWidget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
// Created by Nisala on 1/14/25.
//

import WidgetKit
import SwiftUI
import WidgetKit

enum Danger: Int, Decodable {
case journaledToday = 0
Expand All @@ -26,7 +26,7 @@ struct StreakResponse: Decodable {

struct Provider: TimelineProvider {
let userDefaults = UserDefaults.init(suiteName: "group.app.getbaseline.baseline")!

func getAPIKey() -> String? {
if let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist") {
if let plistContent = NSDictionary(contentsOfFile: path) as? [String: Any] {
Expand All @@ -35,24 +35,23 @@ struct Provider: TimelineProvider {
}
return nil
}

func getIdToken(completion: @escaping (Result<TokenResponse, Error>) -> Void) {
guard let apiKey = getAPIKey() else {
completion(.failure(NSError(domain: "NoApiKey", code: -4)))
return
}

let url = URL(string: "https://securetoken.googleapis.com/v1/token?key=\(apiKey)")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")


guard let refreshToken = userDefaults.string(forKey: "refreshToken") else {
completion(.failure(NSError(domain: "NoData", code: -3)))
return
}

let bodyData = "grant_type=refresh_token&refresh_token=\(refreshToken)"
request.httpBody = bodyData.data(using: .utf8)

Expand All @@ -61,12 +60,12 @@ struct Provider: TimelineProvider {
completion(.failure(error))
return
}

guard let data = data else {
completion(.failure(NSError(domain: "NoData", code: -2)))
return
}

do {
let response = try JSONDecoder().decode(TokenResponse.self, from: data)
completion(.success(response))
Expand All @@ -78,48 +77,48 @@ struct Provider: TimelineProvider {

task.resume()
}

func getISODate() -> String {
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone.current
let isoDateString = dateFormatter.string(from: currentDate)

return isoDateString
}

func postStreakRequest(idToken: String, completion: @escaping (Result<StreakResponse, Error>) -> Void) {
var request = URLRequest(url: URL(string: "https://api.getbaseline.app/streak")!)
request.httpMethod = "POST"

// Add the Authorization header
request.setValue("Bearer \(idToken)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

guard let keys = userDefaults.string(forKey: "keys") else {
completion(.failure(NSError(domain: "NoKeys", code: -14)))
return
}

let body: [String: String] = [
"currentDate": getISODate(),
"keys": keys
"keys": keys,
]

do {
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
} catch {
completion(.failure(NSError(domain: "JSON serialization error: \(error)", code: -13)))
return
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(NSError(domain: "Error making POST request: \(error)", code: -12)))
return
}

if let data = data {
do {
let response = try JSONDecoder().decode(StreakResponse.self, from: data)
Expand All @@ -130,16 +129,15 @@ struct Provider: TimelineProvider {
}
}
}

task.resume()
}


func placeholder(in context: Context) -> Entry {
Entry(date: Date(), streak: 25, danger: Danger.noRecovery, error: false)
}

func getSnapshot(in context: Context, completion: @escaping (Entry) -> ()) {
func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) {
if context.isPreview {
completion(placeholder(in: context))
} else {
Expand All @@ -148,13 +146,14 @@ struct Provider: TimelineProvider {
case .success(let response):
postStreakRequest(idToken: response.id_token) { result in
switch result {
case .success(let response):
completion(Entry(date: Date(), streak: response.streak, danger: response.danger, error: false))
case .failure(let error):
print(error)
completion(Entry.errorEntry())
case .success(let response):
completion(
Entry(date: Date(), streak: response.streak, danger: response.danger, error: false))
case .failure(let error):
print(error)
completion(Entry.errorEntry())
}

}
case .failure(let error):
print(error)
Expand All @@ -164,7 +163,7 @@ struct Provider: TimelineProvider {
}
}

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
var entries: [Entry] = []
let currentDate = Date()
let refreshDate = Calendar.current.date(byAdding: .minute, value: 30, to: currentDate)!
Expand All @@ -181,13 +180,13 @@ struct Entry: TimelineEntry {
let streak: Int
let danger: Danger
let error: Bool

static func errorEntry() -> Entry {
return Entry(date: Date(), streak: 0, danger: .noRecovery, error: true)
}
}

struct StreakWidgetEntryView : View {
struct StreakWidgetEntryView: View {
var entry: Provider.Entry

var body: some View {
Expand Down

0 comments on commit 4850665

Please sign in to comment.