2012-10-28 39 views
1

据我所知,我们可以处理通过方法推送通知是一样的UIRemoteNotification:显示UIAlertView中,当应用程序在前台运行

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 

,我们可以检查,如果应用程序是在前台运行:

if (application.applicationState == UIApplicationStateActive) { ... } 

我们如何显示与本地化完全相同的通知?

NSString *message = [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-key"]; 
NSString *trueMessage = NSLocalizedString(message, nil); 
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" 
                  message:trueMessage 
                cancelButtonItem:@"OK" 
                otherButtonItems:@"Show", nil]; 
[alertView show]; 

这显示原始未定位文本,例如, “您在%2 @上有来自%1 @的新提醒。”

我的问题是,当应用程序在前台运行时,我们如何将loc-args放置在UIAlertView中?

回答

1

一个不那么简单的解决方法,我想出了(假设3是你必须在所有的本地化字符串变量的最大数量):

// Max is 3 variables 
    NSString *variableOne = @""; 
    NSString *variableTwo = @""; 
    NSString *variableThree = @""; 

    int i = 0; 
    for (NSString *eachVariable in [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-args"]) { 
     switch (i) { 
      case 0: 
       variableOne = eachVariable; 
       break; 
      case 1: 
       variableTwo = eachVariable; 
       break; 
      case 2: 
       variableThree = eachVariable; 

      default: 
       break; 
     } 
     i++; 
    } 

    NSString *message = [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-key"]; 

    NSString *trueMessage = [NSString stringWithFormat:NSLocalizedString(message, nil), variableOne, variableTwo, variableThree]; 

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" 
                 message:trueMessage 
               cancelButtonItem:@"Cancel" 
               otherButtonItems:@"Show", nil]; 
    [alertView show]; 
1

我建议你创建一个假va_list这里解释:fake va_list in ARC

这会给看起来有点像这样的代码:

NSString *pushBody; 
id alert = userInfo[@"aps"][@"alert"]; 
if ([alert isKindOfClass:[NSString class]]) pushBody = alert; 
if ([alert isKindOfClass:[NSDictionary class]]) 
{ 
    pushBody = alert[@"loc-key"]; 
    if (pushBody == nil) 
    { 
     pushBody = alert[@"body"]; 
    } 
    else 
    { 
     // Build a fake va_list from the parameters. 
     NSArray *locArgs = alert[@"loc-args"]; 
     NSRange range = NSMakeRange(0, [locArgs count]); 
     NSMutableData* fakeVaList = [NSMutableData dataWithLength: sizeof(id) * [locArgs count]]; 
     [locArgs getObjects:(__unsafe_unretained id *)fakeVaList.mutableBytes range:range]; 

     pushBody = StrLoc(pushBody, @"Remote Notif"); 
     pushBody = [[NSString alloc] initWithFormat:pushBody arguments:fakeVaList.mutableBytes]; 
    } 
} 

告诉我,如果这能为你工作...

相关问题