Home > Blockchain >  How to make UIActivityViewController excluded items dynamic based on a dynamic array?
How to make UIActivityViewController excluded items dynamic based on a dynamic array?

Time:03-15

I went through a tutorial for implementing the UIActivityViewController everything is working as expected. I can also use excludedItems property to remove any default options in UIActivityViewController. But now I want to make this code more dynamic. Actually my plan is that user can choose which options he can choose to omit or exclude from the UIActivityViewController . So for that I am planning to pass an array with some fixed keys and based on that keys I can define which items to included in excluded lists. Below is the sample code :

NSArray* excludedArray = [NSArray arrayWithObjects: @"message", nil];
UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];
if ( [excludedArray containsObject: @"message"] ) {
    NSArray *excluded = @[UIActivityTypeMessage];
    controller.excludedActivityTypes = excluded;
} else {
    // do not found
}

Right now excludedArray only contains message string so based on that I added the UIActivityTypeMessage to excluded array . But tomorrow if the user adds more item to excludedArray for example print then based on that I must be able to add UIActivityTypePrint to excluded array. How to achieve that?

CodePudding user response:

  • Link UIActivityType enum values with the selection you'll give to user using switch case.

  • On select/deselect update the array.

  • At last pass the enum array to excludedActivityTypes.

      func getExcludedActivityTypes(stringArray: [String]) -> [UIActivity.ActivityType]{
      var excludeArray: [UIActivity.ActivityType] = []
      for str in stringArray
      {
          switch str
          { 
          case "messaging":
              excludeArray.append(.message)
              break
          case "postToTwitter":
              excludeArray.append(.postToTwitter)
              break
    
              // write others to exclude those types
          default:
              break
          }
      }
    
      return excludeArray}
    

Objective c - Alternative(you can use if else statement as objective c doesn't support strings for switch cases)

-(NSArray<UIActivityType>*)getExcludedActivityTypes:(NSArray<NSString*>*)stringArray {
NSMutableArray<UIActivityType> * excludeArray = @[].mutableCopy;

for(NSString * str in stringArray) {
    if([str isEqualToString:@"messaging"]){
        [excludeArray addObject:UIActivityTypeMessage];
    }
    
    else if([str isEqualToString:@"postToTwitter"]){
        [excludeArray addObject:UIActivityTypePostToTwitter];
    }
    // write others to exclude those types
}
return excludeArray;}
  • Related