[Day 11] Geofencing — 實作地理圍欄功能
前言 在昨天的內容中,我們學會如何利用 Core Location 搭配 MapKit 即時取得並標記用戶的位置。今天,我們將實作地理圍欄(Geofencing)技術,它不僅能偵測使用者是否進入或離開特定區域,還能結合本地通知即時提醒,我們的 App 之後也會用到這個技術。 什麼是 Geofencing? Geofencing(地理圍欄)是一種以座標為中心、半徑為範疇的虛擬區域,透過 Core Location 框架自動監控使用者是否進入或離開該範圍,並能觸發事件通知,例如打卡、到站提醒、商圈推播都跟這個技術相關。 實作 介面設計 首先在 ContentView.swift 設計一個簡單的輸入區,供使用者自訂要監控的目標緯度與經度。 @State private var latitudeText: String = "" @State private var longitudeText: String = "" @State private var isMonitoring = false // 依據是否監控中,UI 隨之改變 // ... // MARK: - Geofencing 輸入介面 private var geofenceInputSection: some View { VStack(spacing: 12) { Text("設定地理圍欄") .font(.headline) HStack { TextField("緯度 (例: 25.033964)", text: $latitudeText) .keyboardType(.decimalPad) .textFieldStyle(.roundedBorder) TextField("經度 (例: 121.564468)", text: $longitudeText) .keyboardType(.decimalPad) .textFieldStyle(.roundedBorder) } HStack(spacing: 12) { Button(isMonitoring ? "正在監控中" : "建立地理圍欄") { startGeofencing() // 開始監控,待後面實作 } .disabled(isMonitoring || latitudeText.isEmpty || longitudeText.isEmpty) .buttonStyle(.borderedProminent) if isMonitoring { Button("停止監控") { stopGeofencing() // 停止監控,待後面實作 } .buttonStyle(.bordered) .foregroundColor(.red) } } if isMonitoring { Text("正在監控半徑100公尺的地理圍欄") .font(.caption) .foregroundColor(.secondary) } } .padding() .background(Color(.systemGray6)) .cornerRadius(12) } 為了讓 body 不要太肥,我們把這個輸入區域包在一個 geofenceInputSection computed property 裡,之後再只要像用變數一樣取用geofenceInputSection,直接把它放在 body 裡。 ...