The article is a bit long, please read it carefully

By chance, the project of the company needed push. I was very lazy and didn’t want to make the whole APNS process. Just before, I talked with my friends about the Android push integrated with Push and said it was a good experience, so I will try their iOS push. So holding the mentality of trying, I first built a demo, tried to integrate a push iOS push SDK, groped to complete the whole process, back to business, directly on the hard food!

How to integrate iOS SDK look at the official website of iOS SDK, found that they have two ways of integration, respectively XCode integration and CocoaPods integration. I am more lazy, the simpler the better, the more relaxed the better, without hesitation to choose Cocoapods integration means, program ape, it is to try every means of lazy, do!

CocoaPods Integration 1. Install CocoaPods

The installation method is simple, the Mac has its own Ruby, ruby gem command can be downloaded and installed:

$ sudo gem install cocoapods
$ pod setup
Copy the code

2. Prepare the Podfile

In our project directory, create a new file named Podfile and list the names of the dependent libraries in the file as follows:

The authors are using the standard version here:

target 'GeTuipush' do
    platform :ios, "7.0"
    pod 'GTSDK'
end

target 'NotificationService' do
    platform :ios, "10.0"
    pod 'GTExtensionSDK'
end
Copy the code

Recommend the article

Click to enter group communication password: 111Get the big factory interview questions

3. Complete the GTSDK import

In the project root directory, run the following command:

$ pod install
Copy the code

After execution, the project directory structure is as follows:

Note: Before pod install, your project must be created, and if you have target: NotificationService in your Podfile, you need to create the target of the notification extension before Pod install.

4. Enable the push function: Since it is push, of course it is to enable the push function! :

5. Background operation permission setting: It says on the official website of A tweet that it is in order to better support message push, provide more push styles, and improve the message arrival rate. Since that is said, let’s open it first, as shown below:

6.XCode10 suggests enabling WiFi Information: In Xcode 10 and up, find Capabilities -> Access WiFi Information in the app Target Settings, and make sure the switch is set to ON. As shown below:

Note: Both the primary Target and the Target of the notification extension need to be turned on

7 code part, down is our favorite part of the program ape, paste and copy. Because it is the first time to integrate the SDK code, I still carefully studied the next.

1. Add the callback interface class to the AppDelegate:

#import <UIKit/UIKit.h>
#import <GTSDK/GeTuiSdk.h>/ / iOS10 and above to import UserNotifications framework#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate : UIResponder <UIApplicationDelegate, GeTuiSdkDelegate, UNUserNotificationCenterDelegate>

@property (strong, nonatomic) UIWindow *window;


@end
Copy the code

2. Initialize SDK and register APNs:

#import "AppDelegate.h"/// AppId, AppKey, AppSecret registered when applying for App in the website of a twitter developer#define kGtAppId @"GVZZTqh7lu6S4VLMacneZ7"
#define kGtAppKey @"RRYDFjGzO17TJXZfGeTuq3"
#define kGtAppSecret @"7BXDJ0IgWF6a8M0xCgo4G"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point forcustomization after application launch. [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self]; / / registered APNs [self registerRemoteNotification];returnYES; } Register APNs to obtain DeviceToken: / registered APNs * / * * - (void) registerRemoteNotification {UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {if(! error) { NSLog(@"request authorization succeeded!"); }}]; [[UIApplication sharedApplication] registerForRemoteNotifications]; }Copy the code

Demo for developers to provide demo code, according to the APP supported by the iOS system, modify. Our project supports iOS10 at a minimum.

Get CID information:

/** SDK startup success returns cid */

  • (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {

    NSLog(@”clientId:%@”, clientId); } kGtAppId, kGtAppKey, kGtAppSecret I went back and looked at the official website of the next tweet to find out that it just recorded how to apply for three parameters, which were bound to my application bundleID.

How to obtain kGtAppId, kGtAppKey, and kGtAppSecret

1. Create a Twitter developer account

Visit the Twitter developer Center to set up a Twitter account

2. Register a new app

Note: Registering new apps is on the app administration page, not the push page.

Fill in the application name and application description in the application registration interface, select “Push product”, “iOS”, and fill in the package name and bundleID, as shown below:

Submitted after the success to obtain kGtAppId, kGtAppKey, kGtAppSecret, three parameters will fill in our project, then run the project, in GeTuiSdkDidRegisterClient callback methods to get to the cid, well, It seems that we have succeeded in a small part, from success to continue to refueling.

Register DeviceToken and count the hits of APNs notifications 1. Register DeviceToken with each push server:

/** Remote notification of registration success delegate */

  • (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { For the convenience of developers, it is recommended to use the new method NSLog(@”deviceToken:%@”,deviceToken); [GeTuiSdk registerDeviceTokenData:deviceToken]; } 2. Handle the APNs notification click event:

Because our project is at least compatible with iOS10, here I only add iOS10 and later versions of the notification click event, if you want to compatible with iOS10 below, can be found in the demo.

IOS 10 and later handles APNs notification click events

// iOS 10: triggered when you click the notification to enter the App, count the number of valid user clicks in this method

  • (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    NSLog (@ didReceiveNotification: “% @”, the response. The notification, request the content. the userInfo);

    / / / GTSdk: push the APNs received a message to a statistical [GeTuiSdk handleRemoteNotification: response. The notification, request the content. the userInfo];

    completionHandler(); }

3. Accept transparent messages sent by each push channel:

As a developer, it is particularly important to have a learning atmosphere and a communication circle. This is my iOS communication group: 651612063, enter the group password 111, no matter you are small white or big bull, welcome to enter, share BAT, Ali interview questions, interview experience, discuss technology, we exchange learning and growth together!

/** SDK receives a passthrough message callback */

  • (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId AndOffLine :(BOOL)offLine fromGtAppId:(NSString *)appId {NSString *payloadMsg = nil; if (payloadData) { payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding]; }

    NSString *msg = [NSString stringWithFormat:@”taskId=%@,messageId:%@,payloadMsg:%@%@”,taskId,msgId, PayloadMsg,offLine? @”< offLine > : @””]; NSLog(@”\n>>>[GexinSdk ReceivePayload]:%@\n\n”, msg); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} Because I am also the first time to push this book, but also stepped on a lot of pit, in order to next time no longer step on the same pit, so here on how to make push certificate for a neat.

How to make a push certificate?

  • 1. Go to The Apple Developer Center and select the certificate option, as shown below:

  • 2. Before creating the push certificate, you must create an APPID, because the push certificate is bound to the APPID, as shown below:

Select Allow Push Notifications from App Services below, as shown below:

At this time, we need to upload the CSR file. We go back to the desktop, open the key chain, apply for the certificate from the authority and save it to the local disk, as shown in the picture below:

Now that the CSR file is created, we go back to the Apple Developer Center and continue to create our push certificate. Select the CSR file to save locally, as shown below:

In this way, our push certificate has been created. Find the downloaded push certificate in the local download and double click to add it to the keystring. Then open the keystring to find the created push certificate, right click to export the P12 certificate and enter the certificate password, as shown below:

4. Open our App Developer center and upload the correct APNs certificate in app · Message Push – App List – App Configuration, as shown below:

Now comes the most important moment, which is the test, to see if our push can succeed.

Push the test

As a developer, it is particularly important to have a learning atmosphere and a communication circle. This is my iOS communication group: 651612063, enter the group password 111, no matter you are small white or big bull, welcome to enter, share BAT, Ali interview questions, interview experience, discuss technology, we exchange learning and growth together! I did the push test on a push platform. Click the “Create push” button on the previously created app in the list of apps, as shown in the picture below:

After entering, I mentally, because did not understand before pushing the logic of the SDK, after asking a push technical support, technical support to tell me how to plow in a platform to push above, also is too careless, others go in the first sentence and then write very clear, push notification is currently only support android users, please use the iOS passthrough news. Embarrassed! Try tweeting on the passthrough message page. As shown below:

APNs message test

NICE, apps will now receive push notifications when they are in the foreground, in the background, and when they are killed. Looks like we’ve got 90 percent of it!

Notification Service Extension was smugly when I suddenly found that there was multimedia push on the official website of Notification Service Extension. Oh, my god, there is such an operation. Out of curiosity, I re-examine how to do multimedia push. Since we’ve already created the target for the notification extension, we’ll go straight to the code.

1. After NotificationService Extension is successfully added, two classes notificationService. h and NotificationService.m will be automatically generated in the project, which contain the following two methods:

  • (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *_Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy];

    // [test code] TODO: the user can handle the notification style changes here, eg: modify the header, Development phase can be used to judge whether running inform extension / / self bestAttemptContent. Title = [nsstrings stringWithFormat: @ “% @ [WillIn].” self.bestAttemptContent.title];

    // [GTSDK] statistics APNs arrival and multimedia push support interface, It is recommended to use this interface [GeTuiExtSdk handelNotificationServiceRequest: request withAttachmentsComplete: ^ (NSArray * attachments, NSArray *errors) {

    // self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [Success]", self.bestAttemptContent.title]; self.bestAttemptContent.attachments = attachments; // Set the multimedia attachment in the notification self.contenthandler (self.bestatTemptContent);Copy the code

    }]; } We can process our APNs notifications in this method and personalize them to the user. This method is called when the APNs push message arrives, at which point you can process the push content and then use the contentHandler method to end the process. But if the processing time is too long, will enter serviceExtensionTimeWillExpire method finally the emergency treatment.

  • (void) serviceExtensionTimeWillExpire {/ / [GTSDK] destroyed the SDK, release resources [GeTuiExtSdk destory];

    //self.bestAttemptContent.title = [NSString stringWithFormat:@”%@ [Timeout]”, self.bestAttemptContent.title];

    self.contentHandler(self.bestAttemptContent); } if didReceiveNotificationRequest method without calling contentHandler methods end treatment in the limited time and will be back before the expiration of this method. At this point you can display your APNs messages after urgent processing, or display the original APNs push if there is no processing.

The next step was to test the success of our multimedia push. I found a picture of a puppy on the Internet and pushed it directly onto a push platform.

Multimedia testing

6 Ah, finally done! Bang bang da ~ ~ ~

However, an old project said to integrate push, I know, the old project to use XCode integration, it is a kind of torture for lazy people like me, ah, torture is torture, should do it. But having done this with CocoaPods before, it’s not easy to integrate with XCode this time. But in order to prevent mistakes, I still do a demo, so that later in their own projects above the integration will be more control, step on the pit will be less.

XCode integration 1. Import push SDK:

2. Library reference check:

3. Add system dependency library:

libc++.tbd libz.tbd libsqlite3.tbd libresolv.tbd Security.framework MobileCoreServices.framework SystemConfiguration.framework CoreTelephony.framework AVFoundation.framework CoreLocation.framework UserNotifications. Framework (iOS 10 and above need to add, use the Optional way access) AdSupport. The framework (if you use no IDFA version of the SDK, need to delete the AdSupport library)Copy the code

4. Enable the push function, background operation permission setting, and WiFi information authorization

Here is the same as the above steps, not so verbose.

5 copy code, this is our favorite program ape, ha ha ha, before doing, here is not cumbersome.

6. Add Notification Service Extension

(1). Open XCode and choose File->New->Target->Notification Service Extension. As shown below:

Note :1. The Extension Bundle Identifier must not be the same as the Main Target Bundle Identifier, otherwise the Extension Bundle id will be repeated. 2. The Bundle Identifier of Extension must be in the namespace of the Main Target. For example, the BundleID of the Main Target is ent.getui.xxx. The Extension BundleID should be similar to ent.getui.xxx.yyy. Failure to do so will cause a naming error.

This is in a twitter official website above see, before myself also stepped on this pit, here to record.

The corresponding Target is generated after the Notification Service Extension is added. Click Finish and the option box for activating the scheme corresponding to the Target will be displayed. Select Activate. If the option box is not displayed, you need to add the corresponding scheme. As shown below:

(2). Notificationservice. h and NotificationService.m classes will be automatically generated in the project after NotificationService Extension is successfully added

This is the same as up here, so it’s not a drag.

(3). Add GtExtensionSdk dependency library

Select the Target corresponding to the Notification Service Extension and add the following dependent libraries:

libz.tbd
libsqlite3.tbd
GTExtensionSDK.framework
UserNotifications.framework
Copy the code

(4).XCode10 suggests enabling WiFi Information authorization: In Xcode 10. X above, find Capabilities -> Access WiFi Information in the app Target Settings, and make sure the switch is set to ON. As shown below:

(5). Enable multimedia address Http access support:

What impressed me most was the invalid deviceToken. When TESTING APNS push, I asked the technical support of the push side, and they said they could test it in the application configuration first. Then I took my deviceToken to test it. The result showed me that it was invalid deviceToken, I was dizzy, and then I continued to consult the technical support of Getui, they said that the reason might be the problem of my certificate environment. After a careful check, I found that the certificate I passed on the platform was a general certificate, and the authorization certificate on my XCode was in the development environment, so I got the deviceToken in the development environment, and tested it, of course, there would be errors. There are two solutions: first, upload the push certificate under the development environment on the push development platform. Second: replace your certificate of authorization with the production environment.

Notify the extension modify title code does not effect the self inside. BestAttemptContent. Title = [nsstrings stringWithFormat: @ “% @ [Success],” self.bestAttemptContent.title]; I found such a line of code in the demo. When I opened this line of code, I pushed a message and found that the title had not changed. I was shocked! Let me run the main target first, and then run the notification extension. Running the notification extension will send us to the main targetAPP, select the main target, and then push it.

Finally, I’d like to say that the integration of push notifications is really, really important for apps. The above is a push iOS push SDK integration full steps, for everyone to do a reference. In particular, the following points should be noted:

1. The push certificate uploaded on each push platform must be correct and corresponding to your environment. It is recommended to upload the P8 certificate.

2. The main target and the notification extension target are two different targets. Note that the bundleID and the main target are named according to the suggestions on the twitter website.

recommended

Recommend the article

Click into the group exchange to get 2020 factory interview password: 111