Reputation: 21
I am new to iOS development. GET method working fine.
However, POST method returns 500 response..
Here is my POST controller is Swift:
@IBAction func pressedPost(_ sender: Any) {
let restEndPoinst: String = "http://tresmorewebapi.azurewebsites.net/api/accounts"
guard let url = URL(string: restEndPoinst) else {
print("Error creating URL")
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
// api key need urlRequest.setValue(<#T##value: String?##String?#>, forHTTPHeaderField: "APIKey")
let jsonDictionary = NSMutableDictionary()
jsonDictionary.setValue(9, forKey: "Id")
jsonDictionary.setValue("From iOS!", forKey: "UserName")
jsonDictionary.setValue("HAHAH iOS", forKey: "UserEmail")
jsonDictionary.setValue(200.44, forKey: "Rebate")
jsonDictionary.setValue(1200.20, forKey: "MemCom")
let jsonData: Data
do{
jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions())
}
catch{
print("Error creating JSON")
return
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest, completionHandler:
{
(data: Data?, response: URLResponse?, error: Error?) in
print("Error:")
print(error)
print("response:")
print(response)
print("Data:")
print(String(data: data!, encoding: String.Encoding.utf8))
})
task.resume()
}
And my model is look like below:
public class Account
{
public int Id { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
public decimal Rebate { get; set; }
public decimal MemCom { get; set; }
}
I followed Youtube tutorial using swift and azure by asp.net web api
if you search iOS Swift Calling POST, PUT and DELETE on Azure REST Web Service
that is the one I was following.
Please help me how to fix POST request to insert some data to my azure web server.
Upvotes: 0
Views: 1197
Reputation: 21
Answer to this question.. I forgot httpbody
Here is fixed POST in do-catch:
do{
jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions())
urlRequest.httpBody = jsonData
}
Upvotes: 1