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

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()
}

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?

How to solve this issue "Ambiguous reference to member 'dataTask(with:completionHandler:)' " [duplicate]

This question already has answers here:
Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)
(14 answers)
Closed 5 years ago.
How to solve this issue
Ambiguous reference to member 'dataTask(with:completionHandler:)'
guard let requestUrl = URL(string:"http://www.digi.com/laravel_api_demo/api/demoapi") else { return }
let request = NSMutableURLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "firstName=James&lastName=Bond"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request){ (data, response, error) in
if error != nil
{
//print(error)
return
}
//You can print out response object
print("response = \(response)")
//Print out response body
let responseString = String(data: data, encoding: NSUTF8StringEncoding)
print("response data = \(responseString)")
var err: Error?
var json = JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
var firstNameValue = parseJSON["firstName"] as? String
print("first name value = \(firstNameValue)")
}
}
task.resume()
}
Call should be like this , first parameter is of type URL not NSMutableURLRequest
guard let requestUrl = URL(string:"http://www.digi.com/laravel_api_demo/api/demoapi") else { return }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "firstName=James&lastName=Bond"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request){ (data, response, error) in
if error != nil
{
//print(error)
return
}
}
task.resume()
see here signature of available methods

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()
}

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)")`
}

swift ios mobile app login submit

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()

Resources