發表文章

目前顯示的是 6月, 2019的文章

iOS APP 在背景取得使用者位置(Get location at background)

圖片
簡單整理一下iOS如何在背景持續取得使用者位置,本例在收到新定位後會發送一個local notification給自己 在專案中的設定 Target => Capabilities => Background Modes,Switch to ON 選取Location updates 在plist中加入描敘(這會在提醒使用者同意使用定位時出現) Privacy - Location Always and When In Use Usage Description Privacy - Location Always Usage Description Privacy - Location When In Use Usage Description 實作 1. 在AppDelegate中加入import import CoreLocation import UserNotifications 2. AppDelegate實作CLLocationManagerDelegate class AppDelegate: UIResponder , UIApplicationDelegate , CLLocationManagerDelegate { 3. 加入location manager相關實作 使用locationManager.startMonitoringSignificantLocationChanges(),而非locationManager.startUpdatingLocation。使用方法可參考 官方文件 ,要特別注意的是這個方法取得新定位的觸發時間點在這份 官方文件 裡有說明如下,大意大概是移動距離500公尺以上才會觸發,且觸發間隔大於5分鐘(我的解讀及實際測試是在行進中,大約每5分鐘觸發一次) Note Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently ...

DispatchGroup操作

最近一個案子有個需求,需要call 2隻API,並且得到2隻API回傳的結果後,才做資料處理及UI顯示。 做法1: 2隻API沒有前後順序 Code: print ( "Group created" ) //產生兩個task let task1 = DispatchQueue (label: "task1" ) let task2 = DispatchQueue (label: "task2" ) //產生DispatchGroup let group = DispatchGroup () group . enter () task1 . async (group: group , qos: . default ) {     print ( "task1 start" )     sleep ( 10 )     print ( "task1 end" )     group . leave () } group . enter () task2 . async (group: group , qos: . default ) {     print ( "task2 start" )     sleep ( 5 )     print ( "task2 end" )     group . leave () } group . notify (queue: . main , execute:{     print ( "All task is done" )     //self.reloadUI() }) Result: Group created task1 start task2 start task2 end task1 end All task is done 可以看到task1執行10秒,task2執行5秒,所以task2先結束了,並沒有按照順序執行 做法2: API有先後順序,加入...

iOS 強制螢幕轉向(force view orientation)

圖片
最近一個專案的需求,在整個專案裡的某一個View要強制轉成橫的,Google了好久,卡了1天才解決這個需求 1. 在Targets裡面要記得設定App支援的螢幕方向,Targets->Deployment Info->Device Orientation 2. 在要被強制轉向的View裡加入以下的code,做法就是進入viewDidLoad的時候把原本的螢幕方向記下來,然後轉成你要的方向,在viewWillDisappear的時候轉回來,override var shouldAutorotate, supportedInterfaceOrientations, preferredInterfaceOrientationForPresentation      //記錄原本的螢幕方向     var oldOrientation: Int = 0          override func viewDidLoad() {         super . viewDidLoad ()                  //記下原本的螢幕方向         oldOrientation = UIDevice . current . orientation . rawValue                  //強制landscapeRight         UIDevice . current . setValue ( UIInterfaceOrientation . landscapeRight . rawValue , forKey: "orientation" )     }        ...