Get Method JSON Data to show in Textfield not working (Error) - ios

How to get JSON data in textfield for GET method. My Json data is as follows,
SUCCESS: {"code":200,
"shop_detail":{"name":"dad","address":"556666","city":"cSC","area":"scsc","street":"vddva","building":"jhkj","description":null}
"shop_types":
[{"id":7,"name":"IT\/SOFTWARE","merchant_type":"office",}]}
My code with header and URL is
func getProfileAPI() {
let headers: HTTPHeaders = [
"Authorisation": AuthService.instance.tokenId ?? "",
"Content-Type": "application/json",
"Accept": "application/json"
]
print(headers)
let scriptUrl = "http://haitch.igenuz.com/api/merchant/profile"
if let url = URL(string: scriptUrl) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(AuthService.instance.tokenId ?? "", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest)
.responseString { response in
debugPrint(response)
print(response)
if let result = response.result.value // getting the json value from the server
{
}
}
After print response I am getting the values of JSON data printed, if I am having textfield like name.text, address.text. I want to show the values as I get through JSON response. If I try below code it fails in Dictionary.
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
let jsonData:NSDictionary = (data as? NSDictionary)!
print(jsonData)
}}

Try this,
struct Root: Codable {
let code: Int
let shopDetail: ShopDetail
let shopTypes: [ShopType]
}
struct ShopDetail: Codable {
let name, address, area, street, building, city: String
}
struct ShopType: Codable {
let name, merchantType: String
}
And Call
func getProfileAPI() {
let headers: HTTPHeaders = [
"Authorisation": AuthService.instance.tokenId ?? "",
"Content-Type": "application/json",
"Accept": "application/json"
]
print(headers)
let scriptUrl = "http://haitch.igenuz.com/api/merchant/profile"
if let url = URL(string: scriptUrl) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(AuthService.instance.tokenId ?? "", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest).response { response in
guard
let data = response.data,
let json = String(data: data, encoding: .utf8)
else { return }
print("json:", json)
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let root = try decoder.decode(Root.self, from: data)
print(root)
self.t1.text! = root.shopDetail.name
// self.t3.text! = root.shopDetail.description
print(root.shopDetail.name)
print(root.shopDetail.address)
for shop in root.shopTypes {
self.merchant_Type.text! = shop.merchantType
self.t2.text! = shop.name
print(shop.name)
print(shop.merchantType)
}
} catch {
print(error)
}
}}}

Related

Unable to post parameters in post request ios swift

I'm trying to send these parameters as a post request to the URL but the parameters are not getting sent. I don't know whether is URLSession configuration issue. Can anyone check and solve the issue?
import UIKit
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var str = String(data: jsonData!, encoding: .utf8)
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
Check with this:
func post method(){
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"]
let parameters = ["set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as! Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
}
guard let httpresponse = response as? HTTPURLResponse,
(200...299).contains(httpresponse.statusCode) else {
print ("server error")
return
}
if let mimeType = response?.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("got data: \(dataString)")
}
}
})
dataTask.resume()
}
I used an online service called RequestBin to inspect your request and data seem to be sent correctly. I only did minor modifications as already mentioned in the comment.
This was the resulting code:
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try! JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://requestbin.fullcontact.com/***")! // Was "using"
var request = URLRequest(url: url)
request.httpMethod = "POST" // Was "Post"
request.httpBody = jsonData // Was utf8 string representation
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
You can check inspected result using this service. You simply create a new URL and use it in your request. After you have successfully sent the request all you do is reload the page to inspect your request.
Note that these are "http" requests so you need to allow arbitrary loads.
You may set your request like following and change content type according to your need
import UIKit
let json: [String: Any]? = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let parameters = json
{
self.makeParamterString(request: request, parameterDic: parameters)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
static func makeParamterString(request:NSMutableURLRequest, parameterDic:[String:AnyObject])
{
let _ = NSCharacterSet(charactersIn:"=\"#%/<>?#\\^`{|}").inverted
var dataString = String()
for (key, value) in parameterDic {
dataString = (dataString as String) + ("&\(key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)=\(value)")
}
dataString = dataString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
request.httpBody = dataString.data(using: String.Encoding.utf8)
}

how to make post request with row http body using swift as postman request test?

request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let httpbody = object.data(using: String.Encoding.utf8)
request.httpBody = httpbody
You can directly generate a code from postman itself. Also, for your reference, you can call post request with row body as given below.
let headers = [
"content-type": "application/json",
"cache-control": "no-cache"
]
let parameters = ["order": ["line_items": [
["variant_id": 18055889387589,
"quantity": 1]
]]] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
if let data = postData {
let request = NSMutableURLRequest(url: NSURL(string: "http://")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error?.localizedDescription ?? "")
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse?.statusCode ?? 0)
let reponseData = String(data: data!, encoding: String.Encoding.utf8)
print("responseData: \(reponseData ?? "Blank Data")")
}
})
dataTask.resume()
}
Let me know if you have any query.
Thanks.

REST API's issue

I am working on REST API's in iOS application.
I have tested Server URL and Parameters of POST method.
It is returning with
Your browser sent a request that this server could not understand
this error in response.
For the GET request API is working fine.
If anyone faced the same issue please let me know.
Thank you.
Please check my web service model
let configuration = URLSessionConfiguration.default;
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
var urlString = String()
urlString.append(Constant.BASE_URL)
urlString.append(methodName)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let serverUrl: URL = URL(string: (encodedUrl?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!)!
var request : URLRequest = URLRequest(url: serverUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
var paramStr : String = String()
if requestDict.count > 0 {
let keysArray = requestDict.keys
for key in keysArray {
if paramStr.isEmpty{
paramStr.append("\(key)=\(requestDict[key]! as! String)")
}else{
paramStr.append("&\(key)=\(requestDict[key]! as! String)")
}
}
}
let postData:Data = try! JSONSerialization.data(withJSONObject: requestDict)//paramStr.data(using: .utf8)!
let reqJSONStr = String(data: postData, encoding: .utf8)
let postLength = "\(postData.count)"
request.httpMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
//request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
//request.httpBody = reqJSONStr?.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: requestDict)
if headerValue != nil{
let allkeys = headerValue.keys
for key in allkeys {
request.setValue(headerValue[key] as! String?, forHTTPHeaderField: key)
}
}
let postDataTask : URLSessionDataTask = session.dataTask(with: request, completionHandler:
{
data, response, error in
if data != nil && error == nil{
let res = String(data: data!, encoding: .utf8)
let dict = convertToDictionary(text: res!)
if let httpResponse = response as? HTTPURLResponse {
//print("error \(httpResponse.statusCode)")
if httpResponse.statusCode == 200
{
DispatchQueue.main.async {
successBlock (response!,(dict)!)
}
}
else
{
if (error?.localizedDescription) != nil
{
errorBlock((error?.localizedDescription)! as String)
}
else
{
errorBlock("")
}
}
}
else
{
errorBlock((error?.localizedDescription)! as String)
}
}
else{
if let httpResponse = error as? HTTPURLResponse {
//print("error \(httpResponse.statusCode)")
}
errorBlock((error?.localizedDescription)! as String)
}
})
postDataTask.resume()
Assuming that your backend is expecting an form-urlencoded request, then you should convert your parameters dictionary in an string url encoded
This is an example
let parameters : [String:Any] = ["ajax":1,"test":"abuela"]
var queryItems : [URLQueryItem] = []
for key in parameters.keys {
if let value = parameters[key] as? String {
queryItems.append(URLQueryItem(name: key, value: value))
}else{
queryItems.append(URLQueryItem(name: key, value: String(describing:parameters[key]!)))
}
}
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems
then if you
print(urlComponents.percentEncodedQuery!)
you will get
test=abuela&ajax=1
then with this you need to add in your urlString
urlString.append("&" + urlComponents.percentEncodedQuery!)
FULL CODE
let configuration = URLSessionConfiguration.default;
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
var urlString = String()
urlString.append(Constant.BASE_URL)
urlString.append(methodName)
var queryItems : [URLQueryItem] = []
for key in parameters.keys {
if let value = parameters[key] as? String {
queryItems.append(URLQueryItem(name: key, value: value))
}else{
queryItems.append(URLQueryItem(name: key, value: String(describing:parameters[key]!)))
}
}
var urlComponents = URLComponents()
urlComponents.queryItems = queryItems
print(urlComponents.percentEncodedQuery!)
urlString.append("&" + urlComponents.percentEncodedQuery!)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let serverUrl: URL = URL(string: urlString)!
var request : URLRequest = URLRequest(url: serverUrl, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let postDataTask : URLSessionDataTask = session.dataTask(with: request, completionHandler:
{
data, response, error in
if data != nil && error == nil{
let res = String(data: data!, encoding: .utf8)
let dict = convertToDictionary(text: res!)
if let httpResponse = response as? HTTPURLResponse {
//print("error \(httpResponse.statusCode)")
if httpResponse.statusCode == 200
{
DispatchQueue.main.async {
successBlock (response!,(dict)!)
}
}
else
{
if (error?.localizedDescription) != nil
{
errorBlock((error?.localizedDescription)! as String)
}
else
{
errorBlock("")
}
}
}
else
{
errorBlock((error?.localizedDescription)! as String)
}
}
else{
if let httpResponse = error as? HTTPURLResponse {
//print("error \(httpResponse.statusCode)")
}
errorBlock((error?.localizedDescription)! as String)
}
})
postDataTask.resume()
IF your backend is waiting application/json http body encoded
You are passing an JSON object in the httpBody but your contentType header is wrong instead of "application/x-www-form-urlencoded" should be "application/json", I think your json convertion is wrong try using your requestDict directly and JSONSerialization will convert the dictionary in a valid JSON object that you can use in your request.httpBody
replace
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
by
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Use this to convert to JSON your requestDict parameters dictionary
request.httpBody = try! JSONSerialization.data(withJSONObject: requestDict)

How to send array of dictionarys of JSON in SWIFT - (POST method)

I want to know how I can send more than one array of dictionary in JSON. I have to do POST in this format :
{
"Account":
{
"lastname":"VVV",
"PersonEmail":"vaaaay#gmail.com"
},
"Member":
{
"Password__C":"12345"
},
"ProgramName":"My Chili's"
}
This is what I have done so far:
lname = lastName.text!
fname = firstName.text!
email = emailSignUp.text!
pass = passwordSignup.text!
let signUpDict : [String:Any] =
[
"Account": [
"lastname": lname!,
"PersonEmail": email!
],
"Member": [
"Password__C": pass!
],
"ProgramName": "My Chilli's"
]
var urlRequest = URLRequest(url: URL(string: url)!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json;application/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
do{
let postData = try? JSONSerialization.data(withJSONObject: signUpDict, options: JSONSerialization.WritingOptions.prettyPrinted)
urlRequest.httpBody = postData
}
catch {
print("Couldnt post this")
}
let task = URLSession.shared.dataTask(with:urlRequest as URLRequest){(data,response,error) in
if error != nil{
print("Error is \(error)")
return
}
print("Data Responded : \(data)")
print("response is: \(response)")
}
task.resume()
I am getting a 500 error in response.
{ status code: 500, headers {
"Cache-Control" = "s-maxage=0";
"Content-Security-Policy" = "referrer origin-when-cross-origin";
"Content-Type" = "application/json;charset=UTF-8";
Date = "Tue, 01 Aug 2017 12:19:44 GMT";
"Transfer-Encoding" = Identity;
"X-XSS-Protection" = "1; mode=block";
} })
I think the way I have written the signUpDict could be incorrect or missing something, could someone please guide me through this?
Edit:
As requested I tried the json on POSTMAN, however this is my first time using POSTMAN(complete newbie). So I am not sure if I did it right.
POSTMAN screenshot
Please Try to use this updated code
lname = lastName.text!
fname = firstName.text!
email = emailSignUp.text!
pass = passwordSignup.text!
let signUpDict : [String:Any] =
[
"Account": [
"lastname": lname!,
"PersonEmail": email!
],
"Member": [
"Password__C": pass!
],
"ProgramName": "My Chilli's"
]
let data = try! JSONSerialization.data(withJSONObject: signUpDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
let jsonData = json!.data(using: String.Encoding.utf8.rawValue);
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Replace following line :
From
urlRequest.setValue("application/json;application/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
To
urlRequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
Try This:-
lname = lastName.text!
fname = firstName.text!
email = emailSignUp.text!
pass = passwordSignup.text!
let accountDict = NSMutableDictionary.init()
let memberDict = NSMutableDictionary.init()
let finalDict = NSMutableDictionary.init()
accountDict.setValue(lname, forKey: "lastname")
accountDict.setValue(email, forKey: "PersonEmail")
memberDict.setValue(pass, forKey: "Password__C")
finalDict.setValue(accountDict, forKey: "Account")
finalDict.setValue(memberDict, forKey: "Member")
finalDict.setValue("My Chili's", forKey: "ProgramName")
print(finalDict)
let data = try! JSONSerialization.data(withJSONObject: finalDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
let jsonData = json!.data(using: String.Encoding.utf8.rawValue);
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData

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

Resources