溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

用C#完成Swift遠(yuǎn)程推送通知

發(fā)布時(shí)間:2020-03-03 13:22:49 來源:網(wǎng)絡(luò) 閱讀:1689 作者:桂素偉 欄目:移動(dòng)開發(fā)

開發(fā)環(huán)境xcode7.1 運(yùn)行環(huán)境 IOS9.1

IOS的信送簡單就是在開開發(fā)者管理門戶中創(chuàng)建推送證書,然后生成服務(wù)器推送證書(服務(wù)端代碼可以是任意的,我們采用C#來寫),App中嵌入推送代碼,App安裝后允許推送后就可以收到服務(wù)端的推送消息了,關(guān)于更進(jìn)一步的原理說明,可以查看官方文檔。

 

前提是你已經(jīng)開通購買了apple的開發(fā)者帳戶,并且已經(jīng)有開發(fā)證書,能正常創(chuàng)建運(yùn)行項(xiàng)目到你的iphone上了,如果以前條件不具備,請(qǐng)先參完成以上步驟。

導(dǎo)出證書

打開Mac系統(tǒng)的“鑰匙串訪問”-“證書助理”-“從證書頒發(fā)機(jī)構(gòu)請(qǐng)求證書

用C#完成Swift遠(yuǎn)程推送通知

輸入郵箱和名稱,選擇“存儲(chǔ)到磁盤”

用C#完成Swift遠(yuǎn)程推送通知

在彈出框中***的名字為RemotePush_CertificateSigningRequest.certSigningRequest請(qǐng)注意,這記住這個(gè)名字和保存路徑,馬上在創(chuàng)建App ID時(shí)會(huì)用到。

添加App ID

登錄apple的開發(fā)者門戶,進(jìn)入到“MemberCenter-Certificates,Identifiers&Profiles”-IOSApps下的“Certificates”-Identifiers”-“AppIDs”

用C#完成Swift遠(yuǎn)程推送通知

這時(shí),還有沒在xcode下創(chuàng)建自己的項(xiàng)目,所以App IDs下還無法添加對(duì)應(yīng)的App ID,現(xiàn)在先在xcode下創(chuàng)建一個(gè)項(xiàng)目,名字叫RemotePushDemo

用C#完成Swift遠(yuǎn)程推送通知

現(xiàn)在添加一個(gè)App ID

用C#完成Swift遠(yuǎn)程推送通知

用C#完成Swift遠(yuǎn)程推送通知

用C#完成Swift遠(yuǎn)程推送通知



然后提交

用C#完成Swift遠(yuǎn)程推送通知

提交成功后,在App IDs中選擇剛添加的RemotePush,點(diǎn)擊Edit

用C#完成Swift遠(yuǎn)程推送通知

找到Push Notifications節(jié)點(diǎn),點(diǎn)擊CreateCertificate(如果是發(fā)布,就先Production SSL Certificate下的Create Certificate)

 用C#完成Swift遠(yuǎn)程推送通知

選擇繼續(xù),直到選擇上傳證書頁面,點(diǎn)擊選擇證書

用C#完成Swift遠(yuǎn)程推送通知

這是找到文章開始先擇導(dǎo)出的證書RemotePush_CertificateSigningRequest.certSigningRequest,然后點(diǎn)擊Generate生成證書

 用C#完成Swift遠(yuǎn)程推送通知


這時(shí),就可以下載生成的證書了,下載完成后雙擊安裝證書。

用C#完成Swift遠(yuǎn)程推送通知

安裝完成后可以鑰匙串訪問的“登錄”下,類型為證書下看到安裝的證書了。

用C#完成Swift遠(yuǎn)程推送通知

選中這張證書,右鍵,選擇導(dǎo)出證書選項(xiàng),然后在彈出框中輸入證書名稱,要使用.p12格式,同時(shí),需要輸入證書密碼,這時(shí)一定要記住自己設(shè)定的證書密碼,這個(gè)證書和密碼將要在服務(wù)端使用。在最后,導(dǎo)出證書時(shí)需要系統(tǒng)登錄密碼,以作驗(yàn)證。

配置Provisioning Profiles,選擇Development添加,選擇IOS App Development

用C#完成Swift遠(yuǎn)程推送通知

要選擇自己創(chuàng)建的App ID,然后保存下載,雙擊安裝即可(安裝后會(huì)自動(dòng)打開xcode,可以在項(xiàng)目的Build Settings中搜Provisioning Profile的選項(xiàng)目中查看是否安裝成功)。

用C#完成Swift遠(yuǎn)程推送通知

同時(shí),在設(shè)置項(xiàng)目的Capabilities開啟Remotenotifications

用C#完成Swift遠(yuǎn)程推送通知

接下來就開始寫swiftapp中的代碼了,打開項(xiàng)目的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 
之后 收到遠(yuǎn)程推送通知
    func application(application: UIApplication , didReceiveRemoteNotification userInfo: [ NSObject : AnyObject ], fetchCompletionHandler completionHandler: ( UIBackgroundFetchResult ) -> Void ) {
   
    }
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
     
    }
    // 注冊(cè)通知 alert 、 sound 、 badge ( 8.0 之后,必須要添加下面這段代碼,否則注冊(cè)失?。?    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) {
    
    }


注意認(rèn)識(shí)印的倒數(shù)第二個(gè)方法的deviceToken,這個(gè)值要作為服務(wù)端推送的設(shè)備值使用,每個(gè)設(shè)備,每次安裝后都有一個(gè)唯一的值,同樣設(shè)備卸載再次安裝,此值會(huì)變化。

 

接下來是用C#寫服務(wù)端了:

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), "還記得證書密碼嗎?你設(shè)定的,替換這里");
 
            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();
        }
 
    }
}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI