What’s probably the most dependable solution to programmatically get principal bundle ID from inside any goal, extension.
I would wish to have a bit of code shared throughout all targets that might enable for building of frequent app group id that I can use to share UserDefaults
, Keychain
, and so forth. That code needs to be impartial from a concrete venture and bundle id.
As a brief answer I take advantage of this one:
import Basis
public enum AppConstants {
public enum UserDefaults {
public static let suiteName: String = {
let bundleID = Bundle.principal.bundleIdentifier ?? "com.instance.MyApp"
// Discover the principle app bundle ID by eradicating extension suffixes
// This handles any extension naming sample (widget, extension, share, and so forth.)
let elements = bundleID.elements(separatedBy: ".")
if elements.depend > 3 && (
elements.final == "widget" ||
elements.final == "extension" ||
elements.final == "share" ||
elements.final?.accommodates("Extension") == true
) {
// Take away the final element (extension suffix)
let baseID = elements.dropLast().joined(separator: ".")
return "group.(baseID)"
}
// If no extension suffix discovered, use the bundle ID as is
return "group.(bundleID)"
}()
}
}
However I would wish to have a code that might work appropriately no matter bundle ID format or size.
Listed below are a number of points to focus on:
- I need a dynamic answer (not hardcoded strings)
- The answer ought to work with any bundle ID format (not simply 3-component identifiers)
- It must reliably determine the “base” app ID when referred to as from extensions
- The aim is to share issues like
UserDefaults
between app and extensions - The answer needs to be reusable throughout totally different tasks
- Listing merchandise
Further context
- I’ve tried strategy that use elements(separatedBy: “.”) and prefix(3) however discovered it unreliable
- Extensions might need varied suffix patterns (widget, extension, share, and so forth.)
- Some bundle IDs might need extra or fewer (or much less) than 3 elements