how to get JSON data from login without alamofire - json

I am able login, but don't get any data from listpeserta. I want to get user's name etc
func onlinecheckin(){
self.password.resignFirstResponder()
let password1 = password.text;
if let user1 = user.text {
// To trim the characters to remove the empty space
let username = user1.trimmingCharacters(in: CharacterSet.whitespaces)
let passwordnya = password1!.trimmingCharacters(in: CharacterSet.whitespaces)
//Send user data to server side
let myUrl = URL(string: "https://url/jgcm/login.php")!
var request = URLRequest(url: myUrl)
request.httpMethod = "POST"
let postString = "user=\(username) & password=\(passwordnya)"
request.httpBody = postString.data(using: String.Encoding.utf8)
task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
print("response online checking =\(String(describing: response))")
if error != nil {
task.cancel() // To cancel uploading the task.
self.AlertMessage("Error. Please press Login button again.");
print("error=\(String(describing: error))")
return
}
if let datadownload = data {
resultlogin = NSString(data: datadownload, encoding: String.Encoding.utf8.rawValue)!.replacingOccurrences(of: " ", with: "");
print("result of online checking:\(resultlogin)")
}
DispatchQueue.main.async(execute: { () -> Void in
if resultlogin.contains("already") {
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "menu")
self.present(secondViewController!,animated: true,completion: nil)
} else {
self.AlertMessage("User atau Password Salah");
}
})
}
task.resume()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let datapesertac = segue.destination as? datapeserta , let user = sender as? listpeserta{
datapesertac.coba = user
}
}
data peserta controller
var coba : listpeserta?
namalogin.text = coba?.nama
it does not display anything, just show nil

Related

Keep getting an error saying "The data could not be read" because of format

Essentially I am creating a login view controller in my swift app that verifies and logs in a user.
This is how the app is requesting and going through with the POST HTTP Request:
import Foundation
enum MyResult<T, E: Error> {
case success(T)
case failure(E)
}
class NetworkingService {
let baseUrl = "https://example/example/login.php"
func handleResponse(for request: URLRequest,
completion: #escaping (Result<User, Error>) -> Void) {
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
print(unwrappedResponse.statusCode)
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do {
let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
print(json)
if let user = try? JSONDecoder().decode(User.self, from: unwrappedData) {
completion(.success(user))
} else {
let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
completion(.failure(errorResponse))
}
} catch {
completion(.failure(error))
}
}
}
}
task.resume()
}
func request(endpoint: String,
parameters: [String: Any],
completion: #escaping (Result<User, Error>) -> Void) {
guard let url = URL(string: baseUrl + endpoint) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
var components = URLComponents()
var queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: String(describing: value))
queryItems.append(queryItem)
}
components.queryItems = queryItems
let queryItemData = components.query?.data(using: .utf8)
request.httpBody = queryItemData
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
handleResponse(for: request, completion: completion)
}
func request(endpoint: String,
loginObject: Login,
completion: #escaping (Result<User, Error>) -> Void) {
guard let url = URL(string: baseUrl + endpoint) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
do {
let loginData = try JSONEncoder().encode(loginObject)
request.httpBody = loginData
} catch {
completion(.failure(NetworkingError.badEncoding))
}
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
handleResponse(for: request, completion: completion)
}
}
enum NetworkingError: Error {
case badUrl
case badResponse
case badEncoding
}
This is how the structure looks like:
import UIKit
struct User: Decodable {
let id: Int
let name: String
let username: String
}
Because I am working with a mySQL database I am using php script to produce JSON that takes parameters from input.
This is what the JSON looks like:
[
{
"id": "3",
"name": "KevinName",
"username": "kName"
}
]
The status code returns success 200 but no data is loaded into the app and I get the error
The data couldn't be read because it isn't in the correct format
I believe it has something to do with the PHP script that creates the JSON
<?php
$con=mysqli_connect("localhost","username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Equipment'
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, driver_name, username FROM table1 WHERE (username = '$username') and password = '$password' ";
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>

how to make HTTPRequest with json in swift

I am making an ios application. I am new to swift and not able to understand my code. can anyone please help me to understand what is going on with my code.
This is login application on adding email id if the email exist it should go to next view controller and if not then it should give error. I am getting difficulty in understanding my code .
Here is my code:
class checkLoginViewController: UIViewController {
#IBOutlet weak var checkUsernametextfield: UITextField!
#IBAction func checkUsernameButton(_ sender: UIButton) {
print("Clicked On SUbmit !!!!")
//Read Value from Text
let email = checkUsernametextfield.text
let myUrl = URL(string: "http://192.168.0.117/rest/signup.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "email=\(String(describing: email))";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("response = \(String(describing: response))")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of First Name by its key
let emailValue = parseJSON["email"] as? String
print("email: \(String(describing: emailValue))")
}
} catch {
print(error)
}
}
task.resume()
Output:
Clicked On SUbmit !!!! response = Optional( { URL: http://192.168.0.117/rest/signup.php } { Status
Code: 200, Headers {
Connection = (
"Keep-Alive"
);
"Content-Length" = (
61
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 12 Mar 2018 06:35:58 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Server = (
"Apache/2.4.27 (Ubuntu)"
); } }) email: nil
Maybe try this. Hope it works.
let url = URL(string:"http://192.168.0.117/rest/signup.php")
let parameters = ["email": checkUsernametextfield.text]
var request = URLRequest(url : url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
if let json = json {
print("HERE SHOULD BE YOUR JSON \(json)")
}
}
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
}).resume()
Here is way to send request.
enter code here
static func downloadConfig(url:URL, completion:#escaping (_ sucess:Bool , _ jsonObject: [String: String]?)->() ) {
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded",
forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
request.httpBody = postString.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data,response,error) in
if let data = data ,let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200 {
do {
if let todoJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]{
completion(true,todoJSON)
}
else
{
completion(false,nil)
}
}
catch {
//erro parsing
completion(false,nil)
}
}
else
{
completion(false,nil)
}
}.resume()
}
use this download json function in this way.
//Download Json File
let base_url = "base_url"
let urlstr = String.init(format: "%#", base_url)
let url = URL(string: urlstr)
GameUtil.downloadConfig(url: url!) {
(sucess: Bool , jsonObject: [String:String]?) in
if sucess , jsonObject != nil
{
self.configJson = jsonObject!
}
}

I'm having troubles with my Login authentication

I have a JSON Post authentication to make a login request, of course I need to send the user & password parameters to receive a response for filling my HomeViewController, so I need first to validate the two parameters, and if the user doesn't exist of course I'm going to send an Alert and forbid the access to the Home. The thing is that I don't know in which method do I have to put this validation, because the way I'm doing it throws me an alert before the validation. This is my code:
class LoginViewController: UIViewController, LoginProtocol {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var user : String = ""
var psw : String = ""
var idResponse : String = ""
var message : String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func validateLogin(_ sender: Any) {
DoLogin(self.username.text!, self.password.text!)
}
#IBAction func login(_ sender: Any) {
if self.idResponse != "0" {
validation(message: self.message)
} else {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController
self.present(vc, animated: false, completion: nil)
vc.getUser = self.username.text!
vc.getPassword = self.password.text!
}
}
func validation(message: String) {
let myAlert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction (title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated: true, completion: nil)
return
}
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
self.username.text = user
self.password.text = psw
let paramToSend = ["username":user,"password":psw]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let loginModel = LoginModel()
let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
loginModel.message = defaultServiceResponse["message"] as! String
loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int
self.idResponse = String(loginModel.idResponse)
self.message = loginModel.message
print(json!)
}
} catch {
let error = ErrorModel()
error.phrase = "PARSER_ERROR"
error.code = -1
error.desc = "Parser error in login action"
}
})
task.resume()
}
The validateLogin method is attached to a TextView with the action: "EditingDidEnd". So what I need is that when I finish writing the password, the DoLogin function validates that exists and let me continue to the HomeViewController, but the issue is that when I click the button 'Ingresar'(Login), it shows a blank Alert first and only the second time I click the button it let me through immediately. I don't know why is sending the Alert that I declare at the "func validation" if I'm not calling it before. I'm going to attach a picture to show you the Alert that is appearing:
Chances are your EditingDidEnd method calls DoLogin which is processing in background when you press the Login button. hence your if condition below becomes true as your idResponse is initialized to "" empty string.
if self.idResponse != "0"
Rectify this if condition to check if its empty then dont call the validation message.
The best way to do this is to call your DoLogin only after click of the Login button and if in case you have success redirect to Home page. Otherwise show the alert. Please note do the UI action on the main thread.
First Update the Code And User Like this
func DoLogin(_ user:String, _ psw:String)
{
let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = ["username":user,"password":psw]
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else
{
return
}
let json:AnyObject?
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
let loginModel = LoginModel()
let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary
loginModel.message = defaultServiceResponse["message"] as! String
loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int
self.idResponse = String(loginModel.idResponse)
self.message = loginModel.message
if self.idResponse != "0" {
validation(message: self.message)
} else {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController
self.present(vc, animated: false, completion: nil)
vc.getUser = user!
vc.getPassword = psw!
}
}
} catch {
let error = ErrorModel()
error.phrase = "PARSER_ERROR"
error.code = -1
error.desc = "Parser error in login action"
}
})
task.resume()
}
If You want to add alert in imageview use this code
var imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40))
imageView.image = yourImage
alert.view.addSubview(imageView)

How to send a POST request through Swift?

I have my controller like this -
def create
if (#user = User.find_by_email(params[:email])) && #user.valid_password?(params[:password])
render json: #user.as_json(only: [:email,:authentication_token]),status: :created
else
render json:('Unauthorized Access')
end
end
When I use Postman to make this request, I choose Body, and form data and adds in the email and password. And this WORKS
How to use swift to do the same? This is what I have tried
let url = URL(string: "http://localhost:3000/api/v1/user_serialized/")
let config = URLSessionConfiguration.default
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let bodyData = "email=Test#test.com&password=Test1234"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let session = URLSession(configuration: config)
let task = session.dataTask(with: url! as URL, completionHandler: {(data, response, error) in
let json = JSON(data:data!)
debugPrint(json)
})
task.resume()
I have made a Custom HTTP class where we can sent url, parameter and we will get Data from API. Below is the class.
import Foundation
//HTTP Methods
enum HttpMethod : String {
case GET
case POST
case DELETE
case PUT
}
class HttpClientApi: NSObject{
//TODO: remove app transport security arbitary constant from info.plist file once we get API's
var request : URLRequest?
var session : URLSession?
static func instance() -> HttpClientApi{
return HttpClientApi()
}
func makeAPICall(url: String,params: Dictionary<String, Any>?, method: HttpMethod, success:#escaping ( Data? ,HTTPURLResponse? , NSError? ) -> Void, failure: #escaping ( Data? ,HTTPURLResponse? , NSError? )-> Void) {
request = URLRequest(url: URL(string: url)!)
logging.print("URL = \(url)")
if let params = params {
let jsonData = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
request?.httpBody = jsonData//?.base64EncodedData()
//paramString.data(using: String.Encoding.utf8)
}
request?.httpMethod = method.rawValue
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30
session = URLSession(configuration: configuration)
//session?.configuration.timeoutIntervalForResource = 5
//session?.configuration.timeoutIntervalForRequest = 5
session?.dataTask(with: request! as URLRequest) { (data, response, error) -> Void in
if let data = data {
if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode {
success(data , response , error as? NSError)
} else {
failure(data , response as? HTTPURLResponse, error as? NSError)
}
}else {
failure(data , response as? HTTPURLResponse, error as? NSError)
}
}.resume()
}
}
Now you can refer below code to get how to make an API call.
var paramsDictionary = [String:Any]()
paramsDictionary["username"] = "BBB"
paramsDictionary["password"] = "refef"
HttpClientApi.instance().makeAPICall(url: "Your URL", params:paramsDictionary, method: .POST, success: { (data, response, error) in
// API call is Successfull
}, failure: { (data, response, error) in
// API call Failure
})
I think you should pass your request instead of the url to session.dataTask
here is how my code looks like:
private let url = URL(string: "http://example.com/")!
func httpPost(jsonData: Data) {
if !jsonData.isEmpty {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
NSLog("open tasks: \(openTasks)")
}
let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in
NSLog("\(response)")
})
task.resume()
}
}
Here is the Example of POST API for calling Login API with parameters "emailaddress" and "password" with userEmailID and Userpassword as two strings holding values for email and password respectively.
You can call this POST API anywhere in your view controller, as given below:
self.postLoginCall(url: "Your post method url") example: self.postLoginCall(url: "http://1.0.0.1/api/login.php")
func postLoginCall(url : String){
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
let postString = "emailaddress=\(userEmailID!)&password=\(Userpassword!)"
print(postString)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
do {
if let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject]{
print(responseJSON)
print(responseJSON["status"]!)
self.response1 = responseJSON["status"]! as! Int
print(self.response1)
//Check response from the sever
if self.response1 == 200
{
OperationQueue.main.addOperation {
//API call Successful and can perform other operatios
print("Login Successful")
}
}
else
{
OperationQueue.main.addOperation {
//API call failed and perform other operations
print("Login Failed")
}
}
}
}
catch {
print("Error -> \(error)")
}
}
task.resume()
}
Hello everyone I share below an example of a function to make a request in POST with SWIFT 5+.
This function allows you to send a POST request with an API entry point and parameters in the form of [[String: String]] and an Int to determine the output action.
For the output actions we call a function with Switch Case.
The operation is extremely simple. You have to put the two functions in one of your classes.
func MGSetRequestApi(endpoint: String, parameters: [[String: String]], MGSetAction: Int) -> String {
var setReturn: String!
let semaphore = DispatchSemaphore (value: 0)
var MGGetParam: String! = ""
for gate in parameters {
for (key, value) in gate {
let myParam = key + "=" + value + "&"
MGGetParam.append(contentsOf: myParam)
}
}
let postData = MGGetParam.data(using: .utf8)
var request = URLRequest(url: URL(string: endpoint)!,timeoutInterval: 10000)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
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)!)
setReturn = String(data: data, encoding: .utf8)!
DispatchQueue.main.async {
self.MGRequestAction(MGGetIdRq: MGSetAction, MGGetData: setReturn)
}
semaphore.signal()
}
task.resume()
semaphore.wait()
return setReturn
}
Then implement this function to manage the outputs
func MGRequestAction(MGGetIdRq: Int, MGGetData: String) {
switch MGGetIdRq {
case 1:
// Do something here
case 2:
// Do something else here
case 3:
// Do something else here again
default:
print("Set default action");
}
}
How to use this, you have two possibilities, the first one is to process what the function
MGSetRequestApi(endpoint: String, parameters: [[String: String]], MGSetAction: Int) -> String
returns (String) or to pass by the function
MGRequestAction(MGGetIdRq: Int, MGGetData: String)
which will call your Json parse function.
The MGRequestAction() function takes for parameter an Int for the choice of the action and the String of the return of the request
Now to use it do like this:
_ = MGSetRequestApi(endpoint: MY_END_POINT_API,
parameters: [["KEY_1": "VALUE 1"],
["KEY_2": "VALUE 2"],
["KEY_3": "VALUE 3"],
["KEY_4": "VALUE 4"]],
MGSetAction: 3)

Swift PayPal MassPay post call fails. can anybody point me in the right direction

this code is expected to do a Payout in PayPal using MassPay. It fails and I don't get a response from PayPal that tells me what is going on. Can somebody point me in the right direction?
let postsEndpoint: String = "https://api-3t.sandbox.paypal.com/nvp"
var postsUrlRequest = NSMutableURLRequest(URL: NSURL(string: postsEndpoint)!)
postsUrlRequest.HTTPMethod = "POST"
let paymentDict = ["USER" : "example.mydomain.com",
"PWD" : "PQDBVQXJYH4***",
"SIGNATURE" : "A9pEq0L3-2vjFoem1ajRi-b-0nWBAkujmPM.O5dJ9u-m7Vf***",
"METHOD" : "MassPay",
"VERSION" : "93",
"RECEIVERTYPE" : "EmailAddress",
"CURRENCYCODE" : "USD",
"EMAILSUBJECT" : "First payment test form swift",
"L_AMT0" : 1.25,
"L_EMAIL0" : "exampla#gmail.com",
"L_NOTE0" : "first test from swift",
"L_UNIQUEID0" : "KS1946-3"]
let newPost: NSDictionary = paymentDict
do {
let jsonPost = try NSJSONSerialization.dataWithJSONObject(newPost, options: [])
postsUrlRequest.HTTPBody = jsonPost
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let createTask = session.dataTaskWithRequest(postsUrlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
})
createTask.resume()
} catch {
print("Error: cannot create JSON from post")
}
}
working code for MassPay post to PayPal with swift from my App
func payPalMassPayOutMessage() {
let postsEndpoint: String = "https://api-3t.sandbox.paypal.com/nvp"
let postsUrlRequest = NSMutableURLRequest(URL: NSURL(string: postsEndpoint)!)
postsUrlRequest.HTTPMethod = "POST"
let paymentString = "USER=alex***.mydomain&PWD=PQDBVQXJYH4****&SIGNATURE=A9pEq0L3-2vjFoem1ajRi-b-0nWBAkujmPM.O5dJ9u-m7VfmkDJg****&METHOD=MassPay&VERSION=93&RECEIVERTYPE=EmailAddress&CURRENCYCODE=USD&EMAILSUBJECT=First payment test form swift&L_AMT0=1.25&L_EMAIL0=lguerra10#gmail.com"
do {
postsUrlRequest.HTTPBody = paymentString.dataUsingEncoding(NSUTF8StringEncoding)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let createTask = session.dataTaskWithRequest(postsUrlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling post ")
print(error)
return
}
guard let dataSring = NSString(data: data!, encoding: NSUTF8StringEncoding) else {
print("error parse dataString ")
return
}
print("response data \(dataSring)")
})
createTask.resume()
} catch {
print("Error: cannot encode paymentString")
}
}