Xcode Push SDK Setup


SDK contents


Once you've downloaded and unzipped the PUSHTech™ SDK, you'll find two directories:

  • Documentation folder: contains the SDK documentation as plain HTML formatted as Apple do and as Xcode docset.

  • PushTechSDK folder: contains the PushTechSDK.framework and PushTechSDKResources.bundle files.

  • PushTechSDKDemo folder: contains the demo project for the PushTechSDK.

Xcode Project Setup


  • Drag and drop the PushTechSDK folder into your project and make sure 'Copy items if needed' , 'Create folder references' and your project's target are selected on the import dialog.

  • Ios push sdk setup 2
  • To be able to fetch notification data in the background, your app must support remote notification background modes:

  • Ios push sdk setup background modes
  • If you don't use cocoapods yet, it's time to visit the CocoaPods site and install the awesome CocoaPods dependency manager.

  • Once you have CocoaPods installed, create a text file named 'Podfile' in your project's folder like so:

  • Ios push sdk setup 3
  • Your project must use MagicalRecord for the SDK to work:

  • platform :ios, '7.0'
    inhibit_all_warnings!
    
    target 'YourProjectName' do
    
      pod 'MagicalRecord', '2.2'
    
      #Add your project's depencencies here.
    
    end
  • Fire up your favourite terminal, navigate to your project's folder, and run pod install.

  • If cocoapods suceeded with the project's setup, you're ready to start using the PushTechSDK.

Implementation


Import the required header files

At the top of you application delegate, import the umbrella header file:

#import <PushTechSDK/PushTechSDK.h>

Setup your AppDelegate

Paste this code in your -application:didFinishLaunchingWithOptions: method in the AppDelegate.

[PSHEngine startWithEventBusDelegate:self.eventBusDelegate = [EventBusDelegate new]
                notificationDelegate:self.notificationDelegate = [NotificationDelegate new]];
  • The class EventBusDelegate must conform to protocol PSHEventBusDelegate. It's not necessary to be a separated classe (could be the AppDelegate itself) although it is strongly advisable.

  • The class NotificationDelegate must conform to protocol PSHNotificationDelegate. Just like the Event Bus case, it could be the AppDelegate but is better to create an independant class for it.

  • Is absolutely necessary to add a new PLIST file to the project, named PSHConfiguration.plist containing the notification types (alert, sound, badge), as well as the AppSecret and AppID:

  • <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>notificationTypes</key>
        <dict>
            <key>alert</key>
            <true/>
            <key>sound</key>
            <true/>
            <key>badge</key>
            <true/>
        </dict>
        <key>applicationSecret</key>
        <string>YOUR_APP_SECRET_HERE</string>
        <key>applicationID</key>
        <string>YOUR_APP_ID_HERE</string>
    </dict>
    </plist>
    

The EventBusDelegate class is responsible of receiving all the SDK related events. All methods of the protocol are optional, nothing bad happens if none of them are implemented. There is one method for each event:

#import <Foundation/Foundation.h>
#import <PushTechSDK/PushTechSDK.h>

@interface EventBusDelegate : NSObject <PSHEventBusDelegate>

@end
#import "EventBusDelegate.h"

@implementation EventBusDelegate

- (void)onDidRegisterForRemoteNotificationsBusEvent:(NSNotification *)notification
{
    NSString *deviceToken = [PSHModel sharedInstance].managerInfo.pushToken;
    NSLog(@"Remote push notification token: %@", deviceToken);
}

- (void)onDidFailToRegisterForRemoteNotificationsBusEvent:(NSNotification *)notification
{
    NSLog(@"Failed to register push token.");
}

- (void)onSuccessfulAppRegistrationBusEvent:(NSNotification *)notification
{
    NSLog(@"SuccessfulAppRegistration");
}

- (void)onSuccessfulDeviceIdBusEvent:(NSNotification *)notification
{
    NSString *deviceId = [PSHEngine sharedInstance].deviceId;
    // Need a DeviceID to be able to send notifications using the PUSH Techoloigies server API.
    // The app will normally send the DeviceID to a backend server that later will use it to send
    // requests to the PUSH Tecnologies server.
    NSLog(@"Received DeviceID = %@.", deviceId);
}

- (void)onSDKVersionDowngradedBusEvent:(NSNotification *)notification
{
    NSLog(@"SDK version downgraded: %f", [PSHModel sharedInstance].managerInfo.currentSDKVersion);
}

- (void)onSDKVersionUpgradedBusEvent:(NSNotification *)notification
{
    NSLog(@"SDK version upgrade: %f", [PSHModel sharedInstance].managerInfo.currentSDKVersion);
}

@end

The NotificationDelegate class is responsible of receiving the PUSHTech™ notifications and campaings. There is only one delegated method on this protocol and is required, must be implemented in order to get the SDK working:

#import <Foundation/Foundation.h>
#import <PushTechSDK/PushTechSDK.h>

@interface NotificationDelegate : NSObject <PSHNotificationDelegate>

@end
#import "NotificationDelegate.h"

@implementation NotificationDelegate

- (BOOL)shouldPerformDefaultActionForRemoteNotification:(PSHNotification *)notification
                                      completionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    if ([self applicationIsInBackground]) {
        // App is in background
    } else {
        if (notification.defaultAction == PSHNotificationDefaultActionLandingPage) {
            // The notification contains a landing page. Return NO here if your app will handle landing pages by its own
        } else {
            // The notification is a normal push, explore "notification" object to extract poyload like:
            // notification.campaign.title
            // notification.campaign.text
            // ...
        }
    }

    // Do default action, return NO when the app implements a custom action
    return YES;
}

- (void)performInteraction:(NSString *)actionID onNotification:(PSHNotification *)notification {

    // Handle your interactive Push notification when a user select one of the options (e.g: "Buy now" clicked)
    NSLog(@"PUSH action = %@ on notification = %@", actionID, notification);
}

Finally there is only one step left, configure your app's Info.plist to allow geolocation:

<key>NSLocationAlwaysUsageDescription</key>
<string>Write a message why the user need to share Geolocation</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Write a message why the user need to share Geolocation</string>
<key>NSLocationUsageDescription</key>
<string>Write a message why the user need to share Geolocation</string>

And disable the App Transport Security to be able to open any landing page:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

Congratulations! You can start using the SDK on your own with the documentation provided with the SDK. If you had problems setting up your project or anything strange happened, you can take a look to the Demo project and check if your setup is allright.

Send Metrics

Metrics are used to send information about the user or application usage to PUSHTech™ servers. All metrics are sent through the PSHMetrics class:

// Custom metrics
[PSHMetrics sendCustomMetricBoolean:YES type:@"boolean_type" subtype:@"boolean_subtype"];

[PSHMetrics sendCustomMetricDate:[NSDate date] type:@"date_type" subtype:@"date_subtype"];

[PSHMetrics sendCustomMetricString:@"This is a string" type:@"string_type" subtype:@"string_subtype"];

[PSHMetrics sendCustomMetricNumber:@(123.456) type:@"number_type" subtype:@"number_subtype"];

// Model metrics
[PSHMetrics sendMetricGender:PSHGenderTypeMale];

[PSHMetrics sendMetricBirthday:[NSDate date]];

[PSHMetrics sendMetricCarrierName:@"AT&T"];

[PSHMetrics sendMetricCity:@"New York"];

[PSHMetrics sendMetricCountry:@"US"];

[PSHMetrics sendMetricFacebookFriends:1234];

[PSHMetrics sendMetricFacebookLogin];

[PSHMetrics sendMetricTwitterFollowers:1234];

[PSHMetrics sendMetricTwitterLogin];

[PSHMetrics sendMetricGoogleLogin];

[PSHMetrics sendMetricFirstName:@"John"];

[PSHMetrics sendMetricLastName:@"Doe"];

[PSHMetrics sendMetricEmail:@"email@email.me"];

[PSHMetrics sendMetricPhone:@"+15417543010"];

// Purchase metrics
[PSHMetrics sendMetricCartProducts:4 onChange:YES];

[PSHMetrics sendMetricAddCartProduct:@"iPad 5 Pro" productId:@"happle5j38d7" price:@(633.55) currency:@"USD"];

[PSHMetrics sendMetricDeleteCartProduct:@"Nexus 7" productId:@"hatarikdd7" price:@(233.55) currency:@"USD"];

PSHProduct *iphone6Product = [[PSHProduct alloc] initWithProduct:@"iPhone 6" productId:@"h92j38d7" price:@(799.99) currency:@"USD"];
PSHProduct *headsetProduct = [[PSHProduct alloc] initWithProduct:@"Headset" productId:@"67f5ae09" price:@(89.99) currency:@"USD"];
[PSHMetrics sendMetricPurchaseProducts:@[iphone6Product, headsetProduct]];

// Other metrics, please check PUSHTech iOS References documentation for more metrics...

// Metrics are automatically sent by the SDK every 5 minutes, or using "forceSendMetrics" will send immediately
[PSHMetrics forceSendMetrics];

Metrics could include the current location, but by default it is disabled. To configure the location adquisition do it after calling PSHEngine initializeWithAppId:

// Never use location on metrics
[[PSHEngine sharedInstance] setLocationAdquisition:PSHLocationStateTypeNever];

// Always use current location on metrics
[[PSHEngine sharedInstance] setLocationAdquisition:PSHLocationStateTypeAlways];

// Provide manually the location metric with a CLLocation.
[[PSHEngine sharedInstance] setLocationAdquisition:PSHLocationStateTypeManual];
[PSHMetrics sendMetricLocation:location];

The iOS sample app is available on GitHub.

PUSHTech™ GitHub Repository