2017-04-08 44 views
0

我是iOS開發新手,嘗試構建在多個視圖控制器中使用用戶位置的應用程序。我試圖在一個單獨的類中實現位置管理器,然後將位置從回調函數發送到視圖控制器,只要有新的位置可用。我看到一個使用singleton的實現,但想使用協議方法 - 我在過去看到過這樣一個例子,我再也找不到它了,它運行得非常好。iOS 10:CLManager作爲一個單獨的類 - 接受回電

難道人們會建議以這種方式設計它的最佳方式是什麼?以下是我的視圖控制器和位置管理器類中的一些關鍵部分,以供參考。

ViewController.m

- (void)viewDidLoad { 

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
... 
} 

LocClass.m(外景經理類)

- (void)startLocationManager { 
[self.coreLocationManager startUpdatingLocation]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 
//the usual stuff here... 
} 

我怎麼能使用協議的方法來從didUpdateLocations發回的位置:到ViewController.m時,它的可用?如果可能的話,引用一個例子會很好。

+0

PS:我已經看過這個例子,但正如我所解釋的,這不是我正在尋找的:http://stackoverflow.com/questions/11513259/ios-cllocationmanager-in-a-separate-因爲它使用單例。 – moshikafya

回答

1

在LocClass.h文件中添加協議方法

@protocol LocationUpdateProtocol <NSObject> 
@optional 
// Override this method in UIViewController derived class to get back the location details. 
-(void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations; 
@end 

@interface LocClass : NSObject 
@property (nonatomic, weak) NSObject<LocationUpdateProtocol> *delegate; 
@end 

然後在您.m文件

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 
//the usual stuff here... 

    if([self.delegate conformsToProtocol:@protocol(LocationUpdateProtocol)] && [self.delegate respondsToSelector:@selector(locationUpdatedWithManager:newLocations:)]) { 
     [self.delegate locationUpdatedWithManager:manager newLocations:locations]; 
    } 
} 

現在mainViewcontroller類應該實現這個協議

@interface ViewController() <LocationUpdateProtocol> 

而放置地點經理職位的地方,設置代理人

- (void)viewDidLoad { 

locMan = [[LocClass alloc] init]; 
[locMan startLocationManager]; 
locMan.delegate = self; 
... 
} 

//Will get the delegate callback here. 
- (void)locationUpdatedWithManager:(CLLocationManager *)manager newLocations:(NSArray *)locations{ 
} 
+0

OMG這個工作完美。 ++ 1。 – moshikafya