2014-10-02 1 views
0

저는 신속하고 익숙해지기 위해 돌아 다녔습니다. 나는 추측해야하지만 약간의 도움이 필요하다면 나는 그것이 복잡하게 끝난다는 것을 안다.CLDeacon의 정보를 AppDelegate에서 Swift의 View Controller로 가져 오기

iBeacon을 사용하여 비컨의 UUID, Major 및 Minor 값을 읽은 다음보기 컨트롤러에서 이미지를 구동하는 데 사용하려고합니다.

AppDelegate.swift 파일에서 정보를 얻고 println을 사용하여 정보를 얻을 수 있습니다. AppDelegate에 파일은 다음과 같다 :

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. 
    } 



} 

난 정말 당신이 모두 제공 할 수있는 모든 도움을 주셔서 감사합니다 :


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") 
    } 
} 

보기 컨트롤러 파일은 다음과 같다.

답변

0

한 가지 가능한 해결책은 iOS 위임 패턴을 사용하는 것입니다. 이 문제를 해결하는 유일한 방법은 아닙니다.

당신은

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

그런 다음 또한 것 당신의 ViewController 클래스 내부 AppDelegate에 클래스

weak var locationDelegate: BeaconLocationDelegate? 

에 다음 변수를 추가 할 수 AppDelegate에 클래스의 프로토콜을 작성하는 것입니다 어떻게 할 것인지 그런 다음 클래스가 BeaconLocationDelegate 프로토콜을 구현한다고 선언하십시오.

class ViewController: UIViewController, BeaconLocationDelegate 

다음 어딘가에있는 viewDidLoad에서

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

다음 코드 줄을 추가 한 다음 AppDelegate에 클래스마다 내부

func majorBeaconChanged(majorValue:NSNumber) 

그리고 마지막으로 앱 당신이 원하는 그러나 UI를 업데이트 할 수있는 프로토콜 메서드를 구현 다음 코드를 호출 할 비컨의 변화를 감지합니다.

locationDelegate?.majorBeaconChanged(newMajorValue)