Методы UIApplicationDelegate не вызываются

Я пытаюсь создать плагин для мониторинга региона. Мониторинг региона запускается нормально, но функция завершила запуск и получила локальное уведомление. Я не уверен, почему это происходит.

регионМониторинг.h

 #import <Foundation/Foundation.h>
    #import <CoreLocation/CoreLocation.h>


    @interface RegionMonitoringPlugin : NSObject <UIApplicationDelegate,CLLocationManagerDelegate>
    {
        CLLocationManager *locationManager; 
    }

    -(void)enterRegionNotify;
    -(void)leaveRegionNotify;
    -(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)raduis;

    @end

регионМониторинг.мм

#import "RegionMonitoringPlugin.h"

@implementation RegionMonitoringPlugin

- (id) init
{
    //if ( init == [super init]){
    if (locationManager==nil){
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        [locationManager setDistanceFilter:kCLDistanceFilterNone];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }

    return self;
}

-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
    {
        [self enterRegionNotify];
    }

-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
    {
        [self leaveRegionNotify];
    }

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)regionwithError:(NSError *)error
    {
        NSLog(@"Location error %@, %@", error, @"Fill in the reason here");
    }

-(void)leaveRegionNotify
{
    NSLog(@"Starting region monitoring - check point 3");

    UILocalNotification *note = [[UILocalNotification alloc] init];
    note.alertBody= @"Region Left"; // ToAsk: What should be displayed
    note.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:note];
    [note release];

}


-(void)enterRegionNotify
{
    UILocalNotification *note = [[UILocalNotification alloc] init];
    note.alertBody= @"Region Left"; //ToAsk: what should be displayed ? 
    note.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:note];
    [note release];

}

-(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)radius
{ 
    NSLog(@"Starting region monitoring - check point 2");
    [self leaveRegionNotify];
    CLLocationCoordinate2D home;
    home.latitude = latitude;
    home.longitude = longitude;
    CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:home radius:radius identifier:@"region"];
    [locationManager startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest];
    [region release];    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
{ 
    NSLog(@"Starting region monitoring - checkpoint 4");

    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Region Monitor Notification" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
        [alertView show]; 
        [alertView release];
    } 
}


- (BOOL)application:(UIApplication *) application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      NSLog(@"Test");
    return TRUE;
}


@end


extern "C" {
        static RegionMonitoringPlugin *regionMonitor;

        // Unity callable function to start region monitoring
        BOOL _startRegionMonitoring(float m_latitude,float m_longitude, float m_radius)
        {

            NSLog(@"Starting region monitoring");
            if (![CLLocationManager regionMonitoringAvailable] || ![CLLocationManager regionMonitoringEnabled] )
                return NO;

            if (regionMonitor == nil){
                regionMonitor = [[RegionMonitoringPlugin alloc]  init] ;
            }
            [regionMonitor startMonitor:m_latitude longitude:m_longitude radius:m_radius];
            return YES;

        }
}

Код Unity для плагина: RegionMonitorMediater.h

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class RegionMonitoringMediator {

    /*Interface to native implementation */
    [DllImport ("__Internal")]
    private static extern bool _startRegionMonitoring (float m_latitude,float m_longitude, float m_radius);

    public static bool startRegionMonitoring (float latitude,float longitude, float radius)
    {
         /*Call plugin only when running on real device*/
        if (Application.platform != RuntimePlatform.OSXEditor)
            return _startRegionMonitoring ( latitude , longitude , radius);
        else return false;

    }
}

Монитор вызывающего региона

Событие OnPress, которое я делаю

bool startedRM = RegionMonitoringMediator.startRegionMonitoring(77.0f,28.0f,10.0f);

person ila    schedule 12.05.2012    source источник


Ответы (2)


Для каждого приложения разрешено только одно UIApplicationDelegate. Когда Unity3D создает ваше приложение для плеера iPhone, создается класс AppController, который действует как интерфейс.

Этот класс является местом для вставки вашего кода для вызова RegionMonitoringPlugin.

person Kay    schedule 12.05.2012
comment
спасибо кей. Я заметил, что AppController передает уведомление Unity. Поэтому я использовал класс NotificationServices в единстве для обработки уведомлений. Однако у меня есть еще один вопрос, я понял, что даже события диспетчера местоположения не называются набуханием, есть какая-то подсказка по этому поводу? Спасибо - person ila; 13.05.2012
comment
Извините, я не использовал его до сих пор. - person Kay; 13.05.2012

init должен включать вызов super в начале:

- (id) init
{
    if (self = [super init])
    {
        // initialize everything else
    }
    return self;
}

обратите внимание, что мы использовали оператор присваивания (=), а не оператор сравнения (==).

person MByD    schedule 12.05.2012
comment
Гм, я думаю, вы имели в виду «я» как lvalue присваивания и в return. - person Ken Thomases; 12.05.2012
comment
@KenThomases - самая неловкая опечатка за долгое время ... исправлено, спасибо. - person MByD; 12.05.2012
comment
@BinyaminSharet: я внес исправление, но функции все равно не вызываются, вы видите другую проблему. - person ila; 12.05.2012