Ottieni l'identificatore del pacchetto a livello di codice


229

Come posso ottenere una stringa dell'identificatore del pacchetto a livello di codice all'interno della mia app?

Risposte:


454

Objective-C

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

Swift 1.2

let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier

Swift 3.0

let bundleIdentifier = Bundle.main.bundleIdentifier

Xamarin.iOS

var bundleIdentifier = NSBundle.MainBundle.BundleIdentifier

10
Questa risposta non è limitata a iOS. Funziona anche con le app per Mac.
Jonny,

9
In Swift, usalet bundleIdentifier = NSBundle.mainBundle().bundleIdentifier
Tim Camber il

1
(puoi eliminare questo commento) ma adoro la sensazione di leggere la risposta quindi nel commento, vedi qualcosa come @Jonny se Tim (anche se puoi vederlo in un'altra risposta completa), si collega a qualcos'altro che è ancora rilevante e utile. Grazie per i grandi ragazzi della community.
haxpor

2
Swift3:Bundle.main.bundleIdentifier!
Sebastian Roth,


2

Potrebbe essere necessario l'approccio Core Foundation per ottenere il valore. L'esempio ARC è il seguente:

NSString *value = (__bridge_transfer NSString *)CFDictionaryGetValue(CFBundleGetInfoDictionary(CFBundleGetMainBundle()),
                                                                     (const void *)(@"CFBundleIdentifier"));

2

Per ottenere l'identificatore del bundle a livello di codice in Swift 3.0 :

Swift 3.0

let bundle = Bundle.main.bundleIdentifier

0

Uso queste macro per renderlo molto più breve:

#define BUNDLEID    [NSString stringWithString:[[NSBundle mainBundle] bundleIdentifier]]

#define BUNDLEIDEQUALS(bundleIdString) [BUNDLEID isEqualToString:bundleIdString]

quindi posso solo confrontare in questo modo:

if (BUNDLEIDEQUALS(@"com.mycompany.myapp") {
    //do this
}

0

Se stai cercando di ottenerlo a livello di codice, puoi utilizzare la riga di codice seguente:

Objective-C:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

Swift 3.0:

let bundleIdentifier =  Bundle.main.bundleIdentifier

Aggiornato per l'ultimo rapido Funzionerà per le app iOS e Mac.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.