IOS development: App message push (latest), iosapp

Source: Internet
Author: User

IOS development: App message push (latest), iosapp

I haven't written a blog for a long time. Today I am going to give you a simple IOSApp message push tutorial! Everything starts from 0, including XCode6, IOS8, and how to register the application, apply for a certificate, and download the configuration profile from the apple Developer Center. I believe many people who are new to ios will want to know about it. (Ps: although I have read many good tutorials about pushing on the internet, I also learned them step by step. However, these tutorials were last year or earlier, it is not suitable for new users)

Part 1

The first step is to introduce Apple's push mechanism (APNS ), let's take a look at an overview of Apple's official explanation of its push.

Provider is the server that sends Push messages to your mobile app, while APNS (Apple Push Notification Service) is the Apple message pushing server. When your local server needs to push a message to the application, it first needs to send the message to the Apple push server, and then the apple push server sends the message to the mobile phone where the application is installed.

Next, let's look at an illustration:


Based on the logic, I will explain it to you:

1. Your IOS app needs to register the APNS message push function.

2. When the apple APNS push server receives a registration message from your application, it returns a device token to you (very important)

3. Send the device Token received by the application to your local Push server.

4. When you need to push messages to applications, your local push server will package the messages and Device tokens and send them to Apple's APNS server.

5. APNS then pushes messages to the target iphone


Part 2

1. issue a certificate from the Certificate Authority

Open your mac key string for access: Then click the key string for access

Then it will pop up a window of user email information

Enter the name of your apple developer account (which should be an email name), click the Save to disk option, and click Continue, as shown below



Click "Storage". The file name is CertificateSigningRequest. certSigningRequest. Put it in a folder and name it push!


Part 3


Visit Apple developer Website: https://developer.apple.com/

Select the MemberCenter option to go To the logon page. log in with your apple developer account. After a while, the page will automatically jump.

Click the selected part in red

Content.


Select the Certificates option and set the certificate.

The role of the Development option, as the name suggests, is used as the certificate for Development, and the Production option is

It is used to publish products. The name is unfamiliar, isn't it? The previous developer webpage does not have this option, maybe Apple modified it, and this name makes people better

Understand (literally, is it a product ). The steps for generating certificates for the two options are the same. Now we use the developer options to create certificates as follows:

Select the Development option


Click the plus sign option above,


Select the APNS option (development is in the sandbox environment, simulate the actual situation), and then Continue


This AppID is generated in the next section. Now I am using an Application ID that has been generated. Continue


Here, we need to select the CertificateSigningRequest. certSigningRequest file downloaded from the key string access link, select and generate


Click Download To get aps_development. cer and save it to the push file.


Part 4

Create an AppID, select the AppIDs on the webpage, and click the plus sign in the upper right corner"


You only need to name the App according to Apple's requirements.


Then BundleID is very important. It is required to submit for review and test (Apple's TestFlight) and pay-as-you-go, and only needs to be written according to Apple's requirements.


The next step is to select which services your application needs to use, such as advertising, game center, push, and payment.


Finally, select the "Submit" option and select the "done" option in the next interface, so that we can complete the steps for setting AppID.


Part 5: Generate Provisioning Profiles

This configuration profile is divided into two types, one for development and use, and the other for publishing to the appStore.


The process for creating the ProvisioningProfile for the release version is the same as that for the Development version. Click "Development" and then click the plus sign in the upper right corner.

The page for selecting the configuration profile is displayed.


Now we are testing, so we select the "IOS App Development" option. There are two options in the following Distribution release options: "App Store" and "Ad hoc". You can refer to the following description.

Select the options you want to release. Click Continue to go to the next step.


Select the AppID you created in the previous step and click Continue to proceed to the next step.


Select your developer account and Continue the next step.


Select your device in this step (you only need to select your device in this step before you can use this signature for debugging on the device ). How to add your device number is also very

Simply, select "Devices" on the left, click the plus sign in the upper right corner, and add the UUID of your device to the page that comes out later (you can see it in XCode) and name (you can take it as needed and understand it yourself)

Then, Register and follow the process to the final step.

Well, let's Continue to the Provisioning Profile configuration process. After you have selected your device, click "Continue" to go to the next page,


Enter a file name (it is best to start and understand what it is, and you can also start it as needed) and click "Generate" to go to the next page, there will be a Download button on this page for you to download this file,

We downloaded it and put it in the Push folder.


Part 6

Now, all preparations have been completed. Now let's start pushing! (ROAR)

First, double-click the generated "aps_development. cer" file to access the key string and find our dedicated key (based on the common name entered in the certificate authority issuing operation in section 2)


I entered "silicon" in the second part. Because I had not installed it before I switched to a mac, I did not. So I randomly asked for a picture to show it to you, it's not hard to understand it with your talents.

Right-click Export and the following figure will pop up.



Store it in the push folder and name it "push. p12". Exporting in this step will allow you to enter and verify the password. You can customize a password, such as abc123.


Now, the push folder should contain several files: "aps_development. cer", "push. p12", "CertificateSigningRequest. certSigningRequest", and the configuration summary file just now.


Next, open the terminal and generate the. pem file.

1. Generate the aps_development. cer file and cd it to the push folder.


2. Generate the push. p12 file into a. pem file.


The password you entered above is the password you exported for the certificate, that is, abc123. then, you will be asked to enter the password for the. pem file, or use abc123 to prevent confusion.

In this way, we get two more files in the push folder, PushChatCert. pem and PushChatKey. pem.


3. Combine PushChatCert. pem and PushChatKey. pem into a pem file,


A ck. pem file is added to the push folder. We have prepared all the files to be used.


Next, let's test it. Are you very excited ~

To test the certificate status, we can use "telnet gateway.sandbox.push.apple.com 2195" to check if


It indicates the operation is successful.


Then, we use the generated certificate and private key to set a secure link to the Apple Server.

Enter the following command on the terminal: openssl s_client-connect gateway.sandbox.push.apple.com: 2195-cert PushChatCert. pem-key PushChatKey. pem

Enter the password (abc123 we just set ).

Then he will return a series of data, and I will paste a part here:

CONNECTED (1, 00000003)

Depth = 1/C = US/O = Entrust, Inc. /OU = www.entrust.net/rpa is inmarshated by reference/OU = (c) 2009 Entrust, Inc. /CN = Entrust Certification Authority-L1C

Verify error: num = 20: unable to get local issuer certificate

Verify return: 0

---

Certificate chain

..... (Omitted)

..... (Omitted)

..... (Omitted)

Starting Time: 1416389389

Timeout: 300 (sec)

Verify return code: 0 (OK)

---

The test is now...


Part 7

1. Create a push Project

//// AppDelegate. m // TestPushNotifiy /// Created by silicon on 14-10-30. // Copyright (c) 2014 silicon. all rights reserved. // # import "AppDelegate. h "@ implementation AppDelegate @ synthesize mainView = _ mainView;-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {if ([application respondsToSelector: @ selector (messages)]) {// IOS8 // create UIUserNotificationSettings and set the display class type of the message. UIUserNotificationSettings * notiSettings = [UIUserNotificationSettings failed :( uiusernotiftypebadge | uiusernotiftypetypealert | category) categories: nil]; [application registerUserNotificationSettings: notiSettings];} else {// ios7 [application Extensions :( uiremotenotiftypetypebadge | uiremotenotiftypetypesound | uiremotenotiftypetypealert)];} self. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]; // Override point for customization after application launch. self. window. backgroundColor = [UIColor whiteColor]; [self. window makeKeyAndVisible]; self. mainView = [[MainViewController alloc] initWithNibName: @ "MainViewController" bundle: nil]; self. window. rootViewController = self. mainView; return YES;}-(void) application :( UIApplication *) application didRegisterForRemoteNotificationsWithDeviceToken :( NSData *) pToken {NSLog (@ "--- Token -- % @", pToken );} -(void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {NSLog (@ "userInfo =%@", userInfo); NSString * message = [[userInfo objectForKey: @ "aps"] objectForKey: @ "alert"]; UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "prompt" message: message delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil]; [alert show];}-(void) application :( UIApplication *) application didFailToRegisterForRemoteNotificationsWithError :( NSError *) error {NSLog (@ "Regist fail % @", error);}-(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 throttle down OpenGL ES frame rates. games shocould 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 .} -(void) applicationWillEnterForeground :( UIApplication *) application {// Called as part of the transition from the background to the inactive state; here you can undo records 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 previusly in the background, optionally refresh the user interface .} -(void) applicationWillTerminate :( UIApplication *) application {// Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :.} @ end

Add the above Code to appdelegate. m,

If ([application respondsToSelector: @ selector (isRegisteredForRemoteNotifications)]) {// IOS8 // create UIUserNotificationSettings, set the display class type of the message. UIUserNotificationSettings * notiSettings = [UIUserNotificationSettings failed :( uiusernotiftypetypebadge | UIUserNotificationTypeAlert | alert) categories: nil]; [application registerUserNotificationSettings: notiSettings]} else {// ios7 [application registerForRemoteNotificationTypes :( UIRemoteNotificationTypeBadge | uiremotenotiftypetypesound | uiremotenotiftypetypealert)];}
Because the push of ios8 is different from that of ios7 and below, you need to add judgment to register message push.

Function:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken{    NSLog(@"---Token--%@", pToken);}
It will receive the deviceToken from the apple server, and then you need to add it to your local push server. (It is very important to determine whether your device can receive push messages ).

-(Void) application :( UIApplication *) application didReceiveRemoteNotification :( NSDictionary *) userInfo {NSLog (@ "userInfo =%@", userInfo); NSString * message = [[userInfo objectForKey: @ "aps"] objectForKey: @ "alert"]; UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "prompt" message: message delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: @ "OK", nil]; [alert show];}

This function is triggered when the device receives a message from the apple push server and is used to display the PUSH message.

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{    NSLog(@"Regist fail%@",error);}
This function is triggered when registration fails.


2. PHP server

Put the simplepush. php push script in the push folder.

<?php// ??????????deviceToken???????????????$deviceToken = 'c95f661371b085e2517b4c12cc76293522775e5fd9bb1dea17dd80fe85583b41';// Put your private key's passphrase here:$passphrase = 'abc123';// Put your alert message here:$message = 'My first push test!';////////////////////////////////////////////////////////////////////////////////$ctx = stream_context_create();stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);// Open a connection to the APNS server//?????????? //$fp = stream_socket_client(?ssl://gateway.push.apple.com:2195?, $err, $errstr, 60, //STREAM_CLIENT_CONNECT, $ctx);//?????????????appstore??????$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err,$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);if (!$fp)exit("Failed to connect: $err $errstr" . PHP_EOL);echo 'Connected to APNS' . PHP_EOL;// Create the payload body$body['aps'] = array('alert' => $message,'sound' => 'default');// Encode the payload as JSON$payload = json_encode($body);// Build the binary notification$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;// Send it to the server$result = fwrite($fp, $msg, strlen($msg));if (!$result)echo 'Message not delivered' . PHP_EOL;elseecho 'Message successfully delivered' . PHP_EOL;// Close the connection to the serverfclose($fp);?>
Set deviceToken to the token you received, and passPhrase to the password set for your ck. pem.

Now is the time to witness the miracle.

Use the terminal to enter the push folder, and enter php simplep. php on the terminal.


If the above prompt is displayed, the push is successful.

A success diagram is attached.



Push it here!

Thanks for this blog: http://blog.csdn.net/showhilllee/article/details/8631734


I will upload simpush. php and XCode projects to my resources. You can download them over there. If you do not understand anything, you can leave a message or send a private message to me. I will reply to you first ~
















Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.