Sending JSON Data with Swift - json

I'm building a chat app and I understand how to receive the data back but I'm having trouble sending the data. I'm trying to take two UITextField values which are the username and the message and send the data.
Variables
#IBOutlet weak var username: UITextField!
#IBOutlet weak var textBox: UITextField!
Request To Receive
#IBAction func sendMessage(_ sender: UIButton) {
let parameters = ["user": username.text, "message": textBox.text] as! [String: String]
//create the url with NSURL
let url = NSURL(string: "http://website.com/getChatLogJSON.php")
//create the session object
let session = URLSession.shared
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
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)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
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 {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

Checkout SwiftyJSON, its a neat library for your JSON needs.
data insertion into the JSON object becomes as simple as:
json["name"] = JSON("new-name")
json[0] = JSON(1)
json["id"].int = 1234567890
json["coordinate"].double = 8766.766
json["name"].string = "Jack"
json.arrayObject = [1,2,3,4]
json.dictionaryObject = ["name":"Jack", "age":25]
Here is the github page, all instructions are there https://github.com/SwiftyJSON/SwiftyJSON
When it contains all data you need to put in, you can return the raw json in a string if you wish and send that which can be parsed
//convert the JSON to a raw String
if let rawString = json.rawString() {
//Do something you want
} else {
print("json.rawString is nil")
}

Related

Unable to Upload Image and add parameters with POST method multipart/form-data in Swift

Below is the URL requirement for this API: http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/
according to this answer Upload image with multipart form-data iOS in Swift
I have tried below code, but i am unable to add parameters to POST Request and i am unable to call uploadImage method in viewdidload
Here is the code:
func uploadImage(paramName: String, fileName: String, image: UIImage) {
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/")
let boundary = UUID().uuidString
let deviceId: String = "HardcodeDEVICEIDforiTaag222"
let headers = ["deviceid": "deviceId","userType": "personal","key": "5fe42fb3b54543a0bab5667cf96526f8"]
let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"]
let session = URLSession.shared
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = headers as! [String : String]
// Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
// And the boundary is also set here
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
// Add the image data to the raw http request data
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
data.append(image.pngData()!)
data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
// Send a POST request to the URL, with the data we created earlier
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error == nil {
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
if let json = jsonData as? [String: Any] {
print(json)
}
}
}).resume()
}
in the above code i am unable to add parameters let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"] to urlRequest
And How to call uploadImage in viewDidLoad
Please help me with code

How I can pass json data with a decodable struct to UserDefaults properly

I'm a student and I am trying to get a Json Data from an Http Server, and after that save it using UserDefaults
I saw some examples and this code I made seemed to make sense even though it did not work
That is my struct I'm using to decode the json Data
struct UserLogged : Decodable {
var token: String
var userId: String
}
And this is the code I'm trying to use
guard let baseUrl = URL(string: "http://LOCALHOST:8080/auth/login") else {
return
}
var request = URLRequest(url: baseUrl);
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST";
request.httpBody = jsonData;
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
if let user : UserLogged = try JSONDecoder().decode(UserLogged.self, from: data) {
UserDefaults.standard.set(user, forKey: "userLogged")
}
} catch {
print(error)
}
}
}.resume()
You can parse that json with a decoder easily instead of JSONSerialization. It is better to save the token of user in UserDefaults instead of whole user, with a key that makes sense such as userToken:
if let data = data {
print(data)
let decoder = JSONDecoder()
do {
let user = try decoder.decode(UserLogged.self, from: data)
//now you parsed the json and get token and userId
UserDefaults.standard.set(user.token, forKey: "userToken")
} catch {
//Parsing error, couldnt parse user.
}
}

How to POST data from multiple view controllers to server with JSON using SWIFT

I need help with combining data collected from firstVC, secondVC, and thirdVC and serializing those in the fourthVC.
This link helps with one VC but I have to send only ONE FILE of JSON DATA to the server.
How to create and send the json data to server using swift language
The other method is passing a dictionary array from firstVC, secondVC, and thirdVC to the fourthVC and from the fourthVC convert the dictionaries into JSON. But i don't know how to do that.
I used the format from the answer provided in the link above, but if you need additional info, I will gladly cooperate. Thanks!
PS. Please give me useful comments that will help in any way. I need the code and not feedbacks like doing my own research and such cause I have been stressing about this for nearly a month now.
This is the UserDefault keys
if let AC = UserDefaults.standard.value(forKey: "Acc") as? String {
labeltext.text = "\(AC)"
}
if let TY = UserDefaults.standard.value(forKey: "Taxyear") as? String {
taxtext.text = "\(TY)"
}
if let BB = UserDefaults.standard.value(forKey: "Bsb") as? String {
bsbtext.text = "\(BB)"
}
Here is my JSON code
#IBAction func save(_ sender: Any){
typealias JSONDictionary = [String:Any]
let parameters = ["BankAccountNumber": "Acc", "Tax Year": "Taxyear", "my-bsb": "Bsb"]
let url = URL(string: "https://server:port/")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
let valid = JSONSerialization.isValidJSONObject(parameters) // true
print (valid)
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)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// create dataTask using the session object to send data to the server
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 {
//create 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()
let alertMessage = UIAlertController(title: "Saved!", message: "We have recorded your information", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title:"Okay", style: UIAlertActionStyle.default, handler: nil)
alertMessage.addAction(action)
self.present(alertMessage, animated: true, completion: nil)
}
I solved it by first storing them in a variable
var TITLE = UserDefaults.standard.value(forKey: "Title")
var GN = UserDefaults.standard.value(forKey: "GivenNames")
var LN = UserDefaults.standard.value(forKey: "LastName")
Then I placed them in a parameter and that's done. It was so obvious that I can't believe I didn't solve it sooner
#IBAction func save(_ sender: Any){
let parameters = ["Tax Year": TaxYear, "Title": TITLE, "first-name": GN, "sur-name": LN]

Swift: send POST request with JSONEncoder encoded data does not work

I am using the JSONEncoder that has been provided with Swift4.
I have a class called Customer that uses the Codable protocol. Inside of Customer there are four Strings.
class Customer: Codable {
var title: String
var firstName: String
var lastName: String
var email: String
}
Reading JSON with a GET Request works fine.
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
let customer = try JSONDecoder().decode(Customer.self, from: data)
DispatchQueue.main.async {
print("\(customer.title)")
print("\(customer.firstName)")
print("\(customer.lastName)")
print("\(customer.email)")
}
} catch let jsonError {
print(jsonError)
}
}.resume()
However when I start to do a POST request I am lost:
First set up the request object:
let urlString = "http://localhost:8000/customer"
guard let url = URL(string: urlString) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
let customer = Customer()
customer.title = "Mr"
customer.firstName = "Chuck"
customer.lastName = "Norris"
customer.email = "chuck.norris#awsome.com"
let encodedData = try? JSONEncoder().encode(customer)
print(String(data: encodedData!, encoding: .utf8)!) //<- Looks as intended
// Output is {"firstName":"Chuck","lastName":"Norris","title":"MR","email":"chuck.norris#awesome.com "}
Now send it out
request.httpBody = encodedData //
URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.data(withJSONObject: data, options: [])
print(json)
}catch {
print(error)
}
}
})
In return I receive the message "The given data was not valid JSON."
So, my assumption is that I simply can not just put the encoded JSON data into the http body of my request.
Browsing through some articles about URLSession and JSON I found that it seems that I need to serialize my encoded JSON:
var json: Any?
if let data = encodedData {
json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
}
Now, I don't know how to proceed. First I do not understand why I should serialize my JSON to something that can not simply put into a httpBody.
Because JSONSerialization.jsonObject produces Any? and not Data.
Update
Now, I was able to successfully send my data to my server. I am still trying to understand what was wrong - because I did not changed anything (except for the removal of the JSONSerialization call inside the completion Handler. I will investigate further...
...And .resume had been missing. :-)

Posting user input JSON in Swift

I am trying to collect data from user and send it to an web service, however I get an error "invalid top-level type in JSON write" I am collecting the steps from the healthstore in another function and all the data is passed into the userhealthprofile variables correctly as it works printing them out. However something is wrong with my JSON code
Full error message is
2017-10-17 09:30:57.170950+0200 IphoneReader[347:40755] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(0x1d0b3b3d 0x1c33b067 0x1d0b3a85 0x1da763c1 0x9aa50 0x9bb60 0x2231a3b5 0x2231a349 0x22304979 0x22321f87 0x2286bf1b 0x22868833 0x22868423 0x22867849 0x223146f5 0x222e62bb 0x22a797f7 0x22a7419b 0x22a7457d 0x1d06ffdd 0x1d06fb05 0x1d06df51 0x1cfc11af 0x1cfc0fd1 0x1e76bb41 0x22349a53 0xa4d18 0x1c7ae4eb)
libc++abi.dylib: terminating with uncaught exception of type NSException
Code
#IBAction func submitAction(sender: AnyObject) {
userHealthProfile.name = nameLabel.text
print(userHealthProfile.name)
userHealthProfile.age = Int(ageLabel.text!)
print(userHealthProfile.age)
userHealthProfile.heightInMeters = Int(heightLabel.text!)
print(userHealthProfile.heightInMeters)
userHealthProfile.weightInKilograms = Int(weightLabel.text!)
print(userHealthProfile.weightInKilograms)
for element in stepy.step {
print(element)
}
userHealthProfile.totalStepsCount = stepy.step
print("pressing button")
//create the url with URL
let url = URL(string: "www.thisismylink.com/postName.php")!
//change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: userHealthProfile, 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")
//create dataTask using the session object to send data to the server
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 {
//create 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()
}
This is what userprofile looks like, this is what I need to send as a jsonobject for my web service.
class UserHealthProfile {
var name: String?
var age: Int?
var totalStepsCount: Array<Any>!
var heightInMeters: Int?
var weightInKilograms: Int?
}
I think you should use Alamofire for calling web API..
Here is the sample code according to your requirements.
I hope this will help you...
func Submit(parametersToSend:NSDictionary)
{
Alamofire.request(.POST, "http://www.thisismylink.com/postName.php",parameters: parametersToSend as? [String : AnyObject], encoding: .URL).responseJSON
{
response in switch response.2
{
case .Success(let JSON):
print(JSON)
let response = JSON as! NSDictionary
print("My Web Api Response: \(response)")
break
case .Failure(let error):
print("Request failed with error: \(error)")
break
}
}
}
Function Calling in your #IBAction func submitAction(sender: AnyObject) like this
#IBAction func submitAction(sender: AnyObject) {
let steps = stepy.step
let name = nameLabel.text!
let age = Int(ageLabel.text!)
let height = Int(heightLabel.text!)
let weight = Int(weightLabel.text!)
let parameters = [
"name": name
"age": age
"totalStepsCount": steps
"heightInMeters": height
"weightInKilograms": weight
]
self.submit(parametersToSend:parameters)
}