134 lines
5.1 KiB
Swift
134 lines
5.1 KiB
Swift
import CoreLocation
|
||
import Flutter
|
||
import UIKit
|
||
|
||
@main
|
||
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
||
private let location = OneShotLocation()
|
||
|
||
override func application(
|
||
_ application: UIApplication,
|
||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
||
) -> Bool {
|
||
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||
}
|
||
|
||
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
||
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "SfzenithFiles") {
|
||
let channel = FlutterMethodChannel(name: "sfzenith/files", binaryMessenger: registrar.messenger())
|
||
channel.setMethodCallHandler { call, result in
|
||
guard call.method == "saveToDownloads" else {
|
||
result(FlutterMethodNotImplemented)
|
||
return
|
||
}
|
||
let args = call.arguments as? [String: Any] ?? [:]
|
||
let name = (args["name"] as? String) ?? "horizon.bin"
|
||
let bytes = (args["bytes"] as? FlutterStandardTypedData)?.data ?? Data()
|
||
do {
|
||
result(try AppDelegate.saveToDocuments(name: name, data: bytes))
|
||
} catch {
|
||
result(FlutterError(code: "save_failed", message: error.localizedDescription, details: nil))
|
||
}
|
||
}
|
||
}
|
||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "SfzenithLocation") {
|
||
let channel = FlutterMethodChannel(name: "sfzenith/location", binaryMessenger: registrar.messenger())
|
||
channel.setMethodCallHandler { [location] call, result in
|
||
guard call.method == "getLocation" else {
|
||
result(FlutterMethodNotImplemented)
|
||
return
|
||
}
|
||
location.request(result)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Saves into the app's Documents folder, which the Files app shows under
|
||
/// On My iPhone › SkyContour (UIFileSharingEnabled). Never overwrites.
|
||
static func saveToDocuments(name: String, data: Data) throws -> String {
|
||
let fm = FileManager.default
|
||
let dir = try fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||
let safe = (name as NSString).lastPathComponent
|
||
let base = (safe as NSString).deletingPathExtension
|
||
let ext = (safe as NSString).pathExtension
|
||
var target = dir.appendingPathComponent(safe)
|
||
var n = 1
|
||
while fm.fileExists(atPath: target.path) {
|
||
let candidate = ext.isEmpty ? "\(base) (\(n))" : "\(base) (\(n)).\(ext)"
|
||
target = dir.appendingPathComponent(candidate)
|
||
n += 1
|
||
}
|
||
try data.write(to: target, options: .atomic)
|
||
return "Files › SkyContour › \(target.lastPathComponent)"
|
||
}
|
||
}
|
||
|
||
/// One location fix for the web app. The WebView's navigator.geolocation shows
|
||
/// its own "localhost would like to use your location" alert on every launch
|
||
/// (WKWebView has no API to remember the answer); the app itself already holds
|
||
/// the when-in-use permission, so ask Core Location directly.
|
||
final class OneShotLocation: NSObject, CLLocationManagerDelegate {
|
||
private let manager = CLLocationManager()
|
||
private var pending: [FlutterResult] = []
|
||
private var timer: Timer?
|
||
|
||
override init() {
|
||
super.init()
|
||
manager.delegate = self
|
||
manager.desiredAccuracy = kCLLocationAccuracyBest
|
||
}
|
||
|
||
/// Answers {lat, lon, accuracy, alt?} or a FlutterError (denied, unavailable, timeout).
|
||
func request(_ result: @escaping FlutterResult) {
|
||
pending.append(result)
|
||
if pending.count > 1 { return } // a fix is already on its way
|
||
timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { [weak self] _ in
|
||
self?.finish(FlutterError(code: "timeout", message: "No location fix", details: nil))
|
||
}
|
||
switch manager.authorizationStatus {
|
||
case .notDetermined:
|
||
manager.requestWhenInUseAuthorization()
|
||
case .authorizedWhenInUse, .authorizedAlways:
|
||
manager.requestLocation()
|
||
default:
|
||
finish(FlutterError(code: "denied", message: "Location permission denied", details: nil))
|
||
}
|
||
}
|
||
|
||
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
|
||
guard !pending.isEmpty else { return }
|
||
switch manager.authorizationStatus {
|
||
case .notDetermined:
|
||
break
|
||
case .authorizedWhenInUse, .authorizedAlways:
|
||
manager.requestLocation()
|
||
default:
|
||
finish(FlutterError(code: "denied", message: "Location permission denied", details: nil))
|
||
}
|
||
}
|
||
|
||
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
||
guard let loc = locations.last else { return }
|
||
var out: [String: Any] = [
|
||
"lat": loc.coordinate.latitude,
|
||
"lon": loc.coordinate.longitude,
|
||
"accuracy": loc.horizontalAccuracy,
|
||
]
|
||
if loc.verticalAccuracy >= 0 { out["alt"] = loc.altitude }
|
||
finish(out)
|
||
}
|
||
|
||
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
|
||
finish(FlutterError(code: "unavailable", message: error.localizedDescription, details: nil))
|
||
}
|
||
|
||
private func finish(_ value: Any?) {
|
||
timer?.invalidate()
|
||
timer = nil
|
||
let callbacks = pending
|
||
pending = []
|
||
callbacks.forEach { $0(value) }
|
||
}
|
||
}
|