Getting field values of Json Object from HTTP response [duplicate] - ios

This question already has answers here:
How to convert a JSON string to a dictionary?
(10 answers)
iOS - Parsing JSON Dictionary with NSJSONSerialization in Swift
(1 answer)
Closed 6 years ago.
i am developing an iOS app in Swift using Xcode. How can I get values of Json object from this HTTP response.I need values of inner message and status.
{"message":"success","statusCode":200,"data":{"message":"already logged in","status":0}}
Thank you in advance :)

First, let me recommend the best 3rd party API for REST calls (HTTP) which called Alamofire.
If you use the below Alamofire example:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// Parsing the JSON
if let JSON = response.result.value {
print("JSON: \(JSON)")
// The actual cast to Dictionary
let jsonDictionary = JSON as! Dictionary<String, AnyObject>
}
}
Basically jsonDictionary will be your JSON dictionary that the keys are String and the values are of type AnyObject (so you could cast to what ever you need) and now you can do the below calls:
let message = json["message"] as? String

Get that dictionary and
let objDict = yourResponseObject.valueForKey("Data") as! NSDictionary
if objDict.valueforkey("message").isequaltoString("already logged in")
{
User logged already
}
else
{
not logged
}

Related

Don't want to sort parameter in sort sequence alamofire

Here is my request of my api
http://xxxxxxxxxxxxxx/Service/GetEntry.aspx?FromDate=01/08/2018&RID=1&ToDate=25/10/2018&TokenID=1e731b96-4261-453b-848c-5b1a0d44f808
But my original request is like
http://xxxxxxxxxxxxx/Service1/GetEntry.aspx?TokenID=5edc678f-82ee-4cf8-956e-5f1d3798dfec&RID=1&FromDate=01%2F08%2F2018&ToDate=25%2F10%2F2018
Here are my request param and api call
var param = [String:Any]()
param["TokenID"] = tokenId
param["RID"] = Rid
param["FromDate"] = DateUtilities.convertStringfromDate(date: DateUtilities.getDateofMonthStartOfLast2Month())
param["ToDate"] = DateUtilities.convertStringfromDate(date: Date())
print(param)
// Network request
Alamofire.request(finalURL, method: .post, parameters: param, encoding: URLEncoding.queryString, headers: headers).responseJSON { (response: DataResponse<Any>) in
// check result is success
guard response.result.isSuccess else {
failure((response.result.error?.localizedDescription)!,"100")
return
}
if let arrResponse = response.result.value as? [[String: Any]]{
// get status code
if arrResponse[0]["Status"] as? String ?? "" == "Error"{
let statusCode = arrResponse[0][Constants.ResponseKey.code] as? String ?? "0"
if statusCode == "8"{
//Call logout api
ApplicationData.sharedInstance.logoutUser()
return
}
// get status message
let message = arrResponse[0][Constants.ResponseKey.message] as? String ?? ""
failure(message,statusCode)
return
}
success(arrResponse, "")
return
}
}
But due to sequence mismatch I do not get as per desired response, I am getting error in api response.Here I think it is problem of alamofire which taking parameters in sorting into querystring. How can I avoid sorting in request?
Please help me with it.
Apparently this is a closed issue on Alamofire already Follow this link.
Unfortunately Swift's dictionaries aren't order preserving, so there's
no way to currently accomplish this.
Alamofire currently encodes URL parameters in alphabetical order, but
there's no way to preserve an arbitrary ordering in the dictionary. So
unless the order is want is a sort of some kind, or the arbitrary
ordering of the dictionary.

Swift - Server response "unsupported_grant_type"

I'm trying to login using alamofire.
im using the following code:
let parameters = [
"username": "2gggggjggg",
"password": "2ubgh",
]
Alamofire.request(.POST, URL , parameters: parameters, encoding: .JSON).responseJSON { response in
print("request")
print(response.request) // original URL request
print("response")
print(response.response) // URL response
print("data")
print(response.data) // server data
print("result")
print(response.result) // result of response serialization
print("JSON")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
if let myData = response.data?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) {
SignUpVC.clientID = myData
print(myData)
}
}
the server response as follows:
data
Optional(<7b226572 726f7222 3a202275 6e737570 706f7274 65645f67 72616e74 5f747970 65227d>)
result
SUCCESS
JSON
JSON: {
error = "unsupported_grant_type";
}
what might the reason be? am i missing anything?
im new to implementing apps that connects to a server.
as far as i know the server uses Django with REST framework and oAuth2.
i hope to get enough help about it. I've tried to search a lot about this problem and how to resolve it but no luck.
thanks in advance.
Debugging check list
Did you use https in your url?
Did your server have Server Certificate from Certification authority Note iOS 9 will not connected to self sign
Certificate)?
Do you use object maper like "SwiftyJSON" object Model to json
not from the error massage I think you have to check your post url or you Server Certificate
let URL:String ="https://youURLHere"

IOS Swift Alamofire JSON Request

I am trying to make a JSON Request with Alamofire but the response is in Greek and Swift returns:
Response
{
id = 4;
name = "\U0395\U03bb\U03b1\U03b9\U03cc\U03bb\U03b1\U03b4\U03bf"
url = "http://www.gaiaskarpos.com/app/images/categories/olive.png";
}
The problem is at name field.
//Swift Alamofire Request
Alamofire.request(.GET, "http://gaiaskarpos.com/applegetCategores.php",
encoding:.JSON).validate().responseJSON{(response)->
Void in print("Response Json : \(response.result.value)")
I had a same issue in Arabic/Persian chars and It's my solution:
json variable :
{
message = "\U062f\U0633\U062a\U06af\U0627\U0647 \U0645\U0639\U062a\U0628\U0631 \U0646\U06cc\U0633\U062a";
status = 0;
}
So I casted json to [String: AnyObject] :
var test = json as? [String : AnyObject]
print(test)
It's fixed. You should give it a try.
Why is your encoding .JSON? You send .GET-request and you don't need to specify the type of encoding in your request.
Alamofire documentation say:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So use it. Links -> http://cocoadocs.org/docsets/Alamofire/1.1.3/ and https://github.com/Alamofire/Alamofire
You must specify the type of encoding when you pass parameters in the body of your request. It is for .POST and .PUT requests.
Try to print 'name' to Debug area. Maybe you'll get name in normal encoding... Xcode has the disadvantage: it shows not-UTF8 data in response like '\U0395\U03bb ... ... ... \U03b1\U03b9\' when there is some level of nested data in response.
Try to use NSUTF8StringEncoding with alamofire response
encoding: NSUTF8StringEncoding
Try to serialize the JSON with below code this might help you
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]

How can I process multiple links of JSON data?

The code works perfectly. The problem is that, after trying for a while, I cannot figure out how to make my program process a second link of different JSON data.
Here is my viewDidLoad where everything goes on:
override func viewDidLoad() {
super.viewDidLoad()
var err: NSError?
let urlPath: String = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" + searchFieldDataPassed + "?api_key=(removed my private api key for obvious reasons"
var url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { data, response, error in
// cast response as NSHTTPURLResponse and switch on statusCode if you like
if let httpResponse = response as? NSHTTPURLResponse { switch httpResponse.statusCode { case 200..<300: println("OK") default: println("Not OK") } }
// parse JSON using NSJSONSerialization if you've got data
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary,
let include = jsonResult.objectForKey(self.searchFieldDataPassed) as? NSDictionary {
if let summLevel = include[ "summonerLevel" ] as? NSNumber {
dispatch_async(dispatch_get_main_queue()) {
self.summonerLevel.text = "\(summLevel.integerValue)"
println("summoner level: \(summLevel.integerValue)")
}
}
if let profIconId = include[ "profileIconId" ] as? NSNumber {
dispatch_async(dispatch_get_main_queue()) {
self.profileIconId.text = "\(profIconId.integerValue)"
println("profile icon id: \(profIconId.integerValue)")
}
}
if let idNum = include [ "id" ] as? NSNumber {
dispatch_async(dispatch_get_main_queue()) {
self.idNumber = idNum
println("id number: \(self.idNumber)")
}
}
}
// spawn off another network call here if you like
}
task.resume()
}
That is from my secondViewController where all the processing goes on for JSON and then is displayed.
Here is the JSON data that I'm processing (for the first JSON parsing):
{"soon2challenger":{"id":43993167,"name":"soon2challenger","profileIconId":844,"summonerLevel":30,"revisionDate":1435549418000}}
All of that works fine, now, I want to process this JSON data which actually takes the id from the first parsed JSON data and uses it in the link to process more data, which I would like to output, part of it, to the screen.
Second JSON data:
{"summonerId":43993167,"playerStatSummaries":[{"playerStatSummaryType":"AramUnranked5x5","wins":25,"modifyDate":1423007927000,"aggregatedStats":{"totalChampionKills":676,"totalTurretsKilled":20,"totalAssists":991}},{"playerStatSummaryType":"CAP5x5","wins":15,"modifyDate":1429065922000,"aggregatedStats":{"totalChampionKills":312,"totalMinionKills":4885,"totalTurretsKilled":31,"totalNeutralMinionsKilled":511,"totalAssists":216}},{"playerStatSummaryType":"CoopVsAI","wins":28,"modifyDate":1421882181000,"aggregatedStats":{"totalChampionKills":266,"totalMinionKills":2802,"totalTurretsKilled":50,"totalNeutralMinionsKilled":385,"totalAssists":164,"maxChampionsKilled":0,"averageNodeCapture":0,"averageNodeNeutralize":0,"averageTeamObjective":0,"averageTotalPlayerScore":49,"averageCombatPlayerScore":0,"averageObjectivePlayerScore":49,"averageNodeCaptureAssist":0,"averageNodeNeutralizeAssist":0,"maxNodeCapture":0,"maxNodeNeutralize":0,"maxTeamObjective":0,"maxTotalPlayerScore":49,"maxCombatPlayerScore":0,"maxObjectivePlayerScore":49,"maxNodeCaptureAssist":0,"maxNodeNeutralizeAssist":0,"totalNodeNeutralize":0,"totalNodeCapture":0,"averageChampionsKilled":0,"averageNumDeaths":0,"averageAssists":0,"maxAssists":0}},{"playerStatSummaryType":"CoopVsAI3x3","wins":15,"modifyDate":1421882181000,"aggregatedStats":{"totalChampionKills":140,"totalMinionKills":1114,"totalTurretsKilled":9,"totalNeutralMinionsKilled":449,"totalAssists":91}},{"playerStatSummaryType":"OdinUnranked","wins":1,"modifyDate":1421882181000,"aggregatedStats":{"totalChampionKills":31,"totalAssists":45,"maxChampionsKilled":10,"averageNodeCapture":4,"averageNodeNeutralize":4,"averageTeamObjective":0,"averageTotalPlayerScore":843,"averageCombatPlayerScore":268,"averageObjectivePlayerScore":575,"averageNodeCaptureAssist":3,"averageNodeNeutralizeAssist":1,"maxNodeCapture":6,"maxNodeNeutralize":7,"maxTeamObjective":2,"maxTotalPlayerScore":1468,"maxCombatPlayerScore":529,"maxObjectivePlayerScore":939,"maxNodeCaptureAssist":5,"maxNodeNeutralizeAssist":2,"totalNodeNeutralize":22,"totalNodeCapture":25,"averageChampionsKilled":5,"averageNumDeaths":5,"averageAssists":8,"maxAssists":19}},{"playerStatSummaryType":"RankedSolo5x5","wins":116,"losses":120,"modifyDate":1433630047000,"aggregatedStats":{"totalChampionKills":1699,"totalMinionKills":33431,"totalTurretsKilled":219,"totalNeutralMinionsKilled":6501,"totalAssists":1969}},{"playerStatSummaryType":"RankedTeam3x3","wins":0,"losses":0,"modifyDate":1377726216000,"aggregatedStats":{}},{"playerStatSummaryType":"RankedTeam5x5","wins":3,"losses":0,"modifyDate":1383784473000,"aggregatedStats":{"totalChampionKills":28,"totalMinionKills":636,"totalTurretsKilled":6,"totalNeutralMinionsKilled":101,"totalAssists":41}},{"playerStatSummaryType":"Unranked3x3","wins":9,"modifyDate":1421882181000,"aggregatedStats":{"totalChampionKills":90,"totalMinionKills":1427,"totalTurretsKilled":11,"totalNeutralMinionsKilled":428,"totalAssists":105}},{"playerStatSummaryType":"URF","wins":4,"modifyDate":1435024847000,"aggregatedStats":{"totalChampionKills":68,"totalMinionKills":642,"totalTurretsKilled":14,"totalNeutralMinionsKilled":182,"totalAssists":55}},{"playerStatSummaryType":"Unranked","wins":566,"modifyDate":1435549418000,"aggregatedStats":{"totalChampionKills":8419,"totalMinionKills":128213,"totalTurretsKilled":960,"totalNeutralMinionsKilled":26117,"totalAssists":7812}}]}
Heres the link of the second JSON data I want to parse (just adding it, could be useful, but not sure):
https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/43993167/summary?season=SEASON2015&api_key=(took-out-my-private-api-key-for-obvious-reasons)
The link doesn't work because I have to keep my api key private to myself, but the JSON data that it displays is right above the link, which is the what it would result if you were to use the link with the api key.
Just to restate, I would like to process the second part (above of this) of JSON data, but I do not understand how to process multiple links of JSON. I have the first JSON data parsed, but am unable to parse the second JSON data.
I believe Apple is deprecating NSURLConnection. Take a look at NSURLSession. Using it, you can pass in a completion block that takes three arguments: NSData?, NSURLResponse?, and NSError?. The data object contains the JSON you can pass into the JSON serializer. After that, if you need to make another network call, just call it from inside the completion block with another NSURLSession data task. Alamofire is a great framework, but sometimes you don't need everything it provides, and it adds complexity into your app that if something goes wrong or doesn't behave the way you intend/understand, you may not fully understand why. If you want to keep it simple and under your control, use NSURLSession.
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { data, response, error in
// cast response as NSHTTPURLResponse and switch on statusCode if you like
// parse JSON using NSJSONSerialization if you've got data
// spawn off another network call here if you like
}
task.resume() // or in Swift 2, task?.resume()
First, i would totally prefer using some common frameworks for http requests - expecially if youre new in swift. For example here with alamofire.
https://github.com/Alamofire/Alamofire
There is also a version with integrated SwiftyJSON, so you are able to parse JSON Responses very easily.
https://github.com/SwiftyJSON/Alamofire-SwiftyJSON
So if you want to make a request, use this:
Alamofire.request(.GET, "http://httpbin.org/get")
.responseJSON { (_, _, json, _) in
var json = JSON(json)
// get the id out (depends on your structure of JSON):
let id = json["id"].int
}
Now you are able to perform a second Request (with the same Code) - Read the Documentation, how to make different Requests (like with POST) and add Parameters.
If you want to use Segues, so you want to load more data from the ID in another ViewController, you can use Segues to push the data to a second ViewController, and Load the new Content from JSON when the new ViewController is initialised.
Check out this how to send data through segues:
Sending data with Segue with Swift

Handle a JSON Response with Alamofire in Swift

I have a problem I want to handle a JSON Response with Alamofire in Swift
So I found this answer on Stackoverflow unfortunately this post is a few days older.
My question is how can I receive the data from Alamofire on first button press (without swiftyJSON).
I hope someone could help me.
This is the link I found on Stackoverflow.
Handle JSON Response with Alamofire in Swift
this is a small example.
This is what the JSON returns if it fails json_file.json
{ "transaction":"error" }
This is what the JSON returns if its success json_file.json
{ "transaction":"success" }
this is the code , you must add your own URL that will return any of those json responses. (example only)
Alamofire.request(.GET, "http://myjsonexamplewebsite.com/json_file.json", parameters:nil)
.responseJSON { (_, _, JSON, _) in
//println(JSON)
var response = JSON as NSDictionary
var transaction = response.objectForKey("transaction") as String
if transaction == "success" {
NSLog("JSON response was successfull")
}
else {
NSLog("JSON response had an Error")
}
}

Resources