2012-10-28 35 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]; 
    } 
} 

告訴我,如果這能爲你工作...

相關問題