0

I have started Objective C a few hours ago, apologies if my question is already answered, I could not find anything similar.

I have my API key specified in the AppDelegate as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [GMSServices provideAPIKey = "..."]
}

As per google documentation this key need to be provided when I query for the nearby locations. Ideally, I would like to have my key in one file, no copy-paste.

Is there way to get the reference to the key from AppDelegate and use it in another file? Maybe it should be kept in yet another file and both AppDelegate file and the file that calls Locations API should query that another file? Thanks.

Yulia V
  • 3,507
  • 10
  • 31
  • 64
  • Have a look at http://stackoverflow.com/questions/9250805/wheres-the-best-place-to-store-constants-in-an-ios-app – rmaddy Aug 22 '15 at 20:10

1 Answers1

1

You don't need to reference this key in any other file. The API key is paired with your application's bundle ID to identify it. You should call '+ (BOOL) provideAPIKey:(NSString *)APIKey' exactly once in your application.

Therefore, if you called it in application: didFinishLaunchingWithOptions:, you should be able to use google maps services in any other class.

Take a look at https://developers.google.com/maps/documentation/ios/ if you want to see some example codes.

However, if you want, to any reason, be able to reuse any object between your class, you should use Singleton.

The API key, for example is a NSString. Thus, you would declare a class in your .h file like:

@interface APIKey : NSObject

+ (APIKey*)sharedInstance;

@property NSString * apiValue;

@end

And a .m:

@implementation APIKey

+ (APIKey *)sharedInstance{

static APIKey * sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sharedInstance = [[self alloc] init];
});
return sharedInstance;
}

@end

Then you would be able to access 'apiValue' in any class (after import .h file) just calling

[[APIKey sharedInstance] apiValue]; 

Or set new values like this:

[[APIKey sharedInstance] setApiValue:@"someThingHere"]; 

But, as I said, you don't need this to Google API Key.

Hope this helps.

user3435595
  • 137
  • 1
  • 1
  • 9