This is the 11th day of my participation in the August More Text Challenge. For details, see “juejin.cn/post/698796…

preface

Many times you need to save the data returned by the interface for the next time. Application scenarios of local JSON files:

1. As test data

2. Avoid data delay caused by frequent requests to the interface and improve performance (for data that does not change for a long time, such as enumerations, regions)

Example: save the interface/API/Dictionaries/GetDictionariesEnum obtain all enumeration data dictionary () returns the dictionary data as json file, so that the next time the app is started to use, to avoid data delay request interface, according to improve the performance.

1, first get data from content NSMutableArray,

2. If the content does not exist, read searchenum. json from the project’s local file

Request the interface to update DictionariesEnum data after successful login

I, array to JSON string application case

 po [[NSString alloc] initWithData: [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]
Copy the code

Case: save the interface/API/Dictionaries/GetDictionariesEnum returned as json dictionary data files, so that next time use, to submit performance.

1.1 Save the data returned by the interface for the next time to submit the performance

Save the interface/API/Dictionaries/GetDictionariesEnum returned as json dictionary data files, so that next time use, to submit performance.

1, first get data from content NSMutableArray,

2. If the content does not exist, read searchenum. json from the project’s local file

Request the interface to update DictionariesEnum data after successful login

  • The home page is displayed to update the interface data

+ (void)jumpHome{
    

    [ UserInfoModel.shareUserInfoModel setupinitInfo];

    
    [[UIApplication sharedApplication].keyWindow switchRootViewController];
    
    
}

/** Parse local JSON file data to the content update interface data to the local JSON file */
- (void) setupinitInfo{
    
    [self CurrentUserStatus];
    
    
    
    [self GetCurrentSysUser];

    
    [self DictionariesEnum];// Parse the local JSON file data into memory
    [self GetDictionariesEnum];// Update the interface data to the local JSON file
            [QCTAreaListTool getAreaList];

}

Copy the code
  • Provides an NSMutableArray method to get data

Parse local JSON file data into memory


/ * * / API/Dictionaries/GetDictionariesEnum > parse the json data into memory @ local return NSMutableArray * /
- (NSMutableArray *)DictionariesEnum{
    

    if (_DictionariesEnum == nil) {
        
        
        // Get it from the searchenum.json file first.
        
// NSString *path = [[NSBundle mainBundle] pathForResource:@"searchEnum.json" ofType:nil];
// NSArray *array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableLeaves error:nil];
        
        
// NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/searchEnum.json"]; // Obtain the path where the JSON file is saved
        
        
                NSString *filePath = [[NSBundle mainBundle] pathForResource:@"searchEnum.json" ofType:nil];

        
        NSData *data = [NSData dataWithContentsOfFile:filePath];// Obtain the data file at the specified path
        
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; // Retrieve the following data from the JSON file (dictionary)

        
        
        _DictionariesEnum= [QCTDictionariesEnum mj_objectArrayWithKeyValuesArray:json];
        
        
        
        [self setupGetDictionariesEnum:_DictionariesEnum];
        
        
        
        
        
    }
    
    return _DictionariesEnum;
    
}



Copy the code
  • Update the interface data to the local JSON file
/** Update the interface data to the local JSON file */
- (void)  GetDictionariesEnum{
    
    NSString *getURL = k_API_Dictionaries_GetDictionariesEnum;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    __weak __typeof__(self) weakSelf = self;

    [QCTNetworkHelper GET:getURL parameters:params success:^(id  _Nonnull responseObj) {
        
        
        

        NSArray *tmpdic = responseObj[@"data"];
        
        
        if(tmpdic.count >0) {// Save the data to JSON

            NSString *filePath = [[NSBundle mainBundle] pathForResource:@"searchEnum.json" ofType:nil];

            
            
            NSData *json_data = [NSJSONSerialization dataWithJSONObject:tmpdic options:NSJSONWritingPrettyPrinted error:nil];

            [json_data writeToFile:filePath atomically:YES];

            
            
            
        }else{
            
            return ;
        }

        
        
        
        // Update the memory object data
        [weakSelf setupGetDictionariesEnum:[QCTDictionariesEnum mj_objectArrayWithKeyValuesArray:tmpdic]];
        
        
    } failure:nil bizFailure:nil isShowLoadingDataGif:NO];
    
    
}          ///api/SysUser/GetCurrentSysUser

Copy the code

1.2 Periodically update the local JSON file when a new version is released

  • Break point to get data
  "data": [{"keyName" : "EAnnouncementShowType"."data": [{"value" : 1."text" : "Pop-up Notification (including bulletin Center display)"
        },
        {
          "value" : 2."text" : "Bulletin Center Display"}]."description" : "Presentation mode"
    },

Copy the code
  • Enter the LLDB to obtain JSON data
  po [[NSString alloc] initWithData: [NSJSONSerialization dataWithJSONObject:tmpdic options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]

Copy the code

  • Copy console JSON data overwrites the local JSON data

1.3 The enumeration returned by the interface is used to dynamically control the filtering of list data

  • ERiskState Processing status of the list of risky merchants
{" keyName ":" ERiskState ", "data" : [{" value ": 1," text ":" pending "}, {" value ": 2," text ", "approval"}, {" value ": Review 3, "text", "reject"}, {" value ": 4," text ":" already timeout "}, {5, "value" : "text" : "audit completed (remove controls)"}], "description" : "Merchant risk control -- processing status"},Copy the code
  • The effect

1.3.1 Initializing list header data

@interface CRMRisk_merchant_List_VM : NSObject

/** Stores ERiskState data */
    @property (nonatomic.strong) NSMutableArray<QCTkeyValueModel*>  *RiskStates;

/** List header array, that is, state description */
@property (nonatomic.strong) NSArray <NSString *> *titles;

Copy the code

- (NSArray<NSString* >*)getRandomTitles{ //ERiskState NSMutableArray *titles = [NSMutableArray array]; for (QCTkeyValueModel *m in self.RiskStates) { [titles addObject: m.text]; } return titles; [/ / / / NSMutableArray * titles1 = @ QCTLocal (@ "pending"), / / QCTLocal (@ "audit"), / / QCTLocal (@ "audit rejected"), / / QCTLocal (@ "completed"), / / / /]; / /}Copy the code

1.3.2 Core code

When requesting data, according to the state of the following table, or the corresponding state description, and then according to the state description using NSPredicate to find the corresponding enumeration value

  • Set the RiskState parameter
    NSString *tmpRiskState = nil;
    
    if(self.viewModel.titles.count> self.index){
        
        tmpRiskState = [self.viewModel getRiskStateValueWithtext:self.viewModel.titles[self.index]];

    }
    
    
    
    if(! [NSStringQCTtoll isBlankString:tmpRiskState]){
        
        [params setValue:tmpRiskState forKey:@"RiskState"];
        

        
    }

Copy the code
  • According to the corresponding state description, and then according to the state descriptionNSPredicateFind the corresponding enumeration value
- (NSString *)getRiskStateValueWithtext:(NSString *)text{ if(self.RiskStates.count<=0){ return nil; } NSPredicate* predicate = [NSPredicate predicateWithFormat:@"text == %@", text]; NSArray *arFiltered = [ self.RiskStates filteredArrayUsingPredicate:predicate]; // QCTkeyValueModel *dto = nil; if(arFiltered.count>0){ dto = arFiltered.firstObject; } return dto.value; //———————————————— // Copyright notice: This article is the original article of CSDN blogger "# public account: iOS Reverse". It follows the COPYRIGHT agreement of CC 4.0 by-SA. Please attach the link of the original source and this statement. / / the original links: https://blog.csdn.net/z929118967/article/details/113499172}Copy the code

1.3.3 Renderings of other application scenarios

  • Related articles

IOS solution for the screen view blinded by blocking the view [example: landscape electronic signature interface screen view blinded by blocking problem (landscape will recreate) 】 kunnan.blog.csdn.net/article/det…

II. Convert json to array

NSString *path = [[NSBundle mainBundle] pathForResource:@"city.json" ofType:nil];

NSArray *array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableLeaves error:nil];
Copy the code

III 、see also

For more content, please pay attention to the official account: iOS Reverse