iOS开发中通知(Notification)快速入门及推送通知实现教程

iOS开发中通知(Notification)快速入门及推送通知实现教程

标签: NSNotificationCenterNSNotification
 分类:

转载自:http://www.111cn.NET/sj/ios8/90190.htmphp

 

 

通知(Notification)是开发框架中观察者模式的一种实现方式,内部的实现机制由Cocoa框架支持,一般用于试图控制器和数据模型的交互。经过通知,能够向一个或者多个对象发送消息。

继承自NSObject,实现了NSCopying Protocol协议。

通知经过通知中心(NSNotificationCenter)广播给其余对象。通知包含一个名称(name), 对象(object属性), 和一个可选字典(dictionary 属性)三个参数。这些参数协助完成通知操做。

 
通知的原理                                                  

Notification一个 对象很是简单,就是poster要提供给observer的信息包裹。Notification 对象有两个重要的成员变量:name和object。通常name用来惟一标示一个通知对象,object都是指向发送者(poster)(为了让observer在接收到notification时能够回调到poster)因此,Notification有两个方法:- (NSString *)name, - (id)object可供调用。同时,Notification对象还包含一个参数,就是字典(可选参数),这个字典中存储一些传值过程当中的信息,供接收者使用。系统要求这个参数是不可变字典。

以上信息构建好后,咱们就能够建立一个通知。

NSNotification *notification = nil;

notification = [NSNotification notificationWithName: aName object: aObj userInfo: aDictionary];

其中,aName就是notification对象的名称,aObj 就是发送者,aDictionary是通知的可选字典参数。

通知建立好后就能够在必要的时候发送通知,发送通知的时候,须要一个控制中心来发送通知,这个控制中心就是通知中心(NSNotificationCenter)。咱们也能够经过控制中心建立并发送通知,一般咱们也是这么作得。

 

通知的实际运用                                            

1. 页面关联性不大,但须要传递信息的地方。这两个页面一个做为发送者,一个做为监听者;

2. 须要向多个地方发送信息。一个页面做为发送者,多个页面做为监听者。

 
如何使用通知                                       

1.注册通知

2.发送通知

3.移除通知

 

代码实现

创建一个ViewController,修改成MRC。在.m文件里面操做。

先看注册通知

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *mainView = [[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds]autorelease];
    self.view = mainView;
    
    UIButton *redButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    redButton.frame = CGRectMake(100, 100, 100, 30);
    [redButton setTitle:@"Red" forState:UIControlStateNormal];
    [redButton addTarget:self action:@selector(setRedColor) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:redButton];
    
    UIButton *blueButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [blueButton setTitle:@"Blue" forState:UIControlStateNormal];
    blueButton.frame = CGRectMake(100, 150, 100, 30);
    [blueButton addTarget:self action:@selector(setBlueColor) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:blueButton];
    /**
     *  注册通知
     */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doChange:) name:@"ColorChange" object:nil];
   
}


发送通知

- (void)setBlueColor{
    /**
     *  发送通知
     */
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"blueColor" forKey:@"color"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ColorChange" object:self userInfo:dic];
}

- (void)setRedColor{
    /**
     *  发送通知
     */
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"redColor" forKey:@"color"];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ColorChange" object:self userInfo:dic];
}

- (void)doChange:(NSNotification *)notification{
    NSDictionary *dic = [notification userInfo];
    NSString *colorStr = [dic valueForKey:@"color"];
    UIColor *color = nil;
    
    if ([colorStr isEqualToString:@"blueColor"]) {
        color = [UIColor blueColor];
    }
    if ([colorStr isEqualToString:@"redColor"]) {
        color = [UIColor redColor];
    }
    self.view.backgroundColor = color;
}


移除通知

 
- (void)dealloc{
    /**
     *  移除通知
     */
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super dealloc];
}

实现效果以下。点击红色屏幕变成红色,点击蓝色,屏幕变成蓝色。html

 

 

 

iOS上简单推送通知(Push Notification)的实现ios

 

一、理解Apple推送通知的机制json

 

从上面的流程图中,能够看到一个能接收推送通知的App,须要3个东西:服务器

App ID(惟一标识一个App程序)并发

Provisioning Profile(App程序的发布须要它,因此推送通知只能在真机上测试)app

Device Token(设备标识,这个是推送通知功能中特有的)框架

而能推送通知的服务器端则要2个东西:socket

SSL Certificateide

Private Key

(因为我对信息加密不清楚,因此这里不解释)

值得注意的是APNS(ApplePush Notification Service) Server,完成发送Device Token和通知内容的功能,并且这2个动做都是被动的,即第一个动做是由App发起的,第二个则是推送通知的服务器发起的。

对我而言,理解就这么多了。下面我按照参考文章进行实验。

二、建立App ID

 

点击“New App ID”按钮后,以下

 

Description的内容能够任意,Bundle Identifier (App ID Suffix)必须和建立App工程时的Bundle Identifier,以下

 

点击“Submit”后,点击左侧导航中的“App IDs”,找到刚才新建立的App ID,以下

 

点击“Configure”后,以下

 

勾选“Enable for Apple Push Notification service”,而后点击红色的“Configure”按钮,这里暂时只针对Development取得证书。弹出一个对话框,以下

 

点击“Continue”后,要咱们上传一个CSR文件,以下

 

下面使用钥匙串访问(KeychainAccess)应用程序建立上面须要的CSR文件(.certSigningRequest文件)

三、建立CSR文件

Keychain Access位于/Applications/Utilities目录中,打开它以下

 

而后弹出窗口以下。

 

UserEmail Address随意写就能够,Common Name也是同样,注意勾选“Save to disks”,而后点击“Continue”。很快就生成好了所需文件,去找到它。

 

回到下面的网页中,上传刚才用KeychainAccess产生的HelloRemoteNotification.certSigningRequest文件。

 

很快须要的证书就OK了,以下

 

点击“Continue”,而后点击“Done”。

 

发现上面的Status是Enabled,并且多了“Download”按钮,点击它,下载了一个名为“aps_development.cer”的文件。双击打开它,

 

找到上图中“Keys”栏中名为“HelloRemoteNotification”的private key(注意是private key,而不是public key),右击它,选择“Export “HelloRemoteNotification”…”,这样会导出一个.p12文件(须要输入密码),以下(目前共有3个文件)

 

下面开始用刚才产生的.p12文件,建立Profile provision文件

四、建立ProvisioningProfile文件

 

在上图中,点击“New Profile”按钮后,以下

 

填写“Profile Name”;勾选“Certificate”;“App ID”选择正确的、以前咱们建立的ID,即PushNotification;最后关联须要测试真机设备。点击“Submit”,以下

 

能够看到多了一个Provisioning Profile文件,点击“Download”按钮下载它,这时咱们一共产生4个文件,以下

 

双击“PushNotification.mobileprovision”文件,或把它拖入到Xcode中。

 

在Xcode中,找到Code Signing项,如上图,将Debug一项配置成刚才拖入Provisioning Profile对应的iPhone Developer。

五、Xcode工程中取得Device Token

 

在application:didFinishLaunchingWithOptions:方法里,注册使用远程通知。

 

添加2个方法,application: didRegisterForRemoteNotificationsWithDeviceToken:和 application:didFailToRegisterForRemoteNotificationsWithError:,用于取得Device Token和打印错误。运行咱们建的HelloRemoteNotification工程,若是以上步骤都正确,应该打印出Device Token,以下

 

也可能出错以下

 

六、建立.pem文件

将已有的.cer文件转成.pem文件

将已有的.p12文件转成.pem文件(须要输入密码)

最后将上面2个.pem文件合并成1个.pem文件(须要输入新密码)

 

aps_development.cer->HelloRemoteNotification.pem(下面更名为HelloRemoteNotificationCert.pem)

HelloRemoteNotification.p12-> HelloRemoteNotificationKey.pem

 

HelloRemoteNotification.pem +HelloRemoteNotificationKey.pem合并成ck2.pem

七、编写PHP服务器代码,发送通知

<?php

// Put your device token here (without spaces):
$deviceToken = '<Xcode控制台输出的Device Token>';

// Put your private key's passphrase here:
$passphrase = '<最后输入的密码>';

// Put your alert message here:
$message = 'My first push notification!';

////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck2.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$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;
else
 echo 'Message successfully delivered' . PHP_EOL;

// Close the connection to the server
fclose($fp);

注意:修改下面两行代码

// Put your private key's passphrase here:

$passphrase = '<最后输入的密码>';

......

......

stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck2.pem');

运行上面的php脚本,以下

 

能够看到iPad上面收到的推送通知,以下,表示实践成功!

 

 
0
0
相关文章
相关标签/搜索