I am learning JSONParsing. I followed tutorials and what I got is this:
guard let url = URL(string: "http://localhost/test-api/public/api/register") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let newUser = User.init(name: self.collectionTF[0].text, email: self.collectionTF[1].text, password: self.collectionTF[2].text)
do {
let jsonBody = try JSONEncoder().encode(newUser)
request.httpBody = jsonBody
} catch { }
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String:Any]
print(json!)
DispatchQueue.main.async {
if json!["status"] as! Int == 200
{
GeneralHelper.shared.keepLoggedIn()
NavigationHelper.shared.moveToHome(fromVC: self)
}
}
} catch { print(error.localizedDescription)}
}.resume()
Ok, this is what I have done for register. Now, I want to create a Helper, which will do the same thing with @escaping
as I we all need the parsed JSON
in return.
So, I am passing the endPoint
as String and then trying to pass this newUser which is a Encodable
, it can be a Decodable
as well in future, but it throws an error Cannot invoke 'encode' with an argument list of type '(Codable)'
. Can anyone please help? And, is it better this way, by calling this function multiple times when it comes to JSONParsing
?
Edit: - So, I am now using the networkRequestfunction
and here is what I have done.
let newData = User.init(name: "Rob", email: "abc@gmail.com", password: "12345678")
ApiHelper.sharedInstance.networkRequest_Post(urlString: "register", header: nil, encodingData: newData) { (response: User, urlRes, error) in
<#code#> }
Now, it gives me this error: Cannot convert value of type '(User, _, _) -> ()' to expected argument type '(_?, HTTPURLResponse?, Error?) -> ()'
. Any help?