Make HTTP GET request?

I'm trying to implement sending of SMS in my app. I want to try this via a 3rd party. So I need to make a HTTP GET request for sending the SMS:
Code Block
https://sveve.no/SMS/SendMessage?user=*&passwd=*&to=***&msg=Meldingstekst&f=json 

I tried this:
Code Block
 let url = URL(string: "https://sveve.no/SMS/SendMessage?user=myUser&passwd=myPassword&to=12345678&msg=This is the message text&f=json")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()

Fatal error: Unexpectedly found nil while unwrapping an Optional value

The error is on the URL. What can be the issue?

Answered by OOPer in 669241022

What can be the issue?

Each parameter in a URL needs to be properly escaped. Better try using URLComponents:
Code Block
var myUser: String = "myUser"
var myPassword: String = "myPassword"
var msg: String = "This is the message text"
var urlComponents = URLComponents(string: "https://sveve.no/SMS/SendMessage")!
urlComponents.queryItems = [
URLQueryItem(name: "user", value: myUser),
URLQueryItem(name: "myPassword", value: myPassword),
URLQueryItem(name: "msg", value: msg),
URLQueryItem(name: "f", value: "json"),
]
let url = urlComponents.url!
print(url) //->https://sveve.no/SMS/SendMessage?user=myUser&myPassword=myPassword&msg=This%20is%20the%20message%20text&f=json


Accepted Answer

What can be the issue?

Each parameter in a URL needs to be properly escaped. Better try using URLComponents:
Code Block
var myUser: String = "myUser"
var myPassword: String = "myPassword"
var msg: String = "This is the message text"
var urlComponents = URLComponents(string: "https://sveve.no/SMS/SendMessage")!
urlComponents.queryItems = [
URLQueryItem(name: "user", value: myUser),
URLQueryItem(name: "myPassword", value: myPassword),
URLQueryItem(name: "msg", value: msg),
URLQueryItem(name: "f", value: "json"),
]
let url = urlComponents.url!
print(url) //->https://sveve.no/SMS/SendMessage?user=myUser&myPassword=myPassword&msg=This%20is%20the%20message%20text&f=json


Make HTTP GET request?
 
 
Q