I want to upload image to server connect with soap using SWIFT - swift

I want to upload the image to server connect with SOAP using SWIFT
but I have to respond value from soap below
Response: Optional(<NSHTTPURLResponse: 0x281a1a780> { URL: http://xxx.xx.xx.xx/Projectervice/imageService.asmx?op=Upload } { Status Code: 400, Headers {
"Cache-Control" = (
private
);
"Content-Length" = (
0
);
"Content-Type" = (
"text/xml; charset=utf-8"
);
Date = (
"Mon, 08 Jul 2019 07:37:10 GMT"
);
Server = (
"Microsoft-IIS/8.5"
);
"X-AspNet-Version" = (
"4.0.30319"
);
"X-Powered-By" = (
"ASP.NET"
);
} })
Body: Optional()
[![image for Soap web service][1]][1]
I don't understand this response... and why the body does not have value
func uploadImageToserver(photo: String) -> Void
{
let is_URL: String = "http://xx.xx.xx.xx/Projectervice/imageService.asmx?op=Upload"
let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
let session = URLSession.shared
lobj_Request.httpMethod = "POST"
lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
lobj_Request.addValue("xxx.xx.xx.xx", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(String(is_SoapMessage.count), forHTTPHeaderField: "Content-Length")
lobj_Request.addValue("http://tempuri.org/Upload", forHTTPHeaderField: "SOAPAction")
let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in
print("Response: \(String(describing: response))")
let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Body: \(String(describing: strData))")
if error != nil
{
print("Error: " + error.debugDescription)
}
})
task.resume()
}
[1]: https://i.stack.imgur.com/KBJ7T.jpg

Related

Using Swift with URLSession works with GET and PUT, but it gives error 405 Method Not Allowed when I use POST

I develop an iOS app using Swift.
I use the following method below to access an login ENDPOINT with PUT method.
let loginData = LoginModel("myUser","myPassword")
var loginClassJson:Data?
do{
loginClassJson = try JSONEncoder().encode(loginData)
} catch {
fatalError("Unable To Convert in Json")
}
let completeUrl = URL(string: RESconstantes.URL_PRINCIPAL_TREINAGEDAVE + "/login" )!
var request = URLRequest(url: completeUrl)
let myConfig = URLSessionConfiguration.default
let base64LoginString = EndpointController.getBase64StringLoginWithUserAndPasswordV2()
myConfig.httpAdditionalHeaders = ["Authorization" : base64LoginString]
request.httpMethod = "PUT"
request.setValue("\(String(describing: loginClassJson!.count))", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = loginClassJson
let sessionDelegate = SessionDelegate()
let urlSession = URLSession(configuration: myConfig, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
let task = urlSession.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if let error = error{
print("errorX: ")
print(error)
return
}
if let data = data{
let returnData = String(data: data, encoding: String.Encoding.ascii)
print("dataX: ")
print(returnData)
}
if let response = response{
print("responseX: ")
print(response)
}
})
task.resume()
print("END")
This is my URLSessionDelegate class
class SessionDelegate:NSObject, URLSessionDelegate
{
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// usado para fazer o bypass na autenticaĆ§Ć£o self-signed do certificado do servidor
// We've got a URLAuthenticationChallenge - we simply trust the HTTPS server and we proceed
print("start didReceive challenge 1")
if true {
print("didReceive challenge 2")
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}else{
completionHandler(.performDefaultHandling, nil)
}
}
It works perfectly for me, but now I try to create a code to access another ENDPOINT with POST method
let resDadoModel = ResDadoModel.getResenhaById(1)
let jsonRequestUploadResenha = ResDadoModel.createMockJsonObjectResenhaDados(resDadoModel)
let json: [String: Any] = jsonRequestUploadResenha
guard let jsonData:Data = try? JSONSerialization.data(withJSONObject: json) else {
print("guard jsonData error")
return
}
let completeUrl = URL(string: RESconstantes.URL_PRINCIPAL_TREINAGEDAVE + "/validaResenha" )!
var request = URLRequest(url: completeUrl)
let myConfig = URLSessionConfiguration.default
let base64LoginString = EndpointController.getBase64StringLoginWithUserAndPasswordV2()
myConfig.httpAdditionalHeaders = ["Authorization" : base64LoginString, "Content-Type":""]
request.httpMethod = "POST"
request.setValue("\(String(describing: jsonData.count))", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let sessionDelegate = SessionDelegate()
let urlSession = URLSession(configuration: myConfig, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
let task = urlSession.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if let error = error{
print("errorX: ")
print(error)
return
}
if let data = data{
let returnData = String(data: data, encoding: String.Encoding.ascii)
print("dataX: ")
print(returnData)
}
if let response = response{
print("responseX: ")
print(response)
}
})
task.resume()
print("END")
But the code that I use to access the ENDPOINT called "validaResenha" is not working properly, I get a 405 method not allowed error.
I get the following response data
<NSHTTPURLResponse: 0x600002028560> { URL: https://my_url_endpoint/api/spservicos/v1/validaResenha } { Status Code: 405, Headers {
Allow = (
"POST, OPTIONS"
);
"Cache-Control" = (
"no-cache=\"set-cookie, set-cookie2\""
);
Connection = (
"Keep-Alive"
);
"Content-Language" = (
"en-US"
);
"Content-Length" = (
0
);
"Content-Type" = (
"text/plain"
);
Date = (
"Thu, 23 Dec 2021 23:16:21 GMT"
);
Expires = (
"Thu, 01 Dec 1994 16:00:00 GMT"
);
"Keep-Alive" = (
"timeout=10, max=100"
);
"Set-Cookie" = (
"LtpaToken2=L6DEf/sqCSjiI1rePW3wEWZo40oNAsxmNVBNTpIRm3FZZRSSgaqmUTDYdjTq2PNE4+FhiIOKw7Xzuta4+LpD3cUB8QKZQ/KVom/rFFQ50XNkpQezmgMlgsmDDgtodRxVU5eyo1P1NP6r/3M55eY4HkeD583kXQB3/+EH3dIryo0ii6Jn6PrxaspX5noEo0eSt+yF2AylLdU66fCcSMJw7LCrB8Tulna4xHe4Nb9i+O5z2mnTXoIgbozDGuXfS6Y20zPrsaN62Bx1X/nySf1luf1QMhrt6P4SPF6GVudm0s/Db9dS0b444kJA4kMSJ0NbZ2khMzV1zSg3eZY6xZg2kidV8Qczpe5bL2/DNrPQY/CrUo8wcdFE1ebfxDcVrjv3G+nH6uKOPWtbcHHx9Wp1gvHLxj3cJ5MP43AzxW/7GXPA7QlsmlquxW1Ck7OypsP2hrYCvCWubjGdM51cg8uqhIonI+uXRO6BlcXIsPOfpR+LbQfDNo+9vzXzB+CZKZmYnBX63ffWhX09Cr+Ua0a2Sw8mOcE5jXImlO49+ak0FHPkiiaSABzuOl6ALYg9J6LCxjm6MC9bKd7KbMPueJI/ugVeMyphQwss5AHxic8fVmo+7/XNRT6zr4I/01N8xFQsqrvx5+i2AhxWO1bdDKmpZQLPoTHMD7TPcFBkwDXLVqXPXkpkcGvg3mI8ssKOOlxwJT7/SETcqrCY5O8Yr505qdeZiNIj4kjKiLoLuNpE+ZI=; Path=/"
);
} }
Anyone has an idea why I was receiving a 405 error method not allowed? The POST method works for me if I use POSTMAN. It works if I use PUT or GET endpoints with Swift code, but it fails if I try to use endpoints with POST method in Swift.
I see something strange, the "Content-Type" is defined as text/plain in the response, but I set it as "application/json". I don't understand why the config was not being set.
If I call it via POSTMAN, it works, but for some reason I don't know why it not works when I use Swift.
--- EDIT ---
After #matt suggestion, I use Postman to generate the Swift code.
I copy and paste the Swift code to my project, this is the code:
var semaphore = DispatchSemaphore (value: 0)
let parameters = "{ \n \"token\":\"MY_TOKEN\",\n \"resenha\": {\n \"codAP\":\"353750303020001\",\n \"codPropriedade\":\"0\",\n \"cpfVeterinario\":\"01787568814\",\n \"coordGeoLat\": \"37.421565\",\n \"coordGeoLong\": \"-122.084\",\n \"cpfCnpjProdutor\": \"89058500810\",\n \"dataNascimentoAnimal\": \"01/08/1981\",\n \"fotos\": null,\n \"graficas\": null,\n \"id\": \"1\",\n \"idComposicaoPelagem\": \"50\",\n \"idCorOlhoDir\": \"39902\",\n \"idCorOlhoEsq\": \"39902\",\n \"idEspecie\": \"5\",\n \"idPelagem\": \"6\",\n \"idRaca\": \"34\",\n \"idResenhaAnterior\":\"0\",\n \"idSexo\": \"2501\",\n \"machoCastrado\": \"N\",\n \"microChipAnimal\": \"123456989012377\",\n \"microchipMae\": \"\",\n \"nomeAnimal\": \"MACADANIAS111\",\n \"numeroAssocRaca\": \"\",\n \"numeroPassaporte\": \"\",\n \"outrasCaracteristicas\": null,\n \"quantAnimaisEq\": \"05\",\n \"quantAnimaisAs\": \"0\",\n \"quantAnimaisMu\": \"02\",\n \"retifica\": false\n }\n}"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://MY_ENDPOINT/validaResenha")!,timeoutInterval: Double.infinity)
request.addValue("Basic THIS_IS_BASIC_AUTH_VALIDATION", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("JSESSIONID=0000_B1PZRSVcyzEkDUkMxvk9ig:18jgnbg8n; LtpaToken2=q9JsIHVBKPsCYKGRohXJAKnXED3HRXXGlaswzYpnPSLS0B+c/WbiW+QcUMwmw/8xcb7VL1bVvbUh0ZAvMR3TNcGudWUkg9f0z5K0n0P2pJ5Frte6trqVLhPoKuI5E7zwC3Yg+XCsPBNFy0aukkrWNiCWAqbyGI3nir6UuX5qLER4H+bEYfk4cFw58eHGSIN/FTVjH7WW7aEAfkYNXxWzSDnNVJDtihZVXw+oJSfe74Vz8Scv33cPPZH2W74KvKwj09FOo+EJsvFcC2aDUQclYqwuo91HIaIpqcYb17cSCX95xn9KHErlC48M1bU03txKaDVcmUrOCrveCs7pVPNCz066cil5bzjXeYlXDlmUw5MT45Zgg8EmaJ9gi+iC2zPCU+W088OGEriphXpto40ww3irTN9rtnhIppB5U+drRFW6u25UmDkAjx899TNzC/XsJqkRXn9GinQv6xiD+Axnv3AgudQZBGyeYcNNJDRfA+jzbr6HE1NuNSkxY6aP1OvCLGkNDSA16chO7f4IjjR9jkvDH2m3+ajxa7as1rVNK9R0HHcZJLExvOJn3sJ1LKDwMNPTDjKGPLuWOVwTPQL2pzIitLjkeyx8A2Qcqo5p8U/+aa11Z/x8WA0bQRscZLWMtEHE6WLnHFqBaylCAzARF0Y5cOI/TYCW2xd99ux2WaJnumVlskr2uNCWdwSMOp78gvmzdmonQUH0Ko/k4wa8HcJPyMV5NK52gArIyGmeKXo=", forHTTPHeaderField: "Cookie")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
print("end")
But I got now a 401 error. For some reason the basic Auth is not being accepted by the code or by the server.
I checked the user and password and they are correct.
I find out the fix for my problem.
I was using "http://MY_ENDPOINT/validaResenha" in my constants file instead of using "https://MY_ENDPOINT/validaResenha".
After add the "s" to "http" letter (it becomes "https") everything starts to work for me.
The strange part is that GET and PUT methods works fine because of the redirect from HTTP to HTTPS, but in the case of POST calls, I got this error.
It's fixed now.
iOS block HTTP use HTTPS or add to your Info.plist file

Post a json patch in Swift 5

I'm testing an api call in Swift with Patch to update an object partially.
It worked well with Postman
PATCH http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965
[
{
"op": "add",
"path": "/firstname",
"value": "wakaka"
}
]
Here's my playground:
let urlString = "http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965"
let url = URL(string: urlString)
var request = URLRequest(url: url!)
// guard var request = request else { return nil }
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("gzip, deflate, br", forHTTPHeaderField: "Accept-Encoding")
request.httpMethod = "PATCH"
let jsonPatch = "[{\"op\" : \"add\", \"path\" : \"/firstname\", \"value\": \"my first name\"}]"
do {
let encodedResult = try JSONEncoder().encode(jsonPatch)
print(encodedResult.debugDescription)
request.httpBody = encodedResult
print(request.httpBody?.description)
} catch let error {
print(error.localizedDescription)
}
// decoding
URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("err: ",error.debugDescription)
return
}
// handling api's errors
if let res = response as? HTTPURLResponse {
print(res.statusCode)
switch res.statusCode {
case 400:
print("400")
// completion(.failure(ApiError.badRequest))
return
case 409:
print("409")
return
case 422:
print("422")
print(res.debugDescription)
return
default:
break
}
}
// OK
do {
let result = try JSONSerialization.jsonObject(with: data!, options: [])
print("json:", result)
} catch let jsonError {
print("error:", jsonError.localizedDescription)
}
}
.resume()
The result I got:
<NSHTTPURLResponse: 0x600000921320> { URL: http://localhost:5000/api/accounts/eca9c1b05fb24ca192afe370aa5a1965 } { Status Code: 422, Headers {
"Content-Length" = (
350
);
"Content-Type" = (
"application/problem+json; charset=utf-8"
);
Date = (
"Thu, 10 Jun 2021 15:59:29 GMT"
);
Server = (
Kestrel
);
} }
That weird when it returns 422 while my call on Postman works well. Thanks for any advice!

Grab content from POST call URLSession

I am trying to pull the cookie from this POST call to use for another call.
I have a URLSession response for a POST call here:
<NSHTTPURLResponse: 0x600000418120> { URL: https://example.com:443/Auth/ } { Status Code: 200, Headers {
Accept = (
"*/*"
);
"Accept-Encoding" = (
"br, gzip, deflate"
);
"Accept-Language" = (
"en-us"
);
Authorization = (
"Basic keyHere=="
);
"Content-Encoding" = (
gzip
);
"Content-Type" = (
"application/json"
);
Date = (
"Tue, 25 Sep 2018 18:17:38 GMT"
);
Host = (
"example.com:443"
);
"SMSESSION-Idle-Expire" = (
"Tue, 25-Sep-2018 20:17:38 GMT"
);
"SMSESSION-Session-Expire" = (
"Wed, 26-Sep-2018 04:17:38 GMT"
);
"Set-Cookie" = (
"SMSESSION=sessionKeyHere==;Domain=example.com;Path=/"
);
"Transfer-Encoding" = (
Identity
);
"User-Agent" = (
"Web%20Service%20Test/1 CFNetwork/974.2.1 Darwin/18.0.0"
);
"X-Forwarded-For" = (
"11.111.11.11"
);
} }
How would I pull the Set-Cookie SMSESSION key from here? Is there a correct way to do this? Or would I just parse through this response and pull the key from there?
Here is my function:
func test() {
let username = "myUsername"
let password = "myPassword"
let loginString = String(format: "%#:%#", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
let url = URL(string: "https://example.com:443/Auth/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
Thanks for the help!
Thanks #Cristik for the answer.
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
let httpResponse = response as! HTTPURLResponse // HTTPURLResponse is a subclass of URLResponse
print(httpResponse.allHeaderFields["Set-Cookie"] ?? "") // Cookie Value
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()

How to get store one specific element of a JSON post response in Swift

I have a swift program that creates a successful JSON post to a rails application. This is the response:
Optional(<NSHTTPURLResponse: 0x604000226280> { URL: http://groupsyncenv.rtimfc7m2.eu-west-1.elasticbeanstalk.com/login_post } { Status Code: 200, Headers {
"Cache-Control" = (
"max-age=0, private, must-revalidate"
);
Connection = (
close
);
"Content-Length" = (
618
);
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Wed, 24 Jan 2018 17:57:52 GMT"
);
Etag = (
"W/\"c34b1ba0f3cfbd53ef65a30eddd47c50\""
);
Server = (
"nginx/1.12.1"
);
Via = (
"1.1 m00180A4E4E3C (squid/3.5.23)"
);
"X-Cache" = (
"MISS from m00180A4E4E3C"
);
"X-Cache-Lookup" = (
"MISS from m00180A4E4E3C:3128"
);
"X-Content-Type-Options" = (
nosniff
);
"X-Frame-Options" = (
SAMEORIGIN
);
"X-Request-Id" = (
"9bf3c1fa-e362-4d59-8396-8540981f1d36"
);
"X-Runtime" = (
"0.092878"
);
"X-XSS-Protection" = (
"1; mode=block"
);
All I need from this code is the number associated with the response "X-Request-Id" but I'm not sure how to do it. My swift program is below:
func loginPost(){
let headers = [
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"Postman-Token": "b5468cec-292a-6c60-d195-6e270909e54b"
]
let parameters = [
"email": "sample#email.com",
"password": "password123"
] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
guard let data = postData else {
return
}
let request = NSMutableURLRequest(url: NSURL(string: "http://groupsyncenv.rtimfc7um2.eu-west-1.elasticbeanstalk.com/login_post")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as? Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
As you can see I'm just printing the Http response which I know is wrong but I can't figure out how to access individual elements here. Thanks in advance for any help!
You can simply access the HTTP headers after casting the URLResponse object to HTTPURLResponse by calling response.allHeaderFields, which is a Dictionary, so you can use subscription to get the value corresponding to a specific key.
Some generic advice: don't use old Foundation data types unless you have a very good reason to do so. Use their native Swift alternatives. This is especially true when you are casting the Foundation objects to their Swift alternatives right after creating them, since the Swift APIs expect Swift types, such as URLRequest rather than NSMutableURLRequest and URL instead of NSURL.
let headers = [
"Content-Type": "application/json",
"Cache-Control": "no-cache"
]
let parameters = [
"email": "sample#email.com",
"password": "password123"
] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
var request = URLRequest(url: URL(string: "http://groupsyncenv.rtimfc7um2.eu-west-1.elasticbeanstalk.com/login_post")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
if (error != nil) {
print(error!)
} else if let response = response as? HTTPURLResponse {
let requestId = response.allHeaderFields["X-Request-Id"] as? String
print(requestId)
}
}).resume()

401 Forbidden when sending email with Swift and Mailgun

I have the following code but consistently get error 401 forbidden when attempting to run it:
func email() {
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/{edited_out}/messages")! as URL)
request.httpMethod = "POST"
let data = "from: Swift Email <(test#test.com)>&to: [my_email_address#gmail.com,(my_email_address#gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
request.httpBody = data.data(using: String.Encoding.ascii)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("key-{edited_out}", forHTTPHeaderField: "api")
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The error is:
url = https://api.mailgun.net/v3/{edited_out}/messages
response = <NSHTTPURLResponse: 0x600000226a20> { URL: https://api.mailgun.net/v3/{edited_out}/messages } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 9;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 29 Dec 2016 21:22:46 GMT";
Server = nginx;
"Www-Authenticate" = "Basic realm=\"MG API\"";
} }
response code = 401
If I send such a request via curl with my credentials it works fine.
Any ideas?
You need to set the uesrname and the password.
Something like this:
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
and base64Credentials is the :
let credentials= String(format: "%#:%#", username, password)
let base64Credentials= credentials.data(using: String.Encoding.utf8)!
Finally got it working with the following code, if it helps anyone else:
func email() {
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/{edited_out}/messages")! as URL)
request.httpMethod = "POST"
let credentials = "api:key-{omitted}"
request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")
let data = "from: Swift Email <(test#test.com)>&to: [my_email_address#gmail.com,(my_email_address#gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
request.httpBody = data.data(using: String.Encoding.ascii)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
So I guess the answer from William would have worked with:
let base64Credentials = credentials.data(using: String.Encoding.utf8)!.base64EncodedString()
Instead of:
let base64Credentials = credentials.data(using: String.Encoding.utf8)!