How to parse the following JSON in swift ? It has SUCCESS: flag - ios

I am using Alamofire to get DataResponse value for a GET request. But I am getting following JSON which I am unable to understand why
SUCCESS: {
data = (
{
"alt_text" = " ....
}
);
meta = {
};
links = {
};
}
I am unable to understand this JSON format

The snippet your posted is not the JSON you want from alamofire, the SUCCESS is just telling you that the request is successful, and you get your actual data by unwrapping it.
I assume the snippet you posted is your response, here's an example:
AF.request(url, method: .get, parameters: [])
.validate(statusCode: 200..<300)
.responseJSON() { response in
switch response.result {
case .success(let json):
guard let dictJson = json as? [String : Any],
let dataDict = dictJson["data"] as? [String : Any] else { return }
// Handle your json here
print(dataDict)
case .failure(let err):
// Your error handling goes here
}
}

Related

How to get key Value from post webservice API and fetch that to tableview

I got data from API in this format but the problem is that I want to get all questions and answers from the API but whenever I try to get the value by using the key value it returns nil value and application crashes
this is my api data looks like after getting into a dictionary
here's my code for getting data from API
Alamofire.request(url, method: .post, parameters: parameters,encoding: JSONEncoding.default, headers: header ).responseJSON {
response in
switch response.result {
case .success:
print(response)
if let result = response.result.value {
print(result)
let responseDict = result as! [String : Any]
print(responseDict)
let data = responseDict["Result"] as! [Any]
print(data)
}
break
case .failure(let error):
print(error)
}
}
You can try
if let res = responseDict["Result"] as? [[String:Any]] {
for item in res {
if let ques = item["Question"] as? String {
print(ques)
}
if let op = item["Options"] as? [[String:Any]] {
print(op)
}
}
}

Issue with parsing json using Alamofire

My JSON response in postman looks like this...
{
"success": 1,
"Details": {
"seller_id": "165",
"mobile_no": "9653265987",
"seller_name": "User A",
"seller_email_id": "user#gmail.com",
"company_name": "myCompany",
"category": "Cosmetics",
"otp": "1111"
},
"message": "Seller Already Registered!!!"
}
Now I wanted to give a condition based on whether success is 0 or 1 and so for that I wanted to extract success. Also I want to extract mobile number. But I am not able figure out how to do that.
This is how I am making my Alamofire post request...
Alamofire.request(url, method: .post, parameters: Parameters, encoding: URLEncoding.httpBody, headers: headers)
.responseString { (response) in
if let httpResponse = response.response {
print("error \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 {
//Do something
}
}
}
I did go through similar issues raised by other users...but couldn't find from them an exact solution for my issue...
Try this
Alamofire.request(url, method: .post, parameters: Parameters, encoding: URLEncoding.httpBody, headers: headers)
.responseJSON { (response) in
switch response.result{
case .success(_):
print("Success: \(response)")
let JsonResponse = response.result.value as? [String: Any]
if JsonResponse?["success"] as! Int == 1{
let dict = JsonResponse?["Details"] as! [String : Any]
let mobileNo = dict["mobile_no"] as! String
}
else{
print("Failed")
}
case .failure(let error):
print("Failed: \(error)")
}
}
There are a couple of issues:
Your parameters to request don't look quite right.
the parameters parameter doesn't look right: at best, it's very strange to have a Parameters variable (you should use lower case for variables; and this conflicts with an Alamofire type);
the encoding should be URLEncoding.default. Or, because URLEncoding.default is the default value, you can omit this altogether.
If you want to check for status code, let validate do that for you.
If you're expecting JSON in response, use reponseJSON instead of responseString.
Use if let or guard let with as? to safely unwrap optionals. Do not use as! (unless you are 100% sure that it never could fail ... and when dealing with responses from a remote server, you can never be 100% confident).
Thus:
func performRequest(url: String, parameters: [String: String]?, headers: [String: String]?) {
Alamofire.request(url, method: .post, parameters: parameters, headers: headers)
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
switch response.result {
case .success(let value):
guard let dictionary = value as? [String: Any],
let success = dictionary["success"] as? Int else {
print("success not found")
return
}
guard success == 1 else {
print("web service reported failure")
return
}
guard let details = dictionary["Details"] as? [String: Any] else {
print("Did not find details")
return
}
guard let mobile = details["mobile_no"] as? String else {
print("mobile not found")
return
}
print(mobile)
case .failure(let error):
print("Failed: \(error)")
}
}
}
Or, in your comment below, if you want to goToSignUpScreen() if success was 0, then:
Alamofire.request(url, method: .post, parameters: parameters, headers: headers)
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
switch response.result {
case .success(let value):
guard let dictionary = value as? [String: Any],
let success = dictionary["success"] as? Int else {
print("success not found")
return
}
if success == 0 {
self.goToSignUpScreen()
}
case .failure(let error):
print("Failed: \(error)")
}
}

I have a url which posts some data to the server. How do i convert it to alamofire post request method with all parameters mentioned in URL

let url = "(InsertAsset)?customerID=(vmanagerappDelegate.cust_Id!)&assetTag=(self.txt_AssetTag.text! as String)&modelID=(modelObject)&statusID=(statusObject)&serial=(self.txt_Serial.text! as String)&assetName=(self.txt_AssetName.text! as String)&purchaseDate=(selectedPurchaseDate)&supplierID=(supplierObject)&purchaseCost=(purchaseCostObject)&warranty=(self.txt_Warranty.text! as String)&notes=(notesObject)&locationID=(locationObject)&ownerID=(ownerObject)&addUserID=(vmanagerappDelegate.userId as String)&saleEndDate=(self.txt_Sale_End_Date.text! as String)&softwareMaintainenceEndDate=(self.txt_Software_Maintainence_End_Date.text! as String)&supportEndDate=(self.txt_Support_End_Date.text! as String)&MacAddress=(self.txt_Mac_Address.text! as String)&sitekey=testing"
Hi you can create dictionary like following to send parameter as dictionary in Alamofire :
var dicParam = Dictionary<String,AnyObject>()
dicParam[“customerID”] = vmanagerappDelegate.cust_Id!
dicParam[“assetTag”] = self.txt_AssetTag.text! as String
dicParam["modelID"] = modelObject
In Alamofire pass above dictionary as parameters along with your URL like following :
Alamofire.request("Your URL", method: .post, parameters: dicParam, encoding: URLEncoding(destination: .queryString), headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
try creating a dicitonary
let params:Dictionary<String, AnyObject> = ["customerID":vmanagerappDelegate.cust_Id!,"assetTag":self.txt_AssetTag.text,"modelID":modelObject] //similarly add all params to Dict
if you want to add some headers create dicitonary Header for them too and pass in Alamofire.request(.POST,url,parameters: params,headers:Header,encoding: .JSON)
a example for post request
func remotePOSTServiceWithParameters(urlString : String , params : Dictionary<String, AnyObject> , callback:(data: Dictionary<String, AnyObject>?, error: NSError? ) -> Void) {
print("Request POST URL:\(urlString) PARAMS:\(params)")
Alamofire.request(.POST,urlString,parameters: params,encoding: .JSON)
.validate()
.responseJSON {
response in
guard response.result.error == nil else {
print("Error for POST :\(urlString):\(response.result.error!)")
//
callback(data: nil , error: response.result.error! )
return
}
if let value = response.result.value {
print("JSON: \(value)")
if let result = value as? Dictionary<String, AnyObject> {
print("Response for POST :\(urlString):\(value)")
callback(data:result , error: nil )
}
}
}
}

Alamofire 4 Swift 3 GET request with parameters

I'm building a network stack using Alamofire 4 and Swift 3. Following the Alamofire guidelines I've created a router for the endpoints of the services. I'm currently using the free API of OpenWeatherMap but I'm finding problems in order to create a get request.
That's the url needed: http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY. Pasted on a browser, and using a real API Key it works and gives me back my nice json full of info about the weather in the given location.
On my App I can insert the parameters as Dictionary but I cannot find a way to append the api key at the end of the url.
That's my enum router:
enum OWARouter: URLRequestConvertible {
case byCityName(parameters: Parameters)
// MARK: Url
static let baseURLString = "http://api.openweathermap.org"
static let apiKey = "MY_APY_KEY"
static let pathApiKey = "&APPID=\(apiKey)"
var method: HTTPMethod {
switch self {
case .byCityName:
return .get
}
}
var path: String {
switch self {
case .byCityName:
return "/data/2.5/weather"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try OWARouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
switch self {
case .byCityName(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
print((urlRequest.url)!)
}
urlRequest.httpMethod = method.rawValue
return urlRequest
}
}
When I log my (urlRequest.url)! I have this: http://api.openweathermap.org/data/2.5/weather?q=Rome but I cannot find a way to add the apiKey.
What am I doing wrong?
I've also made an ugly test adding this code after the print:
var urlRequest2 = URLRequest(url: (urlRequest.url)!.appendingPathComponent(OWARouter.pathApiKey))
print("URL2: \(urlRequest2)")
And the log is URL2: http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY?q=Rome
How come the api key is in the middle?
If you need this is the simple request code:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome"])).responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
print(response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
Another question...
If I use as parameters ["q":"Rome, IT"], my output url is: http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
How to keep the comma?
Thank you!
Swift - 5 Alamofire 5.0 Updated Code (just Change AF.request Method according to your requirement you can add Parameters headers and intercepter as well )
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
// handle your code
}
case .failure(let error):
print(error)
}
}
Used below lines of code:
func getRequestAPICall(parameters_name: String) {
let todosEndpoint: String = "your_server_url" + "parameterName=\(parameters_name)"
Alamofire.request(todosEndpoint, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response)
if let data = response.result.value{
// Response type-1
if (data as? [[String : AnyObject]]) != nil{
print("data_1: \(data)")
}
// Response type-2
if (data as? [String : AnyObject]) != nil{
print("data_2: \(data)")
}
}
}
}
func AlamofireGetCode()
{
var url:String!
url = "https://jsonplaceholder.typicode.com/comments"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(json)
self.mainarray = json as? NSArray
print(self.mainarray as Any)
self.mytableviewreload.reloadData()
}
case .failure(let error):
print(error)
}
}
}
I've found a solution... the Api Key is simply a parameter to send to the request. So the code to change is not in the router but in the request function:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome","APPID":"MY_API_KEY"])).responseJSON { response in
print(response.request)
//print(response.response)
//print(response.data)
//print(response.result)
//debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
EDIT: the comma issue do not gives me any problem now. Thank you.
Swift 5+
Use AF.request
let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
let request = AF.request(todosEndpoint)
request.responseJSON { (data) in
print("Response", data)
}
**//
Fist in third party liabrary, install pod 'Alamofire'
Using Alamofire get json data
import UIKit
import Alamofire
class APIWRAPPER: NSObject {
static let instance = APIWRAPPER()
func LoginAPI(Uname : String , Password : String) {
let requestString =
"http://************php/v1/sign-in"
let params = ["user_name": Uname,
"password": Password]
Alamofire.request(requestString,method: .get, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: [:]).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil
{
print("response : \(response.result.value!)")
}
else
{
print("Error")
}
break
case .failure(_):
print("Failure : \(response.result.error!)")
break
}
}
}
}

Alamofire Parameter missing in response

I install pod file of Alamofire for calling web service and successfully retrieve data when there is no parameter pass to web service but when I try to pass parameter It shows this parameter missing.
Here is my code:
let parameters: Parameters = ["client_id": "1","user_token":"A4YkkH5FdTbRCI8Mk98s"]
let url = "http://***********/index.php/Web_api/get_client_profile"
Alamofire.request(url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
RESPONSE:
{
"message : client_id parameter missing",
"Code : 500"
}
What I am doing wrong ? Please help me with it.
Thank you
After banging my head for like 6 Hours I figured a different approach, here is a way of calling it, which works:
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
}
}
func loadDataFromServer(message:String?) {
// Prerequisites for Connection to Server
let timeParameter = self.getLastTimeStamp()
let url = "http://your.amazing.url/path/component/classs"
let parameter = ["timestamp":timeParameter]
//sho hud only of there is no data listed
if message != nil {
HUD.show(HUDContentType.label("Loading.."))
}
self.request = Alamofire.request(url, method: .post, parameters:parameter)
if let request = request as? DataRequest {
request.responseString { response in
PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
//Save and Fetch
self.saveTimestamp(dictionary: dictionary, wsEntity: "Section")
self.saveDataInPersisanceStorage(articalDictionary: dictionary)
self.fetchDatafromCore()
//HUD.flash(.success, delay:1.0)
}catch{
//HUD.flash(.error, delay:1.0)
}
}
}
}

Resources