iOS Push summary--swift language

Source: Internet
Author: User

Push mechanism of APNs

First, let's take a look at Apple's official explanation of the iOS push mechanism. Such as

Provider is our own program's backend server, APNs is the Apple push Notification service abbreviation, namely Apple's push server.

The iphone is, of course, our iOS device, and Cllentapp is our client program.

First stage: The server side of the application package the message to be sent, the logo of the target iphone, and send it to APNs.

Phase II: APNs in its own list of iphone's registered push services, look for an iphone with a corresponding identity and send the message to the iphone.

The third stage: The iphone sends the message to the appropriate application and follows the settings to eject the push notification.

APNs detailed workflow for push notifications

The following diagram illustrates the detailed workflow for APNs push notifications:

According to the picture we can summarize:

1, Application registration APNs message push.

2. iOS obtains devicetoken from APNs server, and the application receives device token.

3. The application sends device token to the program's push service-side program.

4. The service-side program sends messages to the APNS service.

5. The APNs service sends the message to the iphone app.

And then I'm going to work.

Start with an Apple device and the simulator doesn't support push, so you'll need a iphone,ipod touch or ipad.

A certificate is required to link between our client and Apple server and between our own server and Apple server. Let's begin the process of making the certificate.

CSR file

First we need to have a request file that generates a certificate Signing requests (that is, a CSR).

Find Keychain access in the utility in the application.

Select Request a certificate from a certification authority

Fill in your mailbox and common name, commonly used names to remember, a will be used. Then choose Save to disk to continue

Save location on desktop, click Save.

After clicking here, we will see a certificatesigningrequest.certsigningrequest request file on the desktop, which is what we call the CSR file. At the same time we generate a CSR file, we generate a pair of keys in keychain Access, the name of the common name we filled out just now

Create a development certificate and publish a certificate

(here to get everyone to see clearly I have removed before)

First we log in to the developer center Https://developer.apple.com/account/ios/identifiers/bundle/bundleList.action

Click on the app IDs click Add icon to add the app ID (if the app already has an app ID then we can just click to edit)

Click the Add button to go to the following page

Here we enter the name

Then enter the bundle ID

Tick the Push notifications option here to click Continue

Click Continue and then click Submit--"Done"

Here we can see the app ID we just added in click on it

Here we can see whether the push notifications or yellow indicates that our current ID is not yet available as a push certificate click Edit

Again here we click on Create Certificate ... button and then click Continue

We clicked Choose File ... Select we have just produced the CSR file

Click on the Generate upload and click Download to download the CER file click Done

At this point we can see that the CER file we just generated is visible in the certificates bar. Here we have made a development of a push certificate published with the same operation as above

And then we're here to apply for our development certificate.

First find the provisioning profiles bar here we are only used for development testing so select development also click the Add button icon

Select IOS App development options Click Continue

Select the app ID we just applied to click Continue

Click here to select All Continue

Click here to select All Continue

Enter name Click Continue Last Click Download we got a file called Pushdemo.mobileprovision. This file is the development certificate that we installed in Xcode

So far we've got three files of Aps_development.cer and Certificatesigningrequest.certsigningrequest and Pushdemo.mobileprovision

We double-click Aps_development.cer and pushdemo.mobileprovision respectively to install the keychain and Xcode

Push test

So far our certificate has been done. Finally can on the code, then the problem comes, since is push, that certainly need the server's cooperation, how to do?

At the moment we just want to test the push of the message on the Mac computer and use the Pushmebaby tool, which is very simple to use. The tool is open source, can be downloaded from Https://github.com/stefanhafeneger/PushMeBaby, the execution of the code is actually set up the SSL certificate, and then connect to APNs, and then send the JSON data.

Open the Pushmebaby project to copy the Aps_development.cer file we downloaded to work

In APPLICATIONDELEGATE.M, change the filename of self.certificate to the name of the. cer file that we copied to the project.

Wait a minute. We also need to change the value of the Self.devicetoken to the Devicetoken requested in our own device so our test server is done.

It is important to note that Self.payload is a JSON-formatted string, the format must be correct; the beep of the message in the sound field is the default, and there is no voice if the error is written; The badge field corresponds to the small dot number on the icon, and the type must be an integer otherwise it cannot be displayed.

Next is the development of the client

Create a new project named Pushdemo

First in the Func application (application:uiapplication, didfinishlaunchingwithoptions launchoptions: [Nsobject:anyobject]?) ---Bool {} method registration notification due to changes in system methods above iOS8 need to be judged

 var str:nsstring = Uidevice.currentdevice (). systemversion var version:float = Str.floatvalue  if  version >= 
    
     8.0 
      {uiapplication.sharedapplication (). Registerusernotificationsettings ( Uiusernotificationsettings (ForTypes:UIUserNotificationType.Sound  | Uiusernotificationtype.alert |             Uiusernotificationtype.badge, Categories:nil)) Uiapplication.sharedapplication (). Registerforremotenotifications ()}  else
     {uiapplication.sharedapplication (). Registerforremotenotificationtypes (UIR Emotenotificationtype.badge  | Uiremotenotificationtype.sound |  Uiremotenotificationtype.alert)}  

When the push registration succeeds, the system will callback the following method will get a devicetoken I copy the printed string to what we just said Self.devicetoken

func Application (application:uiapplication, Didregisterforremotenotificationswithdevicetoken DeviceToken: NSData) {        "<>")        println ("token==\ (token)")  ")        // send token to server    }

System callback when push registration fails

func Application (application:uiapplication, Didfailtoregisterforremotenotificationswitherror error:nserror) {         "" Delegate " OK " )        alert.show ()    }

Callback when a message is pushed to the device and a message is clicked to launch the app

func Application (application:uiapplication, didreceiveremotenotification userInfo: [Nsobject:anyobject]) {         println ("userinfo==\ (userInfo)")    }

UserInfo is the data that the server pushes to the client

After a long day finally to the most exciting moment, first we start our client program to get Devicetoken in the Devicetoken copy to Pushmebaby project Self.devicetoken

Restart click Push for up to a few seconds to see the push message.

So, a push demo is done.

iOS Push summary--swift language

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.