2017-01-01 2 views
0

Я создаю приложение, которое имеет несколько видов. Я хочу, чтобы он мог следить за маяками на фоне всех просмотров. Итак, я настраиваю код в делегате приложения. Когда код находится в делете приложения, он ничего не делает. Если я переведу его на первый контроллер просмотра для загрузки, он попросит авторизацию использовать местоположение, но не выполняет действия при входе в зону маяка. Вот код в делегате приложения. Что я делаю не так?Настройка действий iBeon и мониторинг из Appdelegate

import UIKit 
import CoreLocation 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { 

    var window: UIWindow? 


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     return true 
    } 

    func applicationWillResignActive(_ application: UIApplication) { 
     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
     // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 
    } 

    func applicationDidEnterBackground(_ application: UIApplication) { 
     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
    } 



    func applicationDidFinishLaunchingWithOptions(_ application: UIApplication) { 


     let beaconManager = CLLocationManager() 


      var locationManager: CLLocationManager! 

      var window: UIWindow? 


      locationManager = CLLocationManager() 

      locationManager.delegate = self 

      locationManager.requestAlwaysAuthorization() 

      func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
       if status == CLAuthorizationStatus.authorizedAlways { 
        if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) { 
         if CLLocationManager.isRangingAvailable() { 

          startScanning() 
         } 
        } 
       } 
      } 


      func startScanning() { 

       let uuid = NSUUID(uuidString: "2F234454-CF6D-4AOF-ADF2-F4911BA9FFA6") 
       let beaconRegion1 = CLBeaconRegion(proximityUUID: uuid as! UUID, major: 0, minor: 1, identifier: "AuschwitzAlbum") 
       let beaconRegion2 = CLBeaconRegion(proximityUUID: uuid as! UUID, major: 0, minor: 2, identifier: "Children") 

       locationManager.startMonitoring(for: beaconRegion1) 
       locationManager.startMonitoring(for: beaconRegion2) 
      } 


      func beaconManager(manager: Any, didEnterRegion: CLBeaconRegion) { 

       switch CLBeaconRegion() { 

       case beaconRegion1: 
        let storyboard = UIStoryboard(name: "Main", bundle: nil) 
        let controller = storyboard.instantiateViewController(withIdentifier: "exhibitions") 
        self.window?.rootViewController?.present(controller, animated: true, completion: nil) 


       case beaconRegion2: break 

       default: break 

       } 
      } 

    } 


func applicationWillEnterForeground(_ application: UIApplication) { 
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 
} 

func applicationDidBecomeActive(_ application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

func applicationWillTerminate(_ application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 


} 
+0

Когда приложение входит в область радиомаяка, он должен отображать представление о том, «Вы ввели XXX регион вы бы хотели видеть. экспонатов около XXX? " Если они коснутся да, они перейдут к соответствующему виду. Если они коснутся нет, это просто закроет представление. –

+0

Возможно, более интересно создать собственный синглтон, а не переопределять слишком много кода AppDelegate. – Larme

ответ

0

Чтобы легко начать, вы могли бы попытаться переместить вызов startScanning() вне вложенности условий или использовать отладчик, чтобы увидеть, если вход и выход область часть вашего кода на самом деле вызывается.

Вот несколько упрощенный пример кода, чтобы вы начали:

import UIKit 
import CoreLocation 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    var locationManager: CLLocationManager! 
    let beaconRegion1 = CLBeaconRegion(proximityUUID: UUID(uuidString: "2F234454-CF6D-4AOF-ADF2-F4911BA9FFA6")!, identifier: "AuschwitzAlbum") 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     locationManager = CLLocationManager() 
     locationManager.delegate = self 
     requestLocationAuthorization() 
     return true 
    } 

    // Standard AppDelegate implementations here 
} 

extension AppDelegate : CLLocationManagerDelegate { 

    func requestLocationAuthorization() { 
     if CLLocationManager.authorizationStatus() != .authorizedAlways { 
      locationManager.requestAlwaysAuthorization() 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 
     if status == .authorizedAlways { 
      startMonitoringRegion() 
     } 
    } 

    func startMonitoringRegion() { 
     locationManager.startMonitoring(for: beaconRegion) 
    } 

    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { 
     print("Did enter region \(region.identifier)") 
     if region.identifier == beaconRegion1.identifier{ 
      showViewController() 
     } 
    } 

    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { 
     print("Did exit region \(region.identifier)") 
    } 

    func showViewController() { 
     let storyboard = UIStoryboard(name: "Main", bundle: nil) 
     let controller = storyboard.instantiateViewController(withIdentifier: "exhibitions") 
     self.window?.rootViewController?.present(controller, animated: true, completion: nil) 
    } 
} 
Смежные вопросы