Last active
March 3, 2021 08:15
-
-
Save treastrain/59785f0e7b625c893766dad860adaf0c to your computer and use it in GitHub Desktop.
【SwiftUI & Kronos】NTP から時刻を取得し端末の設定によらず正しい Date を得る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// Shared | |
// | |
// Created by treastrain on 2021/03/03. | |
// | |
import SwiftUI | |
import Kronos | |
@main | |
struct testApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView().environmentObject(ContentViewHolder()) | |
} | |
} | |
} | |
class ContentViewHolder: ObservableObject { | |
private var timer: Timer! | |
private let formatter = DateFormatter() | |
@Published var timeStr = "時間を表示します…" | |
init() { | |
Clock.sync(from: "ntp.nict.jp") | |
self.formatter.locale = Locale(identifier: "ja_JP") | |
self.formatter.dateStyle = .medium | |
self.formatter.timeStyle = .medium | |
self.timer?.invalidate() | |
self.timer = Timer.scheduledTimer(timeInterval: 1/60, target: self, selector: #selector(self.tick), userInfo: nil, repeats: true) | |
} | |
@objc | |
func tick() { | |
if let date = Clock.now { | |
self.timeStr = self.formatter.string(from: date) | |
} | |
} | |
} | |
struct ContentView: View { | |
@EnvironmentObject var holder: ContentViewHolder | |
var body: some View { | |
Text(holder.timeStr) | |
.font(Font.body.monospacedDigit()) | |
.padding() | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment