swift ios mobile app login submit - ios

I'm trying to program an iOS application for this website of our university: https://uniworx.ifi.lmu.de/
I failed with the login. I have managed it to send a http submit for the login form, but I always get the same site back as response. I want to get the site you normally see after logging in. What am I doing wrong?
Here is the code of my function:
func newTest()
{
let request = NSMutableURLRequest(url: NSURL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")! as URL)
request.httpMethod = "POST"
let postString = "username=myusername&password=mypassword"
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 {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString)")
}
task.resume()
}
I've changed my real username and password in the code -of course-.

Try this I hope it would be helpful for you!!
In Swift 2+
let request = NSMutableURLRequest(URL: NSURL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
In Swift 3 You can
var request = URLRequest(url: URL(string: "http://uniworx.ifi.lmu.de/?action=uniworxLoginDo")!)
request.httpMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()

Related

Swift 4 - When sending POST request to localhost, my URLRequest sends the JSON data with the dictionary as a key

Seems like a simple error, but I cannot resolve it for some reason:
let parameters = ["user_id":usernameTF.text!, "password": passwordTF.text!]
let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
print(parameters)
print(jsonData!)
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.httpMethod = "POST"
debugTV.text = "\(parameters["user_id"]!)"+"\(parameters["password"]!)"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options:[])
// pass dictionary to nsdata object and set it as request body
print(request.httpBody!)
} catch let error {
print(error.localizedDescription)
}
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
return
}
guard let data = data else {
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
let responseString = String(data: data, encoding: .utf8)
print(responseString!)
}
when see the NodeJS debug window, my request body is
req.body = { '[password: "test", user_id: "test"]':'' }
how can I convert the request data into a JSON object?

Data posting server gets error in swift 3?

Here i got a token number from api like as shown here "210" and it is saving using userdefaults but when i tried to retrieve data from the userdefaults then it is returning "\"210\"" like this why it is adding slashes and quotes can anyone help me how to resolve this ?
here is the code for posting key
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.CustomerToken!)", forHTTPHeaderField: "Authorization")
print(self.CustomerToken!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(responseString!)
self.customerCartIdNumber = responseString!
self.customerCartIdNumber = responseString!
UserDefaults.standard.set(self.customerCartIdNumber, forKey: "CustomerLoginNumber")
print(self.customerCartIdNumber!)
print(responseString!)
here is the code for getting key
let customerId = UserDefaults.standard.string(forKey: "CustomerLoginNumber")
self.customerCartId = customerId!
print(customerId!)
here is the code for posting
func customerAddToCartItemsDownloadJsonWithURl(cartApi: String){
let url = URL(string: cartApi)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
let cartNumber = customerCartId?.replacingOccurrences(of: "\\", with: "")
let parameters : [String: Any] = ["cartItem":
[
"quote_id": "\(customerCartId!)",
"sku": "\(itemCode!)",
"qty":"1"
]
]
print(customerCartId)
print(parameters)
print(cartNumber)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
}

Why is my Bool value changed to false after exiting the nested method? [duplicate]

This question already has answers here:
Returning data from async call in Swift function
(13 answers)
Closed 6 years ago.
I'm trying to perform a login as follows:
func login()->Bool
{
var result:Bool = false;
var request = URLRequest(url: URL(string: "http://something.com/authenticate")!)
request.httpMethod = "POST"
let postString = "email=\(usernameField.text!)&password=\(passwordField.text!)"
print("email=\(usernameField.text!)&password=\(passwordField.text!)")
request.httpBody = postString.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(error)")
result = false;
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
print("request = \(request)")
result = false
}
let responseString = String(data: data, encoding: .utf8)
result = true;
print("responseString = \(responseString)")
self.processResponse(jsonData:data)
}
task.resume()
return result;
}
My 'result' variable always resolves to false even if the line result = true is hit.
How to set it to true inside the nested method?
You are using Block and blocks are not call at the same time when you are calling "login" method. So, you need to implement blocks for receive result. Try Following Code :
func login(block:((Bool) -> Void)!)
{
var result:Bool = false;
var request = URLRequest(url: URL(string: "http://something.com/authenticate")!)
request.httpMethod = "POST"
let postString = "email=\(usernameField.text!)&password=\(passwordField.text!)"
print("email=\(usernameField.text!)&password=\(passwordField.text!)")
request.httpBody = postString.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(error)")
result = false;
block(result)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
print("request = \(request)")
result = false
}
if data != nil
{
result = true
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
self.processResponse(jsonData:data)
block(result)
}
task.resume()
}

HTTP Send Request Parameter in Swift

i want to send request with username and password for getting authentication key from server, here is my code, i don't know how send to parameter with request, please help me for solve it.
let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate"
func recentProfileURL(parameter : [String:String]?) -> NSURL {
let component = NSURLComponents(string: urlString)!
var queryItem = [NSURLQueryItem]()
if let param = parameter {
for (key,value) in param {
let item = NSURLQueryItem(name: key, value: value)
queryItem.append(item)
}
}
component.queryItems = queryItem
return component.URL!
}
func fetchCode(completion completion: (ProfileResult) -> Void){
let request = NSURLRequest(URL: recentProfileURL(["UserName": self.userNameParam]))
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) in
let result = self.processUserProfileRequest(data: data, error: error)
completion(result)
})
task.resume()
}
I'm trying send username and password for getting authentication code from server how can send array of parameter instead of one parameter?
Try this I hope it would be helpful for you!!
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
try this code
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
This should work for you:
var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")`
}

INPUT_VALIDATION_ERROR in BetFair Login API / iOS

I am getting INPUT_VALIDATION_ERROR while logging into betfair api. I am following the docs, but it was of no use with this particular error code.
I'd appreciate if anyone could guide me in the right direction.
Here is my swift code
let request = NSMutableURLRequest(URL: NSURL(string: "https://identitysso.betfair.com/api/login")!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("MY_APP_KEY", forHTTPHeaderField: "X-Application")
let postString = "username=MY_USER_NAME&password=MY_PASSWORD"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
I think you need to set header in http for Content-Type as
application/x-www-form-urlencoded
Three parameters in Http header:
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setHeader("X-Application", <apiKey>);

Resources