您好,登錄后才能下訂單哦!
開發環境xcode7.1 運行環境 IOS9.1
IOS的信送簡單就是在開開發者管理門戶中創建推送證書,然后生成服務器推送證書(服務端代碼可以是任意的,我們采用C#來寫),App中嵌入推送代碼,App安裝后允許推送后就可以收到服務端的推送消息了,關于更進一步的原理說明,可以查看官方文檔。
前提是你已經開通購買了apple的開發者帳戶,并且已經有開發證書,能正常創建運行項目到你的iphone上了,如果以前條件不具備,請先參完成以上步驟。
導出證書
打開Mac系統的“鑰匙串訪問”-“證書助理”-“從證書頒發機構請求證書”
輸入郵箱和名稱,選擇“存儲到磁盤”
在彈出框中***的名字為“RemotePush_CertificateSigningRequest.certSigningRequest”,請注意,這記住這個名字和保存路徑,馬上在創建App ID時會用到。
添加App ID
登錄apple的開發者門戶,進入到“MemberCenter”-“Certificates,Identifiers&Profiles”-IOSApps下的“Certificates”-“Identifiers”-“AppIDs”
這時,還有沒在xcode下創建自己的項目,所以App IDs下還無法添加對應的App ID,現在先在xcode下創建一個項目,名字叫RemotePushDemo
現在添加一個App ID
然后提交
提交成功后,在App IDs中選擇剛添加的RemotePush,點擊Edit
找到Push Notifications節點,點擊CreateCertificate(如果是發布,就先Production SSL Certificate下的Create Certificate)
選擇繼續,直到選擇上傳證書頁面,點擊選擇證書
這是找到文章開始先擇導出的證書RemotePush_CertificateSigningRequest.certSigningRequest,然后點擊Generate生成證書
這時,就可以下載生成的證書了,下載完成后雙擊安裝證書。
安裝完成后可以“鑰匙串訪問的“登錄”下,類型為“證書”下看到安裝的證書了。
選中這張證書,右鍵,選擇導出證書選項,然后在彈出框中輸入證書名稱,要使用.p12格式,同時,需要輸入證書密碼,這時一定要記住自己設定的證書密碼,這個證書和密碼將要在服務端使用。在最后,導出證書時需要系統登錄密碼,以作驗證。
配置Provisioning Profiles,選擇Development添加,選擇IOS App Development
要選擇自己創建的App ID,然后保存下載,雙擊安裝即可(安裝后會自動打開xcode,可以在項目的Build Settings中搜Provisioning Profile的選項目中查看是否安裝成功)。
同時,在設置項目的Capabilities開啟Remotenotifications
接下來就開始寫swift在app中的代碼了,打開項目的AppDelegate活加如下代碼:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UIApplication.sharedApplication().applicationIconBadgeNumber=0; application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert,UIUserNotificationType.Sound,UIUserNotificationType.Badge], categories: nil)); return true } // 8.0 之后 收到遠程推送通知 func application(application: UIApplication , didReceiveRemoteNotification userInfo: [ NSObject : AnyObject ], fetchCompletionHandler completionHandler: ( UIBackgroundFetchResult ) -> Void ) { } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { } // 注冊通知 alert 、 sound 、 badge ( 8.0 之后,必須要添加下面這段代碼,否則注冊失敗) func application(application: UIApplication , didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings ) { application.registerForRemoteNotifications(); } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { print(deviceToken);//在輸入窗口中查看此值 } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { }
注意認識印的倒數第二個方法的deviceToken,這個值要作為服務端推送的設備值使用,每個設備,每次安裝后都有一個唯一的值,同樣設備卸載再次安裝,此值會變化。
接下來是用C#寫服務端了:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { while (true) { pushMessage(Console.ReadLine()); } } public static void pushMessage(string content) { string deviceID = "deviceToken替換掉這里"; int port = 2195; var hostname = "gateway.sandbox.push.apple.com"; var certificatePath = @"還記得.p12的證書文件嗎?替換這里"; X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "還記得證書密碼嗎?你設定的,替換這里"); X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate); TcpClient client = new TcpClient(hostname, port); SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); try { sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false); MemoryStream memoryStream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(memoryStream); writer.Write((byte)0); writer.Write((byte)0); writer.Write((byte)32); writer.Write(HexStringToByteArray(deviceID.ToUpper())); String payload = "{\"aps\":{\"alert\":\"" + content + "\",\"badge\":10,\"sound\":\"default\"}}"; var payloadlength = System.Text.Encoding.UTF8.GetBytes(payload).Length; writer.Write((byte)0); //writer.Write((byte)payload.Length); writer.Write((byte)payloadlength); byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload); writer.Write(b1); writer.Flush(); byte[] array = memoryStream.ToArray(); sslStream.Write(array); sslStream.Flush(); client.Close(); } catch (System.Security.Authentication.AuthenticationException ex) { client.Close(); } catch (Exception e) { client.Close(); } } private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { Console.WriteLine(certificate.Subject); return true; } public static byte[] HexStringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。