2014-10-02 2 views
0

Я новичок в быстром движении и обошел вокруг, пытаясь понять это. Я знаю, что у меня это сложнее, если я должен был догадаться, но мне нужна помощь.Получение информации CLBeacon из AppDelegate для просмотра контроллера в Swift

Я пытаюсь использовать iBeacon для считывания значений UUID, Major и Minor с маяком, а затем использовать это для управления изображением в контроллере представления.

В файле AppDelegate.swift я могу получить информацию и использовать println для ее получения. Файл AppDelegate заключается в следующем:


import UIKit 
    import CoreLocation 

    @UIApplicationMain 

    class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
    var locationManager: CLLocationManager? 
    var lastProximity: CLProximity? 
    var lastUUID: NSUUID! 
    var lastBeacanIdentifier:String = "" 
    var lastMajorValue: NSNumber = 0.0 
    var lastMinorValue: NSNumber = 0.0 

    func application(application: UIApplication, 
     didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { 

      let uuidString = "99C2E498-7606-4575-A353-5F710834E75B" 
      let beaconIdentifier = "co.Company" 
      let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString) 
      let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier) 

      locationManager = CLLocationManager() 
      if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) { 
       locationManager!.requestAlwaysAuthorization() 
      } 

      locationManager!.delegate = self 
      locationManager!.pausesLocationUpdatesAutomatically = false 

      locationManager!.startMonitoringForRegion(beaconRegion) 
      locationManager!.startRangingBeaconsInRegion(beaconRegion) 
      locationManager!.startUpdatingLocation() 

      if(application.respondsToSelector("registerUserNotificationSettings:")) { 
       application.registerUserNotificationSettings(
        UIUserNotificationSettings(
         forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound, 
         categories: nil 
        ) 
       ) 
      } 
      return true 
    } 

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     // Override point for customization after application launch. 

     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 throttle down OpenGL ES frame rates. 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 applicationWillEnterForeground(application: UIApplication) { 
     // Called as part of the transition from the background to the inactive 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:. 
    } 


} 

extension AppDelegate: CLLocationManagerDelegate { 
    func sendLocalNotificationWithMessage(message: String!) { 
     let notification:UILocalNotification = UILocalNotification() 
     notification.alertBody = message 
     UIApplication.sharedApplication().scheduleLocalNotification(notification) 
    } 

    func locationManager(manager: CLLocationManager!, 
     didRangeBeacons beacons: [AnyObject]!, 
     inRegion region: CLBeaconRegion!) { 
      NSLog("didRangeBeacons"); 
      var message:String = "" 

      if(beacons.count > 0) { 
       let nearestBeacon:CLBeacon = beacons[0] as CLBeacon 

       if(nearestBeacon.proximity == lastProximity || 
        nearestBeacon.proximity == CLProximity.Unknown) { 
         return; 
       } 

       lastProximity = nearestBeacon.proximity; 
       lastMajorValue = nearestBeacon.major; 
       lastMinorValue = nearestBeacon.minor; 
       lastUUID = nearestBeacon.proximityUUID; 


       switch nearestBeacon.proximity { 
       case CLProximity.Far: 
        message = "You are far away from the beacon"; 
        println(lastMajorValue) 
        println(lastMinorValue) 
        println(lastUUID) 
       case CLProximity.Near: 
        message = "You are near the beacon"; 
        println(lastMajorValue) 
        println(lastMinorValue) 
        println(lastUUID) 
       case CLProximity.Immediate: 
        message = "You are in the immediate proximity of the beacon"; 
        println(lastMajorValue) 
        println(lastMinorValue) 
        println(lastUUID) 
       case CLProximity.Unknown: 
        return 
       } 
      } else { 
       message = "No beacons are nearby" 
      } 

      NSLog("%@", message) 
      sendLocalNotificationWithMessage(message) 
    } 
    func locationManager(manager: CLLocationManager!, 
     didEnterRegion region: CLRegion!) { 
      manager.startRangingBeaconsInRegion(region as CLBeaconRegion) 
      manager.startUpdatingLocation() 

      NSLog("You entered the region") 
      sendLocalNotificationWithMessage("You entered the region") 
    } 

    func locationManager(manager: CLLocationManager!, 
     didExitRegion region: CLRegion!) { 
      manager.stopRangingBeaconsInRegion(region as CLBeaconRegion) 
      manager.stopUpdatingLocation() 

      NSLog("You exited the region") 
      sendLocalNotificationWithMessage("You exited the region") 
    } 
} 

Файл View Controller является следующее:

import Foundation 
import UIKit 
import CoreLocation 

class ViewController: UIViewController{ 


    @IBOutlet weak var advertismentImageArea: UIImageView! 

    @IBAction func closeAdvertisementButton(sender: UIButton) { 
     advertismentImageArea.hidden = true 
    } 
    var beaconInformation: AppDelegate! 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     var closestBeacon = beaconInformation 


     var majorNumber = closestBeacon.lastMajorValue 


     if majorNumber == 6303 { 
      advertismentImageArea.image = UIImage(named: "AdOne") 
     } else if majorNumber == 21456 { 
      advertismentImageArea.image = UIImage(named: "AdTwo") 
     } else { 
      return advertismentImageArea.hidden = true; 
     } 
    } 



    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 



} 

Я был бы очень признателен за любую помощь вы можете предоставить.

ответ

0

Одним из возможных решений может быть использование шаблона делегирования iOS. Это не единственный способ решить эту проблему.

Что бы вы сделали бы создать протокол в классе AppDelegate

@protocol BeaconLocationDelegate 
{ 
    func majorBeaconChanged(majorValue:NSNumber) 
} 

Вы бы затем добавить следующую переменную в свой AppDelegate класс

weak var locationDelegate: BeaconLocationDelegate? 

Внутри вашего класса ViewController вы бы затем объявите, что ваш класс реализует протокол BeaconLocationDelegate.

class ViewController: UIViewController, BeaconLocationDelegate 

, а затем где-то в viewDidload добавьте следующую строку кода

UIApplication.sharedApplication().delegate?.locationDelegate = self 

, а затем реализовать метод протокола для обновления пользовательского интерфейса однако вы хотите для вашего приложения

func majorBeaconChanged(majorValue:NSNumber) 

И, наконец, в своем классе AppDelegate когда это вы обнаружите изменение в маяке, который вы затем вызывают код:

locationDelegate?.majorBeaconChanged(newMajorValue) 
Смежные вопросы