轉載自: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上面收到的推送通知,以下,表示實踐成功!