koharuai
koharuai

Reputation: 43

Swift URL Encoding returns Optional("String")

I'm new to swift (Long time PHP and C# Programmer), but I can't really see any documentation or questions relating specifically to this issue I'm having.

So, the low down is this, I want to send a HTTP GET API to a remote server using NSURLSession in swift, however when I encode the editable UITextView I receive the contents of that UITextView encased in the literal string "Optional("")" which causes my app to crash due to a poorly parsed URL.

Here's the code;

    var message = messageField.text
    var encodedMessage = message.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
    println(encodedMessage)

The Value of messageField.text = "Your message here." however, when I view my println output I see;

Optional("Your%20message%20here.")

What can I do to prevent this, or rather, what can I do to utilise this method, or another method of encoding the UITextView?

Upvotes: 2

Views: 3966

Answers (1)

Kirsteins
Kirsteins

Reputation: 27335

stringByAddingPercentEncodingWithAllowedCharacters returns String?. Use optional biding:

var message = messageField.text
var encodedMessage = message.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())

if let encodedMessage = encodedMessage {
    println(encodedMessage)
}

Upvotes: 6

Related Questions