How does iOS switch the official environment and the test environment on a package

  Recently, the project is in the testing stage, so it is inevitable that it has to be packaged to testers every day. Due to the relatively large scale of our company, the project environment is also divided into three types: testing environment, pre-launch (pre-production) environment, and online (production) environment. Therefore, in the later stage of the test, the daily packaging time also occupies a lot of time. When the notebook memory is insufficient, the Xcode has a temper, or there are bugs that need to be solved urgently, packaging is a very tormenting job. The last two days of testing have come to an end, and I finally have time. I suddenly have an idea, that is, is there any way, a source code package can quickly switch environments for testers to test. And in the previous company, this demand also appeared, but it was not paid much attention at the time, and it was gradually ignored. To put it simply, our company's pre-launch environment and the source code of the online environment are a set, but the pre-launch environment adds a binding address to the hosts. Therefore, the following only talks about switching the test environment and the pre-launch environment. After understanding the following methods, it is not a problem to switch between how many environments.

  Originally, my project switching environment was manually changed to 0 or 1 according to a macro definition in the pch file to determine what environment it was, and then in a file dedicated to the basic url string of the project request address, it was spliced ​​out according to different environments. Different urls, so there will be different request urls in different environments. So in order to avoid having to repackage every time the environment is switched, I have seen a lot of methods on the Internet, but they are all very complicated, and I also need to move the settings in the project target, which is too troublesome. The solution I finally thought of was to put a button, click this button to display UIAlertSheet, you can manually select the environment you need to switch, and focus on the current environment. Save the switched environment in the preference settings, and then in the file dedicated to the basic url string of the project request address, take out the value stored in the preference settings and splice the required url, considering that there is an interface before the login page appears Basic settings for request or interface request url, so it is best to restart the app after selecting the desired environment to ensure that the switch is successful . Without further ado, the code above:

1. In the pch file, define some commonly used macros

/***************单例模式宏**************/
#define MACRO_SHARED_INSTANCE_INTERFACE +(instancetype)sharedInstance;
#define MACRO_SHARED_INSTANCE_IMPLEMENTATION(CLASS) \
+(instancetype)sharedInstance \
{ \
static CLASS * sharedInstance = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
sharedInstance = [[CLASS alloc] init]; \
}); \
return sharedInstance; \
}

#define APPDelegate ((AppDelegate*)[UIApplication sharedApplication].delegate)

#define kBaseUrlSubStringKey @"kBaseUrlSubStringKey"
#define kApp_WebSocket_URLKey @"kApp_WebSocket_URLKey"
#define kServerFBKey @"serverFBKey"

#pragma mark - 偏好读写/****************************/
#define KYMWriteUserDefaults(value, key)     [[NSUserDefaults standardUserDefaults] setObject:value forKey:key]
#define KYMReadUserDefaults(key) [[NSUserDefaults standardUserDefaults]objectForKey:key]
#define KYMRemoveUserDefaults(key)     [[NSUserDefaults standardUserDefaults] removeObjectForKey:key]
#define KYMSaveUserDefaults [[NSUserDefaults standardUserDefaults] synchronize]

2. Create a tool class to switch environments and get the current environment

#import <Foundation/Foundation.h>

@interface YimaiChangeEnvironment : NSObject
MACRO_SHARED_INSTANCE_INTERFACE

// Switch environment 
- ( void )changeEnvironment;

// Get the current environment 
- (NSString * )currentEnvironment;
 @end
#import "YimaiChangeEnvironment.h"
#import "AppDelegate.h"
#import "IQUIWindow+Hierarchy.h"
//TEST
static NSString *const devConfig = @"0";

// pre-production 
static NSString * const prodConfig = @" 1 " ;

//生产
//static NSString *const prodConfig1 = @"2";


@implementation YimaiChangeEnvironment
MACRO_SHARED_INSTANCE_IMPLEMENTATION(YimaiChangeEnvironment)

// Switch environment 
- ( void )changeEnvironment {
    
    NSLog(@"change environment start");
    NSString *title= @" Switch environment " ;
    
    NSString *subTitle= @" It will take effect after restarting, non-testers, please click cancel " ;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleActionSheet];
    
    //修改title
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:title];
//    [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, alertControllerStr.length)];
    [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, alertControllerStr.length)];
    [alert setValue:alertControllerStr forKey:@"attributedTitle"];
    
    //修改message
    NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:subTitle];
//    [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, alertControllerMessageStr.length)];
    [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, alertControllerMessageStr.length)];
    [alert setValue:alertControllerMessageStr forKey:@"attributedMessage"];
    
    NSString *currentEnvironment=@"";
    if ([[self currentEnvironment] isEqualToString:devConfig]) {
        currentEnvironment = @"The current environment is TEST " ;
        [alert addAction:[UIAlertAction actionWithTitle: @" TEST " style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
         // Test environment 
        [[NSUserDefaults standardUserDefaults] setObject:devConfig forKey:kServerFBKey];
         // Reset the base url of the request 
        [self resetRequestBaseUrl];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle: @" pre-production " style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             // Pre-production environment 
            [[NSUserDefaults standardUserDefaults] setObject:prodConfig forKey:kServerFBKey];
             // Reset the requested base url 
            [self resetRequestBaseUrl];
        }]];
        
//        [alert addAction:[UIAlertAction actionWithTitle:@"生产" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            //生产环境
//            [[NSUserDefaults standardUserDefaults] setObject:prodConfig1 forKey:kServerFBKey];
//        }]];
    } else if ([[self currentEnvironment] isEqualToString:prodConfig]) {
        
        currentEnvironment = @"The current environment is pre-production " ;

        [alert addAction:[UIAlertAction actionWithTitle: @" TEST " style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             // Test environment 
            [[NSUserDefaults standardUserDefaults] setObject:devConfig forKey:kServerFBKey];
             // Reset the base url of the request 
            [self resetRequestBaseUrl];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle: @" pre-production " style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
             // Pre-production environment 
            [[NSUserDefaults standardUserDefaults] setObject:prodConfig forKey:kServerFBKey];
             // Reset the requested base url 
            [self resetRequestBaseUrl];
        }]];
        
//         [alert addAction:[UIAlertAction actionWithTitle:@"production" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 //             // production environment
 //             [[NSUserDefaults standardUserDefaults] setObject:prodConfig1 forKey:kServerFBKey];
 //         }]]; 
    }
    
    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //
    }]];
    
    NSLog( @" currentEnvironment = %@ " , currentEnvironment);
     // The currently selected view controller needs to be assigned by itself, such as in the didSelectViewController of the tabbar 
    [KeyWindow.currentViewController presentViewController:alert animated:YES completion:^ {
    }];
    
}


// Get the current environment 
- (NSString * )currentEnvironment{
     // Default test environment 
    NSString *currentEnvironment= devConfig;
     if ([[NSUserDefaults standardUserDefaults] objectForKey:kServerFBKey]) {
        currentEnvironment=[[NSUserDefaults standardUserDefaults] objectForKey:kServerFBKey];
    }return currentEnvironment;
}

- ( void )resetRequestBaseUrl {
 #pragma mark - switch test line and pre-production environment
     if ([[YimaiChangeEnvironment sharedInstance].currentEnvironment isEqualToString: @" 0 " ]) {
        NSLog( @" Test environment... " );
         // Test environment 
        KYMWriteUserDefaults( @" test. " , kBaseUrlSubStringKey);
        KYMWriteUserDefaults(@"ws://tws.rt.xywy.com/websocket", kApp_WebSocket_URLKey);
        KYMSaveUserDefaults;
    } else  if ([[YimaiChangeEnvironment sharedInstance].currentEnvironment isEqualToString: @" 1 " ]) {
         // Pre-launch environment 
        KYMWriteUserDefaults( @"" , kBaseUrlSubStringKey);
        KYMWriteUserDefaults(@"ws://testws.rt.xywy.com/websocket", kApp_WebSocket_URLKey);
        KYMSaveUserDefaults;
        
        NSLog( @" Pre-production environment......... " );
    }
}


@end

3. Add the entry to switch the environment on the login page

// Click to switch development environment 
- (IBAction)didClickChangeEnvironment:( id )sender {
    
    [[YimaiChangeEnvironment sharedInstance]changeEnvironment];
    
    return;
}

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325215796&siteId=291194637