i know this is very basic question that i am gonna ask but i need to ask how can i access data which is dictionary that is getting from server.
here is my response
JSON: {
message = "The email must be a valid email address.";}
now i want to do "po" in console log so what to write after in po statement
Thanks
All you need type
po yourResponseAsDictionary["message"]
UPDATED
Sorry I was thinking you already converted it.
If you are not using anything like SwiftyJSON or ObjectMapper to parse your json data then you can do just the following.
But I would recommend to use some lib to convert response directly to your model
let yourResponseFromNetwork = "{ \"country_code\" : \"+9\", \"user_id\" : 123456}"
if let data = yourResponseFromNetwork.data(using: String.Encoding.utf8) {
do {
if let dic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
let countryCode = dic["country_code"]
let userId = dic["user_id"]
}
} catch {
print("Error occurred")
}
}
Related
JSONSerialization didn't serialise data as server send. It reverses turn the data. I use data filter API from backend. its send the accurate data, I've also checked in postman and android side but iOS code changes the response.
do {
if let json = try JSONSerialization.jsonObject(with: usableData, options: .mutableLeaves) as? [String: Any] {
}
} catch let error {
OperationQueue.main.addOperation() {
SVProgressHUD.dismiss()
}
}
But if i convert the data into string then its shows correct. WHY?
var jsonString : String?
jsonString = String.init(data: data, encoding: String.Encoding.utf8)
Finally, I've got the solution. Server sends the data more than 100 keys in dictionary which is incorrect form, with this format our json serialisation could not able to serialised the data as we got from server.so we have decided to change the structure from dictionary to Array.
Incorrect form
1025{
id:1025
name:xyz
area:23123
}
1026{
id:1026
name:xyz
area:23123
}
1027{
id:1027
name:xyz
area:23123
}
Correct Form
[
id:1025
name:xyz
area:23123
,
id:1026
name:xyz
area:23123
,
id:1027
name:xyz
area:23123
]
I used to build my app on Firebase before and there was a method which listens for value updates, something like this:
refHandle = postRef.observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let postDict = snapshot.value as! [String : AnyObject]
// ...
})
Now I'm not using firebase anymore, I'm using deployd and I use Alamofire to retrieve data in JSON. I wonder if there is an event listener in Alamofire that can execute code if the value is changing in the database, instead of retrieving the value every 2 minutes.
Thanks.
Okay so I found this thing called TRVSEventSource which is meant for handling SSE events.
So I added the following code after adding the header files and bridging them like this:
let configs = NSURLSessionConfiguration.defaultSessionConfiguration()
configs.HTTPAdditionalHeaders = ["Accept" : "text/event-stream"]
let eventsource = TRVSEventSource(URL: NSURL(string: "https://app.firebaseio.com/about.json?auth=<Your Database Secret>"), sessionConfiguration: configs)
eventsource.delegate = self
eventsource.open()
After that using the TRVSEventSourceDelegate, I added this delegate to get the information:
func eventSource(eventSource: TRVSEventSource!, didReceiveEvent event: TRVSServerSentEvent!) {
do{
let data = try NSJSONSerialization.JSONObjectWithData(event.data, options: .MutableContainers)
print(data)
}
catch let error
{
print(error)
}
}
The following prints something like this {
data = {
desc = "My Data";
};
path = "/";
}
And with that also tells you within what path of the JSOn file has been edited or added, idk how to handle things separately and stuff but I think you can handle the rest XD. Not a good answer but I hope I helped XD (First time properly answering something)
I want to use JSON data in my app. So I am using this webservice calling method to convert my json data to an array.
func getData(path: String, completion: (dataArray: NSArray)->()) {
let semaphore = dispatch_semaphore_create(0)
// var datalistArray = NSArray()
let baseUrl = NSBundle.mainBundle().infoDictionary!["BaseURL"] as! String
let fullUrl = "\(baseUrl)\(path)"
print("FULL URL-----HTTPClient \(fullUrl)")
guard let endpoint = NSURL(string:fullUrl) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL: endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request,completionHandler: {(data,response,error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSArray else {//NSJSONReadingOptions.AllowFragments
throw JSONError.ConversionFailed
}
print(json)
if let data_list:NSArray = json {
completion(dataArray: data_list)
dispatch_semaphore_signal(semaphore);
}
}catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}) .resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
But now my service sending json data within xml tags like <string xmlns="http://tempuri.org/">json data</string so I am getting an exception when I try to convert my json data. The exception is this.
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
What should I change in my code to remove those tags before sending to json parser?
Please help me.
Thanks
I think your response that you get from server is in xml format not in json. If it is in xml format then you must do xml parsing instead of json parsing.
NSJSONSerialization.JSONObjectWithData is json parsing that give json object from data (data in json format).
But if you getting response in xml format from server then you should use NSXMLParser to parse the data.
If you don't have much idea about it then you can refer tutorial like
XML Parsing using NSXMLParse in Swift by The appguruz or can use third party libraries.
I have real big problem finding the right code which helps me to parse String to JSON and then send to external server. I'm using xCode 6.1, so some ways of parsing won't work for me, like SwiftyJSON.
On internet i only can find the way to send String , but not JSON, or if i found something it won't work.
I'm beginner in iOS and it would really help me if someone can explain me how to do it.
Thank you a lot.
If you have JSON String convert to NSData object.Check the data object before sending to an external server if data is valid JSON format or not by using NSJSONSerialization.I am giving sample code to how can check JSON Data valid or not.
suppose you String is like this,
let jsonString = "{\"device\":\"iPhone 6\",\"OS\":\"iOS 9\",\"name\":\"Apple\"}"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
do {
let responseData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if responseData != nil { // valid JSON
//Now pass data object to server
}
} catch {
NSLog("ERROR when parse JSON")
}
Im using Alamofire to pull a JSON file from a server (http://midlandgates.co.uk/JSON/reliveCacheData.json). To do this I have an Alamofire Request function which should pull the data down and write it to a class called JSONDataClass.
Alamofire Request
Alamofire.request(.GET, "http://midlandgates.co.uk/JSON/reliveCacheData.json")
.response { request, response, data, error in
if let data = data {
let json = JSON(data:data)
for locationData in json {
let locationDataJSON = JSONDataClass(json: locationData.1)
self.cacheData.append(locationDataJSON)
}
for title in self.cacheData {
print(title.memoryTitle)
}
}
}
However my printLn isn't printing the data from the JSON File which indicates there is a problem with either the request or the class. However I'm new to swift and can't seem to work out the problem, all help is appreciated!
Class
import Foundation
import CoreLocation
import SwiftyJSON
class JSONDataClass {
//Location MetaData
var postUser: String!
var memoryTitle: String!
var memoryDescription: String!
var memoryType: String!
var memoryEmotion: String!
var taggedFriends: String!
//Location LocationalData
var memoryLocation: CLLocationCoordinate2D
//MultiMedia AddressData
var media1: String!
var media2: String!
var media3: String!
var media4: String!
var media5: String!
//Writing to varibles
init(json: JSON) {
postUser = json["user"].stringValue
memoryTitle = json["title"].stringValue
memoryDescription = json["description"].stringValue
memoryType = json["type"].stringValue
memoryEmotion = json["emotion"].stringValue
taggedFriends = json["friends"].stringValue
memoryLocation = CLLocationCoordinate2D(latitude: json["latitude"].doubleValue, longitude: json["longitude"].doubleValue)
media1 = json["media1"].stringValue
media2 = json["media2"].stringValue
media3 = json["media3"].stringValue
media4 = json["media4"].stringValue
media5 = json["media5"].stringValue
}
}
(Note: the author of the JSON content has fixed his JSON based on my answer - my answer was correct at the time of this post).
The problem is that you've got invalid JSON coming back from the server.
I switched your SwiftyJSON code out and wrapped it in a try-catch which illuminated the problem:
Alamofire.request(.GET, "http://midlandgates.co.uk/JSON/reliveCacheData.json")
.response { request, response, data, error in
//print("status \(response)")
do {
let myData = try NSJSONSerialization.JSONObjectWithData(data!,
options: .MutableLeaves)
print(myData)
} catch let error {
print(error)
}
}
And I get the following error:
2015-12-30 13:47:06.129 {{ignore}}[10185:2174510] Unknown class log in Interface Builder file.
Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 961."
UserInfo={NSDebugDescription=Unescaped control character around
character 961.}
This error basically means that you have invalid JSON coming back from the server.
Make sure your json is valid by running it through JSONLint:
http://jsonlint.com
Are you new to debuggers and breakpoints?
Set a breakpoint in your response closure (for example, in your if let data = data { line) and step through your code to see if it does what you expect at every stage. Maybe error is set? Maybe the if let data = data { conditional failed (you're not doing anything in an else to log the failure, so how could you know?)...
After I checked the discussion and the data provided by the server from you link, I can say, that your trouble is how to deal with your JSON (class, or struct, or enum??)
Did you follow some tutorial from SwiftyJSON? While your init(json: JSON) in class JSONDataClass seems to accept some JSON object (aka dictionary), in reality your json is an JSON array! Check SwiftyJSON documentation and take in your account, that you received an array.
try this instead:
for d in json {
let locationDataJSON = JSONDataClass(json: d)
self.cacheData.append(locationDataJSON)
}
and see, that locationDataJSON is NOT location data but one json object from the received array. or just remove .1 in locationData.1
For example:
Alamofire.request(.GET, "http://midlandgates.co.uk/JSON/reliveCacheData.json")
.response { request, response, data, error in
if let data = data {
let json = JSON(data:data)
for locationData in json {
let locationDataJSON = JSONDataClass(json: locationData)
self.cacheData.append(locationDataJSON)
}
for title in self.cacheData {
print(title.memoryTitle)
}
}
}