Search Unity

Problem with getting IOS device token.

Discussion in 'iOS and tvOS' started by dinkjing, Apr 26, 2016.

  1. dinkjing

    dinkjing

    Joined:
    Apr 26, 2016
    Posts:
    5
    I'm trying to use the Unity API get IOS device token to register push notification. The difficulties I found that the UnityEngine.iOS.NotificationServices.deviceToken always throw me null value.

    When the app calling RegisterForNotifications, xcode did throw the token back with result below.
    2016-04-26 17:52:56.445 ****[869:1651521] [NotifyEventListener] Method=DidRegisterRemoteNotification, Message=38db43d982215985afd4ce149227eec4b4b260196fda56df13d246c95b76d8b6

    But after that comes to deviceToken, it was still null even through I tried to invoke the methods again.
    Current implemented Unity version was 5.3.4 and xcode was 7.3.
     
  2. _Paulius

    _Paulius

    Mobile Developer Unity Technologies

    Joined:
    Jul 8, 2014
    Posts:
    173
    It seems to work fine for me with 5.3.4p3 and I'm just doing calling this in start:

    Code (CSharp):
    1.         NotificationServices.RegisterForNotifications(
    2.             NotificationType.Alert |
    3.             NotificationType.Badge |
    4.             NotificationType.Sound);
    and reading the token like this :

    Code (CSharp):
    1.         byte[] token = NotificationServices.deviceToken;
    2.         if (token != null) {
    3.             // send token to a provider
    4.             string hexToken = System.BitConverter.ToString (token).Replace ("-", "");
    5.             Debug.Log ("push token: " + hexToken);
    6.         }
    Could you post the script that you're using so that I could try it?
     
  3. dinkjing

    dinkjing

    Joined:
    Apr 26, 2016
    Posts:
    5
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using Amazon.SimpleNotificationService;
    5. using Amazon.Runtime;
    6. using Amazon.CognitoIdentity;
    7. using Amazon;
    8. using Amazon.SimpleNotificationService.Model;
    9. using AWSSDK.Examples;
    10. using System;
    11. using UnityEngine.UI;
    12.  
    13. public class SNSManager : MonoBehaviour {
    14.    
    15.     //identity pool id for cognito credentials
    16.     [SerializeField]
    17.     public string IdentityPoolId;
    18.     //sns android platform arn
    19.     [SerializeField]
    20.     public string AndroidPlatformApplicationArn;
    21.     //sns ios platform arn
    22.     [SerializeField]
    23.     public string iOSPlatformApplicationArn;
    24.     //project id for android gcm
    25.     [SerializeField]
    26.     public string GoogleConsoleProjectId;
    27.    
    28.     //set your regionendpoints here
    29.     private RegionEndpoint _cognitoRegion = RegionEndpoint.APNortheast1;
    30.     private RegionEndpoint _snsRegion = RegionEndpoint.APSoutheast1;
    31.     private string _endpointArn;
    32.  
    33.     void Start () {
    34.         //Check and define user 1st time install and launch app
    35.         if (PlayerPrefs.GetInt ("Initiation") == 0) {
    36.             PlayerPrefs.SetInt("Initiation",1);
    37.             PlayerPrefs.SetInt("Notification",1);
    38.             RegisterDevice ();
    39.         }
    40.     }
    41.  
    42.     private AWSCredentials _credentials;
    43.    
    44.     private AWSCredentials Credentials
    45.     {
    46.         get
    47.         {
    48.             if (_credentials == null)
    49.                 _credentials = new CognitoAWSCredentials(IdentityPoolId, _cognitoRegion);
    50.             return _credentials;
    51.         }
    52.     }
    53.    
    54.     private IAmazonSimpleNotificationService _snsClient;
    55.    
    56.     private IAmazonSimpleNotificationService SnsClient
    57.     {
    58.         get
    59.         {
    60.             if (_snsClient == null)
    61.                 _snsClient = new AmazonSimpleNotificationServiceClient(Credentials, _snsRegion);
    62.             return _snsClient;
    63.         }
    64.     }
    65.    
    66.     private void RegisterDevice()
    67.     {
    68.         #if UNITY_ANDROID
    69.         if(string.IsNullOrEmpty(GoogleConsoleProjectId))
    70.         {
    71.             Debug.Log("sender id is null");
    72.             return;
    73.         }
    74.         GCM.Register((regId) =>
    75.                      {
    76.            
    77.             if(string.IsNullOrEmpty(regId))
    78.             {
    79.                 //                ResultText.text = string.Format("Failed to get the registration id");
    80.                 return;
    81.             }
    82.            
    83.             //            ResultText.text = string.Format(@"Your registration Id is = {0}", regId);
    84.             Debug.Log("Your registration Id is " + regId);
    85.            
    86.             SnsClient.CreatePlatformEndpointAsync(
    87.                 new CreatePlatformEndpointRequest
    88.                 {
    89.                 Token = regId,
    90.                 PlatformApplicationArn = AndroidPlatformApplicationArn
    91.             },
    92.             (resultObject) =>
    93.             {
    94.                 if(resultObject.Exception==null)
    95.                 {
    96.                     CreatePlatformEndpointResponse response = resultObject.Response;
    97.                     _endpointArn = response.EndpointArn;
    98. //                    ResultText.text += string.Format(@"Platform endpoint arn is = {0}", response.EndpointArn);
    99.                     Debug.Log("Platform endpoint arn is " + response.EndpointArn);
    100.                 }
    101.             }
    102.             );
    103.         }, GoogleConsoleProjectId);
    104.         #elif UNITY_IOS
    105.         #if UNITY_5
    106.         UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert | UnityEngine.iOS.NotificationType.Badge | UnityEngine.iOS.NotificationType.Sound);
    107.         #else
    108.         NotificationServices.RegisterForRemoteNotificationTypes(RemoteNotificationType.Alert|RemoteNotificationType.Badge|RemoteNotificationType.Sound);
    109.         #endif
    110.         CancelInvoke("CheckForDeviceToken");
    111.         InvokeRepeating("CheckForDeviceToken",1f,1f);
    112.         #endif
    113.     }
    114.     string deviceToken = null;
    115.     //to keep a track of max number of times the device token is polled
    116.     int count = 0;
    117.     private void CheckForDeviceToken()
    118.     {
    119.         #if UNITY_IOS
    120.         #if UNITY_5
    121.         var token = UnityEngine.iOS.NotificationServices.deviceToken;
    122.         var error = UnityEngine.iOS.NotificationServices.registrationError;
    123.         #else
    124.         var token = NotificationServices.deviceToken;
    125.         var error = NotificationServices.registrationError;
    126.         #endif
    127.         if(count>=10 || !string.IsNullOrEmpty(error))
    128.         {
    129.             CancelInvoke("CheckForDeviceToken");
    130.             Debug.Log(@"Cancel polling");
    131.             return;
    132.         }
    133.        
    134.         if(token!=null)
    135.         {
    136.             deviceToken = System.BitConverter.ToString(token).Replace("-","");
    137.             Debug.Log("device token  = " + deviceToken);
    138.             //            ResultText.text = string.Format(@"Your device token is = {0}", deviceToken);
    139.             SnsClient.CreatePlatformEndpointAsync(
    140.                 new CreatePlatformEndpointRequest
    141.                 {
    142.                 Token = deviceToken,
    143.                 PlatformApplicationArn = iOSPlatformApplicationArn
    144.             },
    145.             (resultObject) =>
    146.             {
    147.                 if(resultObject.Exception==null)
    148.                 {
    149.                     CreatePlatformEndpointResponse response = resultObject.Response;
    150.                     _endpointArn = response.EndpointArn;
    151.                     //                    ResultText.text += string.Format("\n Subscribed to Platform endpoint arn = {0}", response.EndpointArn);
    152.                 }
    153.             }
    154.             );
    155.            
    156.             CancelInvoke("CheckForDeviceToken");
    157.         }
    158.         count++;
    159.         #endif
    160.     }
    161.    
    162.     private void UnregisterDevice()
    163.     {
    164.         if(!string.IsNullOrEmpty(_endpointArn))
    165.         {
    166.             SnsClient.DeleteEndpointAsync(
    167.                 new DeleteEndpointRequest
    168.                 {
    169.                 EndpointArn = _endpointArn
    170.             },
    171.             (resultObject)=>{
    172.                 if(resultObject.Exception == null)
    173.                 {
    174.                     Debug.Log("Deleted the endpoint. You will not get any new notifications");
    175.                     //                    ResultText.text = @"You will not get any new notifications";
    176.                 }
    177.             }
    178.             );
    179.         }
    180.     }
    181.  
    182.     public void ToggleNotification(bool toggle){
    183.         PlayerPrefs.SetInt("Notification",Convert.ToInt32(toggle));
    184.         if (toggle)
    185.             RegisterDevice();
    186.         else
    187.             UnregisterDevice();
    188.     }
    189. }
    190.  
    Here is my C# codes that I tried to implement the Amazon SNS to mobile application. For android was successfully to register endpoint with token. Left only the iphone keep throwing null token while trying to register.
    As further checked my Unity in Mac version was 5.3.4f1 that showing latest version.
     
  4. dinkjing

    dinkjing

    Joined:
    Apr 26, 2016
    Posts:
    5
    I tried this way also get same result as null always in iOS with 5.3.4f1.
     
  5. dinkjing

    dinkjing

    Joined:
    Apr 26, 2016
    Posts:
    5
    I tried further checked found while invoke the method NotificationServices.RegisterForNotifications, the xcode log show Method=DidRegisterRemoteNotification, Message={token}.
    Then come to NotificationServices.deviceToken, the xcode log show SendMessage: object NPBinding not found!
     
  6. dinkjing

    dinkjing

    Joined:
    Apr 26, 2016
    Posts:
    5
    I found the issue was caused by the cross platform native plugin Ultra pack that earlier imported. The plugin did modify the xcode notification service behavior when the setting of notification service enabled for the plugin. After disabled the plugin setting, it works to get token from ios again.
     
  7. siddharth3322

    siddharth3322

    Joined:
    Nov 29, 2013
    Posts:
    1,049
    I don't know why this setting remain default off in xCode 8.1

    Screen Shot 2016-11-14 at 9.35.19 PM.png

    After changing toggle to ON, its working correctly.
    Other from last 4 hours I was getting NULL from deviceToken.

    In previous version of xCode its working without any kind of settings.
    I hope this become useful to someone :)
     
  8. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
    Anyone know a way to automate this toggle so I can have it done from my Unity build?

    Solved: See this great post by @a_p_u_r_o.
     
    Last edited: Mar 28, 2017
    UniqueMonsterInc and a_p_u_r_o like this.
  9. BearHugMark

    BearHugMark

    Joined:
    Feb 21, 2016
    Posts:
    21
    You've just saved me hours! Exactly what I was hunting for. Thank you my friend!!
     
  10. senad

    senad

    Joined:
    Dec 16, 2011
    Posts:
    6
    So I turned push notification capability on in XCode but still the device token is null with UnityEngine.iOS.NotificationServices.registrationError being empty.

    However in the XCode console I only see the Debug.Log outputs from within Unity code. How do you guys get to see the XCode system logs?
     
  11. alpdogan

    alpdogan

    Joined:
    May 8, 2015
    Posts:
    10
    Hello,
    I couldn't make "ISN_RemoteNotificationsController. RegisterForRemoteNotifications" work.

    Is there anything that I need to know? Push notifications are enabled in "stans assets settings" and also "XCode capabilities. Thanks in advance.
     
  12. Anagr

    Anagr

    Joined:
    Oct 1, 2016
    Posts:
    22
    Try to enable Symlink Unity Libraries chekcbox in Build Setting
     
  13. GargGarima

    GargGarima

    Joined:
    Apr 9, 2018
    Posts:
    11
    I have done this thing also...but noting is displaying on console