ios - WhatsApp NSURL returning nil When sharing text - Swift -


i'm trying share text whatsapp nsurl returning nil text encoded right ! take @ code :

var msg : nsstring = "to world of none"; var titlewithoutspace = msg.stringbyaddingpercentescapesusingencoding(nsutf8stringencoding) var urlwhats = nsstring(string: "whatsapp://send?text=\(titlewithoutspace)") println(urlwhats) var whatsappurl = nsurl(string: urlwhats string) println(whatsappurl) 

when printing result string equal :

whatsapp://send?text=optional("to%20the%20world%20of%20none") 

and whatsappurl returning nil :

nil 

stringbyaddingpercentescapesusingencoding: returns optional string that's why urlwhats contains optional(""). avoid need unwrap optional :

var msg: nsstring = "to world of none"; var titlewithoutspace = msg.stringbyaddingpercentescapesusingencoding(nsutf8stringencoding) if let titlewithoutspace = titlewithoutspace {     var urlwhats = nsstring(string: "whatsapp://send?text=\(titlewithoutspace)")     var whatsappurl = nsurl(string: urlwhats string)     println(whatsappurl) } else {     // unwrapping failed because titlewithoutspace nil (might because stringbyaddingpercentescapesusingencoding failed). } 

besides suggest use string type directly since nsstring useless there (except stringbyadding…) :

var msg: nsstring = "to world of none"; var titlewithoutspace = msg.stringbyaddingpercentescapesusingencoding(nsutf8stringencoding) if let titlewithoutspace = titlewithoutspace {     var urlwhats = "whatsapp://send?text=\(titlewithoutspace)"     var whatsappurl = nsurl(string: urlwhats)     println(whatsappurl) } else {     // unwrapping failed because titlewithoutspace nil (might because stringbyaddingpercentescapesusingencoding failed). } 

also please note nsurl(string:) may fail returns optional nsurl object. use might need unwrap did titlewithoutspace.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -