Working With Emoji in Swift. Emoji aren't just simple strings

文章推薦指數: 80 %
投票人數:10人

Emoji have become a big part of our life. iPhones and iPads have a special emoji keyboard (unless it's turned off). We see them on websites, ... GetstartedOpeninappSigninGetstartedFollow198KFollowers·ArchiveWriteForUsSupportUsAboutGetstartedOpeninappWorkingWithEmojiinSwiftEmojiaren’tjustsimplestringsAlexNekrasovSep22,2020·6minreadPhotobyGabyPrestesNekrasovaonInstagram.Emojihavebecomeabigpartofourlife.iPhonesandiPadshaveaspecialemojikeyboard(unlessit’sturnedoff).Weseethemonwebsites,inmobileanddesktopapps,andweenterthemwhenwritingtextsandfillinginforms.Howdowecontrolthem?HowdowepreventusersfromenteringemojiinUITextField?HowdoweparseemojiintheJSONresponsefromaserver?Let’sdiscussitall.ALittleBitofTheoryEmojiareapartofmodernUnicode.Computersworkwithbitsandbytes—notwithsmilesandothersmallpictures.Letters,numbers,andspecialcharactersinatextareallencodedinoneormorebyteseach.Thesamegoesforemoji.They’rejustsymbols.TherearethreestandardmodificationsofUnicode.Allofthemareconstantlyevolving,newsymbolsappear,newlanguagesareincluded.Sothereareactuallymorethanthreeversions,butforusdevelopers,it’simportanttoknowthreedifferentstandards:UTF-8(UnicodeTransformationFormateightbits):Eachsymbolinthisencodingispresentedasoneormorebytes.Simplelatincharacters,digits,andsomeothersymbolstakeonlyonebyte(eightbits).Ifthefirstbitis0,weknowthatit’saone-bytesymbol.Ifit’saRussian,Chinese,orArabicsymboloranemoji,itwillstartwithbit1andhavemorethanonebyte.UTF-16(UnicodeTransformationFormat16bits):Allsymbolsareencodedintotwoorfourbytes.Twobytesmake65,536combinations,whichincludealmostallknowncharacters.Emojiusuallytaketwobytes,buttheycanhavemodifiers(colourofskinorhair).Inthatcase,itusesextraspace.UTF-32(UnicodeTransformationFormat32bits):Thesimplestforunderstandingencoding,buttheleastmemory-efficient.Eachsymboltakesexactlyfourbytes.EmojihaveappearedinUnicodesinceversion6.0backin2010.AllmoderniPhonesandMacssupportmuchnewerversions,sobyaddingemojitoyourapps,youcanbesurethatuserswillseethem.“AnNSStringobjectencodesaUnicode-complianttextstring,representedasasequenceofUTF–16codeunits.”—AppleDeveloperAsyoucansee,emojicanbeincludedinanystringinSwift.EmojiinmacOSAswewriteSwiftcodemostlyinmacOS,let’sseehowtoaddemojitoourcode.Inanyappwithtexteditingcapability,includingXcode,youcanclickontheEditmenu,thenEmoji&Symbols.You’llseeapanelwithemoji.Chooseanyofthemandtheywillappearinyourcode.Anotherwayistousethehotkey⌃⌘Space(ctrl+cmd+space).EmojiinmacOSDetectingEmojiinStringsBeforewecontinue,let’saddseveralextensionstoourproject.TheywillallowustocheckifStringhasemoji,ifithasonlyemoji,ifCharacterisanemoji,andsoon.NowyoucancheckifStringhasanemoji:"Alex😊".containsEmoji//true"Alex😊".containsOnlyEmoji//falseForbiddingEmojiinUITextFieldOftentimes,weshouldn’tallowtheusertoenteremoji.Forexample,ifwewanttoknowtheirlegalnameorotherdata.Therearetwowaystodoso—amorerestrictiveoneandlessrestrictiveone.Themorerestrictive(buteasier)wayistochoosetheASCIICapablekeyboardtype.Itwillremoveallsymbolsthatarenotincludedinthefirst128symbolsoftheUnicodeset.IfyoustillrememberdetailsaboutUTF-8,ithasone-byte,two-byte,andfour-bytecharacters.Thisoptionwillallowonlyone-bytecharacters(startingwithbit0).ChangingkeyboardtypeItcanbeusefulforenteringusernamesorpasswords,butnamesandotherdatacanhavediacritic,non-Latin,andothercharacters.Inthiscase,weusethesecondway.Ithasseveralsteps:SetkeyboardtypetoDefault.Setadelegate.Usually,it’syourUIViewController.Inadelegate,overridethemethodfunctextField(_textField:UITextField,shouldChangeCharactersInrange:NSRange,replacementStringstring:String)->Bool.Getupdatedtext:iflettext=textField.text,lettextRange=Range(range,in:text){letupdatedText=text.replacingCharacters(in:textRange,with:string)}5.CheckthatupdatedTextdoesn’thaveemojiandreturnfalseifitdoes.That’showitlooks:Nowwhentheusertriestoinsertanemojiinatextstring,therewillbenoeffect.Ifyouwanttomakeitclearerfortheuser,addanalertwithamessage.DecodingEmojiinAPIResponseIfyou’veworkedwithaRESTAPIinSwift,youmayknowthatsometimesyougetaresponsewithoutemoji.ConversionsbetweenStringsandJSON-compatibletypes,likeArrayandDictionary,mayalsoloseemoji.ThesafestwaytogoistogetDatafromtheAPIandconvertittothetypeyouneed:letstr=String(data:data,encoding:.utf8)SamewithJSON.It’sbettertodecodethemmanuallyfromdata:letjson=try?JSONSerialization.jsonObject(with:data,options:.allowFragments)Let’shavealookatthisexamplewiththepopularlibraryAlamofire:Alamofiregetsregularupdates,somaybeitwillreturnemojiintheresponseStringhandler.It’spossiblyalreadydone,butwhenItestedit,IgotStringinreturnwithoutanyemoji.Ifyouuseanotherlibrary,thistrickwillbealsohandy.Rememberthatyoualwaysreceiveabufferofbytesfromanywebrequest.TheclosesttoitinSwiftisaDataobject.Allothertypesareconvertedfromit.YoushouldalwayspreferDataifyouwantfullcontrol.NoteaboutMySQLandotherSQLdatabasesThisisnotexactlyaboutSwift,butaswearetalkingaboutemojiinAPI,I’llmentionthistoo.IfyouplantohaveemojiinaSQLdatabase(e.g.MySQL),youshoulddotwothings:Setthecharactersetofthewholedatabase,table,oraseparatefieldtoutf8mb4.Simpleutf8won’tletyoustoreemojiinstringfields.RunSETNAMESutf8mb4beforerunningotherSQLrequests.EmojiVariablesI’llgivesomecredittoApplefortheirsenseofhumour.Youcanuseemojiinthenamesoffunctionsorvariables.Forexample,thisisavalidSwiftcode:Neverdoitinproductioncode—it’sveryuncomfortabletotype,search,orshare.Butitcanbeuseful,forexample,toteachchildren.Looksfunny,right?SourcecodewithemojiAmorecommonpracticeistoincludeemojiinStrings:leterrorText="Sorry,somethingwentwrong😢"ConclusionInmostcases,appsshouldallowuserstoenteremoji.Butifit’snotadesiredbehaviour,it’salwayspossibletoaddrestrictions.Usingemojiintheuserinterfaceisalsogettingmoreandmorepopularthesedays.Atthesametime,don’tuseemojiinyoursourcecodeunlessit’sreallynecessary.Swiftallowsit,butit’snotagoodpractice.Evenifit’sapartofastringconstant,it’sbettertoputitinaseparatefile.Seeyounexttimeandhappycoding!AlexNekrasovGameandsoftwaredeveloperwithmorethan15yearsexperience.FounderandCEOatMariposaStudios,freelancer.Follow1191ThankstoZackShapiro. 119 1191ProgrammingEmojiSwiftMobileXcodeMorefromBetterProgrammingFollowAdviceforprogrammers.Here’swhyyoushouldsubscribe:https://bit.ly/bp-subscribeReadmorefromBetterProgrammingMoreFromMediumHowtoWriteiOSAppsWithoutXcodeAlexNekrasovinBetterProgrammingDifferenceBetweenNSOperationandDispatchQueuesShayanMehranpoorinCodeXSwiftOptionals[iOS]KalyanTakingEnumsinSwiftawayfromitsSweetSpotSaiDurgaMaheshLearnSwiftUIRenModel-View-ControllerPatterninswift(MVC)forBeginnersAhmedAminHassanHowtoforcechangeAppLanguageprogrammaticallywithoutbreakingyourappMukeshMandorainDevGeniusFixingXcode’siPhoneXS,XSMaxandXRSimulatorNamesandiOSVersionsGeoffHackworth



請為這篇文章評分?