Apple Local Push Connectivity with error nil? - ios

I'm trying to configure Local Push Connectivity. I already have Local Push Entitlement, and have install a provisioning profile with local push entitlement. It's build fine but when app start, PushProvider didn't active and start and Push Manager show error nil. I have done every instructions that sample code have provided.
This is my project.
In my application target, I have a bundle id com.my_team_name.my_app_name
and in the app group name group.com.my_team_name.my_app_name
In the .entitlement, I've set the required configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>app-push-provider</string>
</array>
<key>com.apple.developer.networking.wifi-info</key>
<true/>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.my_team_name.my_app_name</string>
</array>
</dict>
</plist>
Info.plist has noting to change
And I have a PushManager Class with this code
class AppPushManager: NSObject, NEAppPushDelegate{
func appPushManager(_ manager: NEAppPushManager, didReceiveIncomingCallWithUserInfo userInfo: [AnyHashable : Any] = [:]) {
}
static let shared = AppPushManager()
private var pushManager: NEAppPushManager = NEAppPushManager()
private let pushManagerDescription = "PushDefaultConfiguration"
private let pushProviderBundleIdentifier = "com.my_team_name.my_app_name.PushProvider"
func initialize() {
if pushManager.delegate == nil {
pushManager.delegate = self
}
pushManager.localizedDescription = pushManagerDescription
pushManager.providerBundleIdentifier = pushProviderBundleIdentifier
pushManager.isEnabled = true
pushManager.providerConfiguration = [
"host": "my_server.local"
]
pushManager.matchSSIDs = ["my_wifi_ssid"]
pushManager.saveToPreferences(completionHandler: { error in
print("error? \(String(describing: error))")
print("is active: \(pushManager.isActive)")
})
}
}
In my extension, A PushProvider Target. I have a bundle id com.my_team_name.my_app_name.PushProvider
and in the app group name group.com.my_team_name.my_app_name
In the Info.plist of my extension, I've added the required configuration:
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.networkextension.app-push</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).PushProvider</string>
</dict>
the .entitlement file have the same contents as the application.
and I have created the extension class "PushProvider.swift" as follow:
class PushProvider: NEAppPushProvider {
...
}
When I run the application, I got this printed out
error? nil
is active: false
I think it might be something with providerBundleIdentifier in Push Manager. Have anyone know what I've missing?

Related

azure ad login is not working in ios app while microsoft authenticator app is installed

I have built an ios app which is using azure ad login and it was working fine but after install microsoft authenticator app the azure ad login is not working anymore
in fact the alert which does say " app wants to use 'microsoftonline.com' to sign in"
not coming
and uninstalling the authenticator my ios app can login via azure ad again
let kClientID = [clientid]
let kGraphEndpoint = "https://graph.microsoft.com/"
let kAuthority = "https://login.microsoftonline.com/xxxxxxxxx"
let kRedirectUri = [URI]
let kScopes: [String] = ["user.read"]
func initMSAL() throws {
guard let authorityURL = URL(string: kAuthority) else {
print("Unable to create authority URL")
return
}
let authority = try MSALAADAuthority(url: authorityURL)
let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID,
redirectUri: kRedirectUri,
authority: authority)
self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
self.initWebViewParams()
}
func initWebViewParams() {
self.webViewParamaters = MSALWebviewParameters(authPresentationViewController: self)
}
func acquireTokenInteractively() {
guard let applicationContext = self.applicationContext else { return }
guard let webViewParameters = self.webViewParamaters else { return }
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webViewParameters)
parameters.promptType = .selectAccount
applicationContext.acquireToken(with: parameters) { (result, error) in
if let error = error {
print("Could not acquire token: \(error)")
return
}
guard let result = result else {
print("Could not acquire token: No result returned")
return
}
self.accessToken = result.accessToken
let aduser=MicrososftUser.init(id: result.uniqueId ?? "", mail: result.account.username ?? "", givenName: result.account.username ?? "", surname: "");
self.adLoginRequest(aduser: aduser)
//self.getContentWithToken()
}
}
info.plist
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>msauth.$(PRODUCT_BUNDLE_IDENTIFIER)</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.674973595907-gsm9poebb8u1vvb28rvt7osv</string>
</array>
</dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>msalv2</string>
<string>msaalv3</string>
<string>msauthv2</string>
<string>msauthv3</string>
</array>
<key>UIAppFonts</key>
<array>
<string>Inter.ttf</string>
<string>Inter-Black.ttf</string>
<string>Inter-ExtraLight.ttf</string>
<string>Inter-Regular.ttf</string>
<string>Inter-Bold.ttf</string>
<string>Inter-Light.ttf</string>
<string>Inter-SemiBold.ttf</string>
<string>Inter-ExtraBold.ttf</string>
<string>Inter-Medium.ttf</string>
<string>Inter-Thin.ttf</string>
</array>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
<string>remote-notification</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
</dict>
</plist>
when i click on azure ad login button the following error is showing in debug window
Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Failed to delete broker key with error: -34018, MSALInternalErrorCodeKey=-42708, MSALCorrelationIDKey=4A0C2756-0173-7068-AC4F-AFEC1C84BCB3}
could any one help me with this issue
sorry for my bad english
solving the issue by disabling the access from my app to authenticator.
Adding the following line in initMSAL function
MSALGlobalConfig.brokerAvailability = .none
got help from following links:
https://github.com/AzureAD/microsoft-authentication-library-for-objc/issues/845
https://github.com/AzureAD/microsoft-authentication-library-for-objc/blob/dev/MSAL/src/public/configuration/MSALGlobalConfig.h#L74

App's created Folders/Files don't show up in "Files" on iPhone

wonder if anyone can help me. I have an app and I'm trying to move some files into iCloud so they'll show up in "Files" and cloud to other devices. I've been going through lots of resources online researching what's wrong, and nothing seems to help.
In my app project, I have turned on iCloud Documents in capabilities.
In my plist file, I have this:
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.com.mypublishername.myappname</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>myappname</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
In my entitlements file I have:
<dict>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.com.mypublishername.myappname</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.com.mypublishername.myappname</string>
</array>
</dict>
in ObjC, I'm fetching the iCloud folder like so:
NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:#"Documents"];
if (rootDirectory)
{
if (![[NSFileManager defaultManager] fileExistsAtPath:rootDirectory.path isDirectory:nil]) [[NSFileManager defaultManager] createDirectoryAtURL:rootDirectory withIntermediateDirectories:YES attributes:nil error:nil];
gCloudFolder=rootDirectory;
}
Then, when I save a file, I do so locally, and move it into the cloud folder like this:
//
// theFilename is a file in the app's documents folder...
//
int aFile=creat(theFilename,S_IREAD|S_IWRITE);close(aFile);
aFile=open(theFilename,O_BINARY|O_RDWR);
if (aFile)
{
write(aFile,theDataPtr,theLen);
close(aFile);
if (gCloudFolder)
{
NSURL *aLocalStr=[NSURL fileURLWithPath:[NSString stringWithUTF8String:theFilename]];
NSURL *aCloudStr=[gCloudFolder URLByAppendingPathComponent:#"testing_file.txt"];
NSError *error;
if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:aLocalStr destinationURL:aCloudStr error:&error]) NSLog(#"iCloud Error occurred: %#", error);
}
So... what happens. This file DOES get created. If I run this twice, it tells me it can't move to testing_file.txt because it already exists. Also, if I try to setUbiquitous:NO on the file, it tells me I can't set it to no when the file hasn't been synced.
Any idea why my app's folder and this file don't show up in my FILES folder under iCloud?
I have increased the bundle version, which is something I've seen elsewhere. Did nothing.
What am I doing wrong?
This completely stunned me; I had no idea it was possible. I'll just describe my test app in full. It's going to look a lot like yours!
Here is the bundle identifier:
Here is the entitlement:
Here is the entitlement text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.com.neuburg.matt.SaveIntoFilesApp</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.com.neuburg.matt.SaveIntoFilesApp</string>
</array>
</dict>
</plist>
Here is the entry in the Info.plist:
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.com.neuburg.matt.SaveIntoFilesApp</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>MyApp</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
Here is the app delegate:
var ubiq : URL!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
DispatchQueue.global(qos:.default).async {
let fm = FileManager.default
let ubiq = fm.url(forUbiquityContainerIdentifier:nil)
print("ubiq: \(ubiq as Any)")
DispatchQueue.main.async {
self.ubiq = ubiq
}
}
return true
}
Here is the button I tap:
#IBAction func doButton (_ sender:Any) {
if let del = UIApplication.shared.delegate as? AppDelegate {
if let ubiq = del.ubiq {
do {
let fm = FileManager.default
let docs = ubiq.appendingPathComponent("Documents")
try? fm.createDirectory(at: docs, withIntermediateDirectories: false, attributes: nil)
let url = docs.appendingPathComponent("test.txt")
print("here we go")
try? fm.removeItem(at: url)
try "howdy \(Date())".write(to: url, atomically: true, encoding: .utf8)
print("saved")
} catch {
print(error)
}
}
}
}
I did have to increment the bundle version (from 1 to 2) and I did have to kill and restart the Files app. And then I saw my file (and can open and examine it):

PacketTunnelProvider network extension not called Swift 3

I am trying to add a PacketTunnerProvider network extension to my project. The method startTunnelWithOptions(options: [String : NSObject]?, completionHandler: (NSError?) -> Void) Never gets called
However, I am able to succesfully establish a VPN connection using the network extensions bundle id for the providerBundleIdentifier
This is my code used to establish a connection
let vpnManager = NETunnelProviderManager.shared()
func initVPNTunnelProviderManager() {
let config = NETunnelProviderProtocol()
config.providerBundleIdentifier = self.tunnelBundleId
config.providerConfiguration = ["lol": 1]
config.serverAddress = self.serverAddress
config.username = self.username
config.passwordReference = passwordRef
vpnManager.loadFromPreferences {
(error: Error?) in
self.vpnManager.protocolConfiguration = vpnProtocol
self.vpnManager.localizedDescription = "Connect_1.0.0"
self.vpnManager.isEnabled = true
self.vpnManager.saveToPreferences {
(error: Error?) in
do {
try self.vpnManager.connection.startVPNTunnel()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
}
}
This is my PacketTunnel entitlements file
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.networking.vpn.api</key>
<array>
<string>allow-vpn</string>
</array>
<key>com.apple.security.application-groups</key>
<array>
<string>group.touchcore.Connectionapp</string>
</array>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)touchcore.Connectionapp.PacketTunnel</string>
</array>
<key>com.apple.developer.networking.networkextension</key>
<array>
<string>packet-tunnel-provider</string>
<string>app-proxy-provider</string>
<string>content-filter-provider</string>
</array>
</dict>
</plist>`
The method startTunnelWithOptions(options: [String : NSObject]?, completionHandler: (NSError?) -> Void) Never gets called
However, I am able to succesfully establish a VPN connection using the network extensions bundle id for the providerBundleIdentifier
What exactly do you mean it never gets called? If you're able to successfully establish a connection then startTunnelWithOptions is being called.
If you're trying to determine that it' being called by using an NSLog(), keep in mind that that will only show in the debug log if you attatch the debugger to the provider instead of your container application.
This will be difficult as the provider is initialized and the startTunnelWithOptions function is called before you get a chance to attach the debugger.
A useful work around in this situation is to sleep in order to give the debugger time to attach.
- (void) startTunnelWithOptions:(NSDictionary *) options
completionHandler:(void (^)(NSError *)) completionHandler
{
// Give debugger time to attach, 10 seconds is usually enough
// Comment this out before you release the app or else you
// will be stuck with a 10 second delay on all connections.
sleep(10);
// Continue with execution
. . .
}
Then, when you initialize your PacketTunnelProvider it will wait 10 seconds before fully entering your logic inside of the startTunnelWithOptions function.
So, during this time in XCode you can go to Debug->Attach To Process->YourVPNProviderProcess and wait for it to fully initialize.

AWSS3 Region / plist configuration issue 'The service configuration is `nil`

I am facing a strange issue with AWSS3.
Setup:
AWS Mobile HUB
Cognito
DynamoDB
S3
--> Cognito, Dynamo & even S3 (through cognito user data) work.
However I now tried to connect directly to AWS3 with the following code:"
let transferManager = AWSS3TransferManager.default()
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = "XXXXXXXXXXXX"
uploadRequest?.key = "user-data/" + awsId! + "/primary_profile_picture.png"
uploadRequest?.body = imgUrl as URL
transferManager.upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block: { (task:AWSTask<AnyObject>) -> Any? in
if let error = task.error as? NSError {
if error.domain == AWSS3TransferManagerErrorDomain, let code = AWSS3TransferManagerErrorType(rawValue: error.code) {
switch code {
case .cancelled, .paused:
break
default:
print("Error uploading: \(uploadRequest?.key) Error: \(error)")
}
} else {
print("Error uploading: \(uploadRequest?.key) Error: \(error)")
}
return nil
}
let uploadOutput = task.result
print("Upload complete for: \(uploadRequest?.key)")
return nil
})
and am getting the error:
AWSiOSSDK v2.5.1 [Debug] AWSInfo.m line:122 | -[AWSServiceInfo initWithInfoDictionary:checkRegion:] | Couldn't read the region configuration from Info.plist for the client. Please check your `Info.plist` if you are providing the SDK configuration values through `Info.plist`.
2017-02-20 19:29:21.748997 [2210:1152801] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The service configuration is `nil`. You need to configure `Info.plist` or set `defaultServiceConfiguration` before using this method.'
I am using the downloaded plist configuration from AWS Mobiel HUB and am therfore a bit surprised that it does not work (as all other components do).
Any ideas what the issue might be? The plist actually contains the bucket ID & region.
For me, I had to configure the credentials with the following code, before uploading:
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1,identityPoolId:PoolID)
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
Where PoolID is my Cognito identity. I hope this helps others.
Your info.plist needs to have S3TransferManager in it.
So, **AWS -> S3TransferManager -> Default -> Region -> ...**
You can find an example of one here
Swift 3 - Xcode 8.3.3
For people still having this issue, I just spent 3h fighting against this annoying setup issue.
I added both these chunks in my Info.plist (replace the variables between ** ** in the second bloc) and now it's working again.
Amazon's documentation isn't updated properly I think. I hope this can save some people some time.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>amazonaws.com</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>amazonaws.com.cn</key>
<dict>
<key>NSThirdPartyExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
and:
<key>AWS</key>
<dict>
<key>CredentialsProvider</key>
<dict>
<key>CognitoIdentity</key>
<dict>
<key>Default</key>
<dict>
<key>PoolId</key>
<string>**YourCognitoIdentityPoolId**</string>
<key>Region</key>
<string>**AWSRegionUnknown**</string>
</dict>
</dict>
</dict>
<key>S3TransferManager</key>
<dict>
<key>Default</key>
<dict>
<key>Region</key>
<string>**AWSRegionUnknown**</string>
</dict>
</dict>
</dict>
I had the same issue instead of S3TransferManager you should put DynamoDBObjectMapper
e.g..
<key>DynamoDBObjectMapper</key>
<dict>
<key>Default</key>
<dict>
<key>Region</key>
<string>us-east-1</string>
</dict>
</dict>
The problem was, region should be:
us-east-1
Instead of; US_EAST_1
Add Service configuration file with the data
If the above marked solution is not working for some cases. Try the below solution.
As the error says, the service configuration file is nil. So, we need to add the awsconfiguration.json file with the below data.
{
"Version": "1.0",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "REPLACE_ME",
"Region": "REPLACE_ME"
}
}
},
"S3TransferUtility": {
"Default": {
"Bucket": "REPLACE_ME",
"Region": "REPLACE_ME"
}
}
}
Replace the bucket, region, poolId of your project.

iOS: Simple way to manage REST end points

Our REST based application can be used for testing on multiple internal environments each with a different REST end point. Is there a simple way to set up environment level configuration within an iOS (Swift 3) app? I've seen a few approaches but they all seem pretty involved.
This is my approach of doing things when we have multiple end points. I used to make a ConfigurationManager class something like this
Swift 3.0 code
import Foundation
import UIKit
let kEnvironmentsPlist:NSString? = "Environments"
let kConfigurationKey:NSString? = "ActiveConfiguration"
let kAPIEndpointKey:NSString? = "APIEndPoint"
let kLoggingEnabledKey:NSString? = "LoggingEnabled"
let kAnalyticsTrackingEnabled:NSString? = "AnalyticsTrackingEnabled"
class ConfigurationManager:NSObject {
var environment : NSDictionary?
//Singleton Method
static let sharedInstance: ConfigurationManager = {
let instance = ConfigurationManager()
// setup code
return instance
}()
override init() {
super.init()
initialize()
}
// Private method
func initialize () {
var environments: NSDictionary?
if let envsPlistPath = Bundle.main.path(forResource: "Environments", ofType: "plist") {
environments = NSDictionary(contentsOfFile: envsPlistPath)
}
self.environment = environments!.object(forKey: currentConfiguration()) as? NSDictionary
if self.environment == nil {
assertionFailure(NSLocalizedString("Unable to load application configuration", comment: "Unable to load application configuration"))
}
}
// CurrentConfiguration
func currentConfiguration () -> String {
let configuration = Bundle.main.infoDictionary?[kConfigurationKey! as String] as? String
return configuration!
}
// APIEndpoint
func APIEndpoint () -> String {
let configuration = self.environment![kAPIEndpointKey!]
return (configuration)! as! String
}
// isLoggingEnabled
func isLoggingEnabled () -> Bool {
let configuration = self.environment![kLoggingEnabledKey!]
return (configuration)! as! Bool
}
// isAnalyticsTrackingEnabled
func isAnalyticsTrackingEnabled () -> String {
let configuration = self.environment![kAnalyticsTrackingEnabled!]
return (configuration)! as! String
}
func applicationName()->String{
let bundleDict = Bundle.main.infoDictionary! as NSDictionary
return bundleDict.object(forKey: "CFBundleName") as! String
}
}
In Project--> Info Add some new configurations as per your need.
I have added Staging and QA as extra endpoints.Generally I use to make Staging as Release config and QA as Debug. So it will look like:
Now go to Targets -> Build Settings and add a User Defined Setting
Give the name of the user defined like ACTIVE_CONFIGURATION.
Add a key named ActiveConfiguration in info.plist with a variable name as $(ACTIVE_CONFIGURATION) same as given in User Defined Settings with a $ in the beginning. We gave the name of key as ActiveConfiguration because we are using the same name in our ConfigurationManager.swift class for kConfigurationKey.
let kConfigurationKey:NSString? = "ActiveConfiguration"
You can define as per your naming convention.
It will look like:
Now in the ConfigurationManager class I am getting a path for Environments.plist file.
I will just make a Environments.plist file like this:
The actual description source of this file is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Development</key>
<dict>
<key>APIEndPoint</key>
<string>https://dev</string>
<key>LoggingEnabled</key>
<true/>
<key>AnalyticsTrackingEnabled</key>
<true/>
<key>Flurry</key>
<dict>
<key>FlurryApplicationID</key>
<string></string>
<key>FlurryApplicationSecret</key>
<string></string>
</dict>
<key>Facebook</key>
<dict>
<key>FacebookAppID</key>
<string></string>
<key>FacebookAppSecret</key>
<string></string>
</dict>
</dict>
<key>QA</key>
<dict>
<key>APIEndPoint</key>
<string>https://qa</string>
<key>LoggingEnabled</key>
<true/>
<key>AnalyticsTrackingEnabled</key>
<true/>
<key>Flurry</key>
<dict>
<key>FlurryApplicationID</key>
<string></string>
<key>FlurryApplicationSecret</key>
<string></string>
</dict>
<key>Facebook</key>
<dict>
<key>FacebookAppID</key>
<string></string>
<key>FacebookAppSecret</key>
<string></string>
</dict>
</dict>
<key>Staging</key>
<dict>
<key>APIEndPoint</key>
<string>https://staging</string>
<key>LoggingEnabled</key>
<false/>
<key>AnalyticsTrackingEnabled</key>
<true/>
<key>Flurry</key>
<dict>
<key>FlurryApplicationID</key>
<string></string>
<key>FlurryApplicationSecret</key>
<string></string>
</dict>
<key>Facebook</key>
<dict>
<key>FacebookAppID</key>
<string>840474532726958</string>
<key>FacebookAppSecret</key>
<string></string>
</dict>
</dict>
<key>Production</key>
<dict>
<key>APIEndPoint</key>
<string>https://production</string>
<key>LoggingEnabled</key>
<true/>
<key>AnalyticsTrackingEnabled</key>
<true/>
<key>Flurry</key>
<dict>
<key>FlurryApplicationID</key>
<string></string>
<key>FlurryApplicationSecret</key>
<string></string>
</dict>
<key>Facebook</key>
<dict>
<key>FacebookAppID</key>
<string></string>
<key>FacebookAppSecret</key>
<string></string>
</dict>
</dict>
</dict>
</plist>
We are now good to go. Now you have to just call
ConfigurationManager.sharedInstance.APIEndpoint()
for your respective end points.
Now you just have to change the schemes from Edit Schemes and you are done and change the Build Configuration in info.
This not only manages API End Points but also other things like whether to enable analytics or tracking for the respective end point or different ids of Facebook for different end points.
As Zac Kwan suggested, you can use different schemes to accomplish this, but you don't necessarily have to create a different configuration as well. Each scheme can specify unique environment variables. Then, access them from Swift:
let prodURL = "http://api.com"
let baseURL = ProcessInfo.processInfo.environment["BASE_URL"] ?? prodURL
I found that creating different Scheme and Configuration for your project works best. My setup is as follow:
I usually have 3 different scheme, MyApp-dev, MyApp-staging and MyApp.
Each of the scheme i created User-Defined-Attribute to have different string appending to my Bundle Display Name. So it can concurrently appear on my iOS device as MyApp-d, MyApp-s and MyApp. Each also have its own Bundle ID Then I create custom flags for each of them.
So in my Routes.swift files i have something like this at the top:
#if PRODUCTION
static let hostName = "http://production.com/api/v1/"
#elseif STAGING
static let hostName = "http://staging.com/api/v1/"
#else
static let hostName = "http://development.com/api/v1/"
#endif
There is quite a few ways in how to update different hostname. But ultimately creating different Scheme and Configuration is always the first step.
Here is a few links that might help you get started:
https://medium.com/#danielgalasko/change-your-api-endpoint-environment-using-xcode-configurations-in-swift-c1ad2722200e#.o6nhic3pf
http://limlab.io/swift/2016/02/22/xcode-working-with-multiple-environments.html
I ended up using https://github.com/theappbusiness/ConfigGenerator:
A command line tool to auto-generate configuration file code, for use
in Xcode projects. The configen tool is used to auto-generate
configuration code from a property list. It is intended to create the
kind of configuration needed for external URLs or API keys used by
your app. Currently supports both Swift and Objective-C code
generation.

Resources