venerdì 2 dicembre 2016

Notifiche cloud con Firebase su IOS

Nel precedente post era stato mostrato come inviare notifiche push a client Android tramite il cloud di Firebase. Si puo' fare la stessa cosa anche con IOS ma e' un inferno  e rimando al video linkato



dopo aver creato un progetto generico per prima cosa si devono aggiungere le librerie via Firebase
inizializzando Cocoapod

pod init

poi si edita il Podfile
----------------------------------
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'Notifica' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!


  # Pods for Notifica

  target 'NotificaTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'NotificaUITests' do
    inherit! :search_paths
    # Pods for testing
  end

pod 'Firebase'
pod 'Firebase/Messaging'
end
----------------------------------
poi si installano le librerie

pod install

e si apre il progetto

open Notifica.xcworkspace

per attivare le notifiche e' sufficiente modificare AppDelegate.m (in giallo sono selezionate le righe di interesse)

AppDelegate.m
-----------------------------------
//
//  AppDelegate.m
//  Notifica
//
//  Created by Luca Innocenti on 30/11/16.
//  Copyright © 2016 Luca Innocenti. All rights reserved.
//

#import "AppDelegate.h"
@import Firebase;
@import FirebaseMessaging;


@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [FIRApp configure];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshCallback:) name: kFIRInstanceIDTokenRefreshNotification object:nil];
    
    UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
    
     return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[FIRMessaging messaging]disconnect];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [self connectToFirebase];

}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"%@",userInfo);
}

- (void)tokenRefreshCallback:(NSNotification *)notification{
    NSString *refreshToken = [[FIRInstanceID instanceID] token];
    NSLog(@"Instance ID Token: %@",refreshToken);
    [self connectToFirebase];
}

- (void)connectToFirebase{
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error){
        if (error != nil) {
            NSLog(@"Unable to connect to FCM %@",error);
        }else {
            NSLog(@"Connesso");
        }
        
    }];
}


@end
-----------------------------------

Si devono poi modificare le Capabilities del progetto attivando le Push Notification e Keyring Sharing


il problema principale e' quello di creare un certificato di autenticazione, aspetto che non e' presente sulla versione Android. La procedura e' spiegata nel dettaglio nel video e non e' esattamente banale

Un avvertimento: non e' possibile usare l'emulatore software di IOS, e' necessario utilizzare un dispositivo fisico







Nessun commento:

Posta un commento

Debugger integrato ESP32S3

Aggiornamento In realta' il Jtag USB funziona anche sui moduli cinesi Il problema risiede  nell'ID USB della porta Jtag. Nel modulo...