roblav96 / nativescript-onesignal

A Nativescript plugin that wraps the iOS and Android OneSignal Push Notifications SDK.
https://documentation.onesignal.com/docs/getting-started
Other
24 stars 42 forks source link

How to get player id after registered device by using idsAvailable #5

Open kentplaza opened 7 years ago

kentplaza commented 7 years ago

I added idsAvailable after registered successfully as below but got error and failed to return any player id: TnsOneSignal.idsAvailable(function(userId,registrationId) { console.log("OneSignal User ID:", userId); });

Error: JS: error Error: Cannot convert object to Lcom/onesignal/OneSignal$IdsAvailableHandler; at index 0

roblav96 commented 7 years ago

The current state of this plugin only exposes the native OneSignal class on ios and the com.onesignal.OneSignal class on android.

I'll be making some changes to make this more of a plugin rather than a wrapper.

kentplaza commented 7 years ago

thanks for fast response.

TnsOneSignal just a variable.

im using class OneSignal and sucessfully register into onesignal. Just i failed to retrieve player id by using OneSignal.idsAvailable.

what your nean idsAvailable method not expose in this plugin? mean i cant use this method to get the player id?

davecoffin commented 7 years ago

@kentplaza I am using IdsAvailable to get the player ID. Maybe your problem is you arent calling the method correctly, its IdsAvailable, not idsAvailable

kentplaza commented 7 years ago

@davecoffin I tried IdsAvailable. No luck.

tushar-1health commented 7 years ago

Any update on this I am facing the same issue as @kentplaza . Help needed.

roblav96 commented 7 years ago

@kentplaza @tushar-1health

Android

export class OneSignalClass extends OneSignalCommonClass {

    private static parseJson(json: org.json.JSONObject) {
        return (json) ? JSON.parse(json.toString()) : json
    }

    init(nativeApp: android.app.Application) {
        com.onesignal.OneSignal.startInit(nativeApp)
            .autoPromptLocation(false)
            .inFocusDisplaying(com.onesignal.OneSignal.OSInFocusDisplayOption.None)

            .setNotificationReceivedHandler(new com.onesignal.OneSignal.NotificationReceivedHandler(<com.onesignal.OneSignal.NotificationReceivedHandler>{
                notificationReceived: function(notification: com.onesignal.OSNotification) {
                    OneSignalClass.onReceived({
                        title: notification.payload.title,
                        body: notification.payload.body,
                        data: OneSignalClass.parseJson(notification.payload.additionalData),
                    })
                },
            }))

            .setNotificationOpenedHandler(new com.onesignal.OneSignal.NotificationOpenedHandler(<com.onesignal.OneSignal.NotificationOpenedHandler>{
                notificationOpened: function(result: com.onesignal.OSNotificationOpenResult) {
                    OneSignalClass.onOpened({
                        opened: result.action.type == com.onesignal.OSNotificationAction.ActionType.Opened,
                        data: OneSignalClass.parseJson(result.notification.payload.additionalData),
                    })
                },
            }))

            .init()

        com.onesignal.OneSignal.idsAvailable(new com.onesignal.OneSignal.IdsAvailableHandler(<com.onesignal.OneSignal.IdsAvailableHandler>{
            idsAvailable: OneSignalClass.idsAvailable,
        }))
        com.onesignal.OneSignal.setSubscription(true)
    }

}

iOS

export class OneSignalClass extends OneSignalCommonClass {

    private static parseJson(dict: NSDictionary<any, any>) {
        if (!dict) {
            return dict
        }
        let data = NSJSONSerialization.dataWithJSONObjectOptionsError(dict, NSJSONWritingOptions.PrettyPrinted)
        let results = NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding)
        return JSON.parse(<any>results)
    }

    init(launchOptions: NSDictionary<any, any>) {
        let opts = NSMutableDictionary.new()
        opts.setValueForKey(false, 'kOSSettingsKeyAutoPrompt')
        opts.setValueForKey(false, 'kOSSettingsKeyInAppLaunchURL')
        opts.setValueForKey(OSNotificationDisplayType.None, 'kOSSettingsKeyInFocusDisplayOption')
        OneSignal.initWithLaunchOptionsAppIdHandleNotificationReceivedHandleNotificationActionSettings(
            launchOptions,
            '<ONESIGNAL_ID>',

            function receivedCallback(notification: OSNotification) {
                OneSignalClass.onReceived({
                    title: notification.payload.title,
                    body: notification.payload.body,
                    data: OneSignalClass.parseJson(notification.payload.additionalData),
                })
            },

            function actionCallback(result: OSNotificationOpenedResult) {
                OneSignalClass.onOpened({
                    opened: result.action.type == OSNotificationActionType.Opened,
                    data: OneSignalClass.parseJson(result.notification.payload.additionalData),
                })
            },

            opts
        )

        OneSignal.IdsAvailable(OneSignalClass.idsAvailable)
        OneSignal.setSubscription(true)
    }

    registerForPushNotifications() {
        OneSignal.registerForPushNotifications()
    }

}
davorpeic commented 7 years ago

Hi @roblav96 , thanks for the examples, any change you could provide how we can actually use this snippets? I made special provider with this code, but I have bunch of typings errors, I included both typings (they are not in npm btw, so I moved them manually).

I tried to replace code in main.ts with this but I get

***** Fatal JavaScript exception - application has been terminated. *****
roblav96 commented 7 years ago

OneSignalCommonClass is your own class. You don't have to make these calls from a class.

davorpeic commented 7 years ago

Could you find time to provide how and where would you put this code so it actually works? I managed to buildup some callback functions based in Readme docs, but your solution looks much prettier :)

thanks

tushar-1health commented 7 years ago

An example of this implementation (idsAvailable) in demo would help alot.

roblav96 commented 7 years ago

@tushar-1health @davorpeic

Refer to /typings

https://github.com/roblav96/nativescript-onesignal/tree/master/typings You guys really need to learn how to read typescript before writing it.

Android

com.onesignal.OneSignal.idsAvailable(new com.onesignal.OneSignal.IdsAvailableHandler(<com.onesignal.OneSignal.IdsAvailableHandler>{
    idsAvailable: function (id) {
        console.log('id', id)
    },
}))

iOS

OneSignal.IdsAvailable(function (id) {
    console.log('id', id)
})
davorpeic commented 7 years ago

Lol true, but also making library wrapper and not providing documentation on how to use it, it's also almost useless as not having the wrapper at all :)

rags22489664 commented 7 years ago

This is how I managed to do it in case some body is still looking for this.

install tns-platform-declarations by following below

http://docs.nativescript.org/angular/core-concepts/accessing-native-apis-with-javascript.html

then append below to your references.d.ts

declare module com {
    export module onesignal {
        export class OneSignal extends java.lang.Object {
            public static idsAvailable(param0: com.onesignal.OneSignal.IdsAvailableHandler): void;
        }
        export module OneSignal {
                export class IdsAvailableHandler extends java.lang.Object {
                /**
                 * Constructs a new instance of the com.onesignal.OneSignal$IdsAvailableHandler interface with the provided implementation.
                 */
                public constructor(implementation: {
                    idsAvailable(param0: string, param1: string): void;
                });
                public idsAvailable(param0: string, param1: string): void;
            }
        }
    }
}

in main.ts (or anywhere you like)

import * as application from 'application';
var TnsOneSignal = require('nativescript-onesignal').TnsOneSignal

if (application.android) {
    application.on(application.launchEvent, function (args: application.ApplicationEventData) {
        try {
            TnsOneSignal.startInit(application.android.context).init();
            TnsOneSignal.idsAvailable(new com.onesignal.OneSignal.IdsAvailableHandler({
                idsAvailable: (arg1: string, arg2: string) => {
                    console.log(arg1);
                    console.log(arg2);
                }
            }));
        } catch (error) {
            console.error('error', error)
        }
    });
}
dgome commented 6 years ago

I'm late, but you could do the following that works for me:

            TnsOneSignal.startInit(application.android.context).init();

            var status=TnsOneSignal.getPermissionSubscriptionState();
            console.dir(status.getSubscriptionStatus().getUserId());

https://documentation.onesignal.com/docs/android-native-sdk#section--getpermissionsubscriptionstate-

markosole commented 5 years ago

Hi guys, I got device Ids on Android and iOS and app registers on OneSignal. But I can not unsubscribe using OneSignal.setSubscription(false); and I tried TnsOneSignal.setSubscription(false); but non of them does not work.

Here is my code (sorry it's TS converted to JS).

 if (application.ios){  
    var __extends = (this && this.__extends) || (function () {
        var extendStatics = function (d, b) {
            extendStatics = Object.setPrototypeOf ||
                ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
                function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();

    var MyDelegate = /** @class */ (function (_super) {
        __extends(MyDelegate, _super);
        function MyDelegate() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        MyDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (app, 
 launchOptions) {
            try { 
                //  ID OneSignal
                TnsOneSignal.initWithLaunchOptionsAppId(launchOptions, '<MY_ONESIGNAL_ID>');
                // Show OneSignal device ID
                OneSignal.IdsAvailable(function (id) {
                    console.log('OneSignal ID is: ', id);
                })
                OneSignal.setSubscription(false);
            }
            catch (error) {
                console.log('error', error);
            }
            return true;
        };
        MyDelegate.ObjCProtocols = [UIApplicationDelegate];
        return MyDelegate;
    }(UIResponder));
    application.ios.delegate = MyDelegate; 
 }

App stays subscribed all the time. Can someone help with this pls. It's not totally related to issue. Thanks in advance