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

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

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?

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

Swift - Multiple Parameters to webservice

I have the following code that should send a username and password off to a webservice, in return I get a single integer back:
func attemptLogin() {
let url:URL = URL(string: endpoint+"/LoginNew")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let postString = "username="+txtUsername.text! + "; password="+txtPassword.text!
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString)
}
task.resume()
}
In my function I need to add two parameters are I'm trying to do in this line:
let postString = "username="+txtUsername.text! + "; password="+txtPassword.text!
request.httpBody = postString.data(using: String.Encoding.utf8)
I am getting the following response from my web service when I run this however
Optional("Missing parameter: password.\r\n")
I am obviously not appending the parameters to the request properly but I'm not sure what I've done wrong.
It is good practice to avoid using explicit unwraps of optionals (using !), use guard let for text i UITextFields instead.
And why not separate into two methods, attemptLogin and login, which maybe can take a closure for code to execute when sign in completed? Maybe the closure can take an Result enum.
Like this:
typealias Done = (Result) -> Void
enum MyError: Error {
case unknown
}
enum Result {
case success(String)
case failure(MyError)
init(_ error: MyError) {
self = .failure(error)
}
init(_ dataString: String) {
self = .success(dataString)
}
}
func login(username: String, password: String, done: Done? = nil) {
let session = URLSession.shared
guard
let url = URL(string: endpoint+"/LoginNew"),
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let postString = "username=\(username)&password=\(password)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request) {
(data, response, error) in
guard let data = data else { done?(Result(.unknown)); return }
let dataString = String(data: data, encoding: String.Encoding.utf8)
done?(Result(dataString))
}
task.resume()
}
func attemptLogin() {
guard
let username = txtUsername.text,
let password = txtPassword.text
else { return }
login(username: username, password: password) {
result in
swicth result {
case .success(let dataString):
print(dataString)
case .failure(let error):
print("Failed with error: \(error)")
}
}
}
Disclaimer: Have not tested the code above, but hopefully it compiles (at least with very small changes).

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 HTTP request post json

I want to make a HTTP request to a server but I have troubles parsing my data to JSON.
This is my code:
let dic = ["interest":["category":"Viajes","value":"Mexico"],"metadata":["version":"0.1","count":1]]
do{
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions())
let url:NSURL = NSURL(string: "http://ip/interests")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
//let paramString = ""
//request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = jsonData
let dataString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
print(dataString)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print(error)
return
}
print(response?.description)
}
task.resume()
}catch let error as NSError {
print(error)
return
}
The server catch :
{ '{"interest":{"category":"Viajes","value":"Mexico"},"metadata":{"count":1,"version":"0.1"}}': '' }
What I want:
{"interest":{"category":"Viajes","value":"Mexico"},"metadata":{"count":1,"version":"0.1"}}
Anybody knows how to fix it?

Resources