Text with emoji is not decoding - iOS Swift - Stack Overflow

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

I have used the following code to encode/decode the string which has emojis. extension String { func encodeEmoji() -> String { let data = ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Textwithemojiisnotdecoding-iOSSwift AskQuestion Asked 1year,7monthsago Active 1year,7monthsago Viewed 498times 0 Ihaveusedthefollowingcodetoencode/decodethestringwhichhasemojis. extensionString{ funcencodeEmoji()->String{ letdata=self.data(using:.nonLossyASCII,allowLossyConversion:true)! returnString(data:data,encoding:.utf8)! } funcdecodeEmoji()->String?{ letdata=self.data(using:.utf8)! returnString(data:data,encoding:.nonLossyASCII) } } Ihavecalledthisfunctionlikethisbelow.Convertedtheresponseinthe'User'model. letuser=User()//LoadedAPI'sresponseinthismodel lettextWithEmoji=user.aboutMe.decodeEmoji()//Here,Iamgettingthestringasthesameasbeforedecoding lblAboutMe.text=textWithEmoji Followingistheencodedstringwhichisnotdecoding: "Ilovetoo...\n\u2705Laugh\uD83D\uDE02\n\u2705Readnovels\uD83D\uDCDA\n\u2705Watchmovies\uD83C\uDFAC\n\u2705Goforbikerides\uD83D\uDEB5\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705Goforlongwalks\uD83D\uDEB6\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705Cook\uD83D\uDC69\uD83C\uDFFD\u200D\uD83C\uDF73\n\u2705Travel\uD83C\uDDEA\uD83C\uDDFA\uD83C\uDDEE\uD83C\uDDF3\uD83C\uDDEC\uD83C\uDDE7\n\u2705Eat\uD83C\uDF2E\uD83C\uDF5F\uD83C\uDF73\n\u2705Playboardgames\u265F\n\u2705Gotothetheatre\uD83C\uDFAD\nMyfavouriteseasonisautumn\uD83C\uDF42,ilovesuperheromovies\uD83E\uDDB8\u200D\u2642\uFE0FandChristmasisthemostwonderfultimeoftheyear!\uD83C\uDF84" Hereistheoriginaltextimage: iosswiftdecodeencodeemoji Share Follow editedMar30'20at14:57 TusharAmkar askedMar30'20at13:57 TusharAmkarTusharAmkar 5177bronzebadges 7 Doesthisansweryourquestion?SwiftEncode/decodeemojis – koen Mar30'20at14:06 No,Ihavecheckedthispostbutdidn'tfindasolution. – TusharAmkar Mar30'20at14:11 Socanyouexplainwhatyoumeanby"theencodedstringwhichisnotdecoding"?Doyouseenothingatall,ordoyouseegarbage? – koen Mar30'20at14:24 Iamgettingjustthesamestringafterdecodingthetext. – TusharAmkar Mar30'20at14:34 Pleaseaddsomemorecodeinyourquestionasaminimalreproducibleexamplehowyouarecallingyourdecodefunction. – koen Mar30'20at14:37  |  Show2morecomments 1Answer 1 Active Oldest Votes 1 Thestringyouareusingisinvalid("Ilovetoo...\n\u2705Laugh\uD83D\uDE02\n\u2705Readnovels\uD83D\uDCDA\n\u2705Watchmovies\uD83C\uDFAC\n\u2705") ItshouldbeinvalidStringliteral "\\uD83D\\uDCDA\\u2705" Youhaveastringnon-BMPcharactersinformofJSONString.AndyourdecodeEmojicannotconvertthemintovalidcharacters. Soweneedtoforcefullyconvertsuchstrings. extensionString{ varjsonStringRedecoded:String?{ letdata=("\""+self+"\"").data(using:.utf8)! letresult=try!JSONSerialization.jsonObject(with:data,options:.allowFragments)as!String returnresult } } Afterthatyouneedtodecodeemojifromabovestringusingbelowfunction. extensionString{ vardecodeEmoji:String?{ letdata=self.data(using:String.Encoding.utf8,allowLossyConversion:false); letdecodedStr=NSString(data:data!,encoding:String.Encoding.nonLossyASCII.rawValue) ifdecodedStr!=nil{ returndecodedStrasString? } returnself } } UsuallyJSONdecodercandecodethesetypeofcharactersintoemoji MaybethereischancesofinvalidJSON Firstneedtoverifythesethingsthatjsonisvalidornotbeforeusing. USAGE: letjsonDecodedString="Yourstring".jsonStringRedecoded letdecodedEmojiText=jsonDecodedString?.decodeEmoji debugPrint("\(decodedEmojiText)") Share Follow answeredMar31'20at9:06 DishaPatelDishaPatel 2611bronzebadge 0 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggediosswiftdecodeencodeemojioraskyourownquestion. TheOverflowBlog Podcast395:Whoisbuildingcloudsfortheindependentdeveloper? Explodingturkeysandhownottothawyourfrozenbird:Topturkeyquestions... FeaturedonMeta Nowlive:Afullyresponsiveprofile Reducingtheweightofourfooter TwoBornottwoB-Farewell,BoltClockandBhargav! Linked 7 SwiftEncode/decodeemojis Related 1049 HowtochangeStatusBartextcoloriniOS 625 DoSwift-basedapplicationsworkonOSX10.9/iOS7andlower? 880 HowtoiteratealoopwithindexandelementinSwift 455 CloseiOSKeyboardbytouchinganywhereusingSwift 618 iOSappwithframeworkcrashedondevice,dyld:Librarynotloaded,Xcode6Beta 675 iOS8UITableViewseparatorinset0notworking 266 ChangingPlaceholderTextColorwithSwift 373 AddplaceholdertextinsideUITextViewinSwift? 565 Whyareemojicharacterslike👩‍👩‍👧‍👦treatedsostrangelyinSwiftstrings? HotNetworkQuestions Usinga2TBSSDona2016MacBookPro Couldanyequationhavepredictedtheresultsofthissimulation? WhatcrimesdidRosenbaumcommitwhenheengagedRittenhouse? Isitagoodideatomaketheactionsofmyantagonistreasonable? Howtoaskfriendnottoleavesoquickly,oratleastletmeknowifhedoesn'tplanonstayingverylong? Doestherulethatalcoholonflightsmustbeservedbyaflightattendantalsoapplytoprivateflights? WhydoesHebrews3:1callJesusanapostle? Meaningof"ruinsomethingforsomeone" DemerzelandtheLawsofRobotics Whyisthecurrententeringaconductorthesameastheoneexitingit? TheWitch'sBroom Algebraictopologyandhomotopytheorywithsimplicialsetsinsteadoftopologicalspaces IPv6prefixinterpretation IstheDaoathingoranaction? NewtoBikes:MychainfelloffandIputitbackon.HowcanIknowifit'sontherightcog? Propertranslationfor"artissubtraction" Wordforaplanthathasnotbeenperformedbecauseofsomeissues HowshouldIteachlogarithmstohighschoolstudents? Whatisthemosthumanewaytokillcrayfishathome? Commenttraduire« HoweverlittleImayremember »? WhatCouldExplainASolitaryMountaininaGrassland? HowcanIgettrue1"thickoakboards? HowtojustifysmallHomininsnotbeingconqueredby(anatomicallymodern)Humans? Harmonicdivisornumbers morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-swift Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?