API URL to post json formatted data - ios

How would I transfer code from textfields into json formatted data.
Below is the current code i have, but it doesn't seem to transfer the data within the textfields to json when the button is clicked. Is their any errors within this code?
#IBAction func submitButton(_ sender: Any) {
// parse in paramaters
let parameters = ["Name": nameTextField, "Email": emailTextField, "DOB": dateTextField] as [String : Any]
guard let url = URL(string: "https://prod-69.westeurope.logic.azure.com/workflows/d2ec580e6805459893e498d43f292462/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=zn8yq-Xe3cOCDoRWTiLwDsUDXAwdGSNzxKL5OUHJPxo") else { return }
var request = URLRequest(url: url)
// let url session know that this is a post request
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// convert paramaters to JSON
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
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()
}

Are nameTextField, emailTextField and dateTextField of type String or UITextField. Make sure you are passing the UITextField.text property and not the UITextField itself.
See below:
guard let name = nameTextField.text,
let email = emailTextField.text,
let dob = dateTextField.text else {
return
}
let parameters: [String: String] = ["name": name, "email": email, "dob": dob]

Related

Swift HTTP Post Request returns HTML of site instead of JSON response

I am trying to reach a site that should take the username and password given and return a JSON which contains information stating whether or not the login data provided was valid or not.
However, all I'm getting back is the site's HTML code instead of a response. I've tried the request with the same parameters on https://www.hurl.it/ and have gotten the correct response so that does not seem to be the issue.
I use the following code:
private func uploadToAPI(username: String, password: String) {
guard let url = URL(string: "http://api.foo.com/login.php"),
let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {
self.loginButton.isLoading = false
return
}
let httpBodyParameters = ["user": encodedUsername, "password": encodedPassword, "client": "ios", "version": "5"]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: httpBodyParameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response.mimeType) // Prints "text/html"
}
if let data = data {
print(try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)) // Prints nil
print(String(data: data, encoding: String.Encoding.utf8)) // Prints the site's HTML
}
}.resume()
}
I fail to see where the issue is. I've also tried not setting the HTTP headers but that makes no difference. Anyone got any ideas?
It seems like not setting the HTTP header fields and using a string literal instead of a Dictionary as HTTP body data did it for me.
For anyone interested this is the code that now receives the expected response:
guard let url = URL(string: "http://api.foo.com/login.php?"),
let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {
if let delegate = self.delegate {
delegate.viewModelDidRejectLogin(self)
}
return
}
let httpBodyString = "user=\(encodedUsername)&password=\(encodedPassword)&client=ios&version=5"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = httpBodyString.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print(error)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String : AnyObject] {
self.readLoginResponse(json)
}
} catch {
print(error)
}
}.resume()

how to use server response and data in other functions in swift 3

am making a post request to a server and the server responds with some data,am storing the recived data in a variable named json now am trying to access this variable from other functions but i get an error : "use of unresolved identifier "json"
here is the code incase u need it
#IBAction func Login(_ sender: UIButton) {
guard let url = URL(string: "url was here..lol") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "data to be posted"
print(postString)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.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: []) as! [String: Any]
let token = json?["access_token"] as! String
print (json)
}
}
}
task.resume()
}
You need to declare the variables you want to share between functions on the class level so they can be accessed by each function in the class. token is an instance property of the class with this implementation, so each class instance has its own variable called token that can be accessed anywhere inside the class.
class MyViewController: UIViewController {
var token = ""
#IBAction func Login(_ sender: UIButton) {
guard let url = URL(string: "url was here..lol") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "data to be posted"
print(postString)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
}
if let data = data {
guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else {return}
guard let receivedToken = json["access_token"] as? String else {return}
self.token = receivedToken
otherFunction()
}
}
task.resume()
}
func otherFunction(){
print(token)
}
}

JSON response format is incorrect(Swift)

I am new to Swift and I am getting response from mysql through PHP script in JSON format. But my JSON is in correct format :
["Result": <__NSArrayI 0x60000005bc60>(
<__NSArray0 0x608000000610>(
)
,
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
)
]
my code for serialisation is :
let url = URL(string: "my url")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "Id=\(Id)"
request.httpBody = body.data(using: .utf8)
// request.addValue("application/json", forHTTPHeaderField: "Content-type")
URLSession.shared.dataTask(with: request) { data, response, error in
if error == nil {
DispatchQueue.main.async(execute: {
do {
if let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Dictionary<String,Any>{
print(json)
Where am I going wrong?
POSTMAN output
{
"Result": [
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
]
}
Try it once.
let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
Swift 3.0
Try this code..
//declare parameter as a dictionary
let parameters = ["Id": Id"] as Dictionary<String, String>
//url
let url = URL(string: "http://test.com/api")!
//session object
let session = URLSession.shared
//URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST"
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("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
Alamofire
Try this code using Alamofire..
let parameters = [
"name": "user1"]
let url = "https://myurl.com/api"
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
failure(0,"Error")
}
}
Make sure you get the response as json. Some times get string as response. If you get string then convert that json string to json object.
Check it is a valid json object
let valid = JSONSerialization.isValidJSONObject(jsonOBJ) // jsonOBJ is the response from server
print(valid) // if true then it is a valid json object

authenticating json data, it does not take username and password in swift? can you correct me my code?

http://beta.json-generator.com/api/json/get/E1jKVbplX I have registered successfully. i am struck in authentication. i accessed all data. but i struck in accessing individual user data. please see below code and correct me. var email = “bhupal”
var pwd = “k”
//
let parameters: Dictionary<String, AnyObject> = ["Email": email as AnyObject, "Password": pwd as AnyObject,"Type" : "Organization" as AnyObject,"Mode" : "Register" as AnyObject]
//create the url with URL
let url = URL(string: "http://beta.json-generator.com/api/json/get/E1jKVbplX ")! //change the url
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as GET
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
print("--------")
print(myJson[0])
print(myJson[1])
print("--------")
email = myJson["Email"] as? String
pwd = myJson["Password"] as? String
print("--------")
print(email)
print(pwd)
print("--------")
}
catch
{
}
}
}
}
task.resume()
Your response is Array of Dictionary so myJson[0] will return you a dictionary object and in that dictionary you should try accessing value for Email or Password.
You can try below code to access email and password :
for dict in myJson { // myJson is array and dict will of dictionary object
let email = dict[Email]
let password = dict[Password]
print("--------")
print("Email is : \(email)")
print("Password is : \(password)")
print("--------")
}
Note : You make need to improvise it.

Swift JSON parsing username and password

I am trying to POST username & password as NSDictionary through JSON format. I am getting this following error :
Domain=NSCocoaErrorDomain Code=3840 "
JSON text did not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
My code is below:
#IBAction func loginAuthentication(_ sender: UIButton) {
let username : NSString = NameTextField.text! as NSString
let password : NSString = passwordTextField.text! as NSString
let parameters = [
"username": "\(username)",
"password": "\(password)"
]
print(parameters)
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
]
if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {
let request = NSMutableURLRequest(url: URL(string: "http://..")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
print(request.httpBody)
// let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if (error != nil) {
print("Error message \(error)")
} else {
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
{
let success = json["error"] as? Bool
print("Error from php\(success)")
let message = json["message"] as? String
// here you check your success code.
if (success == false)
{
print("Result1 \(message)")
self.performSegue(withIdentifier: "", sender: self)
}
else
{
self.dismiss(animated: true, completion: nil)
print("Result2 \(message)")
}
}
})
}
}
task.resume()
}
}
The problem looks to me like your string is not being serialized correctly. Instead of your current json serialization approach, simply convert a swift dictionary to data.
//Start with a dictionary
let body = [
"username": "bob",
"password": "admin"
]
//Serialize it.... you might want to put this in a do try catch block instead
let jsonBody = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
//Add it to the request
request.httpBody = jsonBody
//make the request, etc.
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response, error in

Resources