2015-02-04 104 views
1

我試圖發送目標c中的通知,但我無法弄清楚如何。如何發送本地通知

到目前爲止,我有

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { 
    if(self.username != nil) 
    { 
     NSLog(@"Background fetch username: %@", self.username); 
     [self fetchNotifications]; 
    } 


    completionHandler(UIBackgroundFetchResultNewData); 
} 
- (void)fetchNotifications 
{ 
    NSURL *url = [NSURL URLWithString: 
        [NSString stringWithFormat:@"%@%@", 
        @"https://myurl?username=" 
        , self.username]]; 

    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, 
               NSData *data, NSError *connectionError) 
    { 
     if (data.length > 0 && connectionError == nil) 
     { 
      NSDictionary *notifications = [NSJSONSerialization JSONObjectWithData:data 
                      options:0 
                      error:NULL]; 

      int nbMessages = [[notifications objectForKey:@"NbOfUnreadMessage"] intValue]; 
      int nbOfNewMatch = [[notifications objectForKey:@"NbOfNewMatch"] intValue]; 
      int nbOfNewPlanification = [[notifications objectForKey:@"NbOfNewPlanification"] intValue]; 
      //int nbMessages = [[notifications objectForKey:@"NbOfUnreadMessage"] intValue]; 

      NSLog(@"Notifications - nbMessage: %i",nbMessages); 
      NSLog(@"Notifications - nbNewMatch: %i",nbOfNewMatch); 
      NSLog(@"Notifications - nbNewPlan: %i",nbOfNewPlanification); 

      // Schedule the notification 
      UILocalNotification* localNotification = [[UILocalNotification alloc] init]; 
      localNotification.fireDate = nil; 
      localNotification.alertBody = @"test"; 
      localNotification.alertAction = @"Show me the item"; 
      localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1; 

      [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
     } 
    }]; 
} 

當我嘗試在iPhone 6模擬器IOS 8.1,我有以下錯誤

試圖徽章應用程序圖標,但還沒有從獲得許可用戶徽章的應用程序

我將不得不閱讀並理解這個post

但我真正的問題是當我使用iPhone 5 IOS 7.1模擬器時,函數fetchNotifications甚至沒有被調用。

爲什麼fetchNotifications只在IOS 8.1下調用?

performFetchWithCompletionHandler既OS

回答

0

試圖徽章應用程序圖標下調用但沒有從用戶接收許可徽章應用

是Xcode的告訴你,你能方式在模擬器上運行時不會更改通知標誌值。這是不允許的

這個委託方法是在iOS決定時調用的。從UIApplicationDelegate文檔:

當有機會下載數據時,系統調用此方法爲您的應用程序提供下載所需數據的機會。更重要的是,系統使用經過的時間來計算應用程序後臺下載的用電量和數據成本。如果您的應用程序需要很長時間才能調用完成處理程序,則未來可能會有更少的未來獲取數據的機會。

+0

我明白了,但我在performFetchWithCompletionHandler中獲得日誌消息,但它不會在7.1下調用fetchnotification,但它會在8.1 – Marc