AbashscripttosendiOSpushnotificationswiththeApplePushNotificationservice(APNs)
AboutInordertotestiOSpushnotificationsyoumighthaveyourownserversetupormaybeyouuseoneofthemanypushnotificationservicesthatalreadyexist.Allthistakesalotoftimeandefforttogetupandrunning.Ideally,youwouldprobablyliketostartsendingnotificationsjustwithamac,aniOSdeviceandzeroincash(excludingthemoneyyou'vepaidforyourmacanddeviceofcourse).Withtheuseofwebtokensandtheshellscriptcontainedhereinyoucanstartsendingpushnotificationstoyourdevicesinminuteswhilegettingsomefeedbackeachtimesomethinggoeswrong.
FeaturesUsesJSONwebtokensinsteadofcertificates.FasterandpainlessDisplayserrormessages,ifany,returnedbyAPNsNoexternalservicesorlibraries(err,exceptOpenSSL)AlldonewithasinglebashscriptAlldonetransparentlywithrespecttoyourdataInstallationClonetherepoInstallOpenSSLifyouhaven'talreadyfonesoGetadevicetokenObtainyourencryptionkeyEnteryourowndatainthescriptRunthescript(./pu.sh)Youcanoptionallypassoneofthereadymade.jsonfilesfoundhereasaparametertopu.shInstallOpenSSLYoucanskipthisifyouhavealreadyinstalledOpenSSL.Onamac:
OpenaterminalInstallhomebrew:/usr/bin/ruby-e"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/master/install)"TypebrewinstallopensslGettingadevicetokenBelowarethemethodsofyourappsapplicationdelegate,withsomeshortexplanationcomments,youneedtoobtainadevicetoken.
/**Hereyouregisterforremotenotifications*/funcapplication(_application:UIApplication,didFinishLaunchingWithOptionslaunchOptions:[UIApplication.LaunchOptionsKey:Any]?)->Bool{application.registerForRemoteNotifications()returntrue}/**Hereyouprintoutyourdevicetoken*/funcapplication(_application:UIApplication,didRegisterForRemoteNotificationsWithDeviceTokendeviceToken:Data){lettoken=deviceToken.hexEncodedString()//nowthetokenwillappearinthexcodeconsoleprint(token)}/**ThishelpermethodconvertsthedevicetokenfrmDatatoString*soyoucouldjustpasteitintothescriptbelow*/funchexEncodedString()->String{returnmap{String(format:"%02hhx",$0)}.joined()}ObtainyourkeyYouneedanAPNsauthenticationtokensigningkeytogeneratethetokensusedbyyourserverinordertosendpushnotifications.Yourequestthiskeyfromyourdeveloperaccountondeveloper.apple.comintheKeys➙Allsectionasshownbelow.
Aftercontinuingtothenextstepyouget:
A10-characterstringwiththekeyID.Keepthisonhandyouwillneedit.Ifyouforgetititisstillavailableinthedeveloperportal.Asigningkeyasa .p8textfile.Keepthissomewheresafe.Forinstance,don'tkeepitinyoursourcecoderepository.Ifyouloseitit'sgoneforeverandyouwillhavetorevokeitandregenerateit.Ifthiskeyiscompromisedinanywayitcanbeusedtosendpushnotificationstoyourapps
评论