ShingHung
ShingHung

Reputation: 337

How to pass text field of inputed data to url on swift

I've created two UITextField

@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtUserpassword: UITextField!

and make username and password to store the data

let username = txtUsername.text
let userpassword = txtUserpassword.text

Also, pass the data to URL

let urlAsString = "http://lifewinner2015.dlinkddns.com/SERVER/user?function=login&username=\(username)&password=\(userpassword)"

but the \(username) and \(user password) may be error, Xcode can not run this.

Can help me to fix this?

Upvotes: 0

Views: 1898

Answers (1)

CouchDeveloper
CouchDeveloper

Reputation: 19106

Note that each URL component needs to be escaped properly. Escaping is error prone and easy to get wrong.

Thus, you should use NSURLComponents to create a URL which also automatically escapes the different components of an URL for you:

let urlString = "http://lifewinner2015.dlinkddns.com/SERVER/user"

Note: the above URL also consists of several components which may require escaping. IFF you are sure for the given string literal you don't need escaping, you can try to set the URL string as above. Otherwise set each component separately.

guard let urlComponents = NSURLComponents(string: urlString) else {
    throw MyError.CouldNotCreateURLFromString(string: urlString)
}

Then create the url query component:

let queryItems: [NSURLQueryItem] = [
    NSURLQueryItem(name: "function", value: "login"),
    NSURLQueryItem(name: "username", value: username),
    NSURLQueryItem(name: "password", value: userpassword)
]

and assign it the url components object:

urlComponents.queryItems = queryItems

Obtaining the URL should not throw now, but anyway:

guard let url = urlComponents.URL else {
    throw MyError.CouldNotCreateURL
}

Upvotes: 1

Related Questions