I have a variable content from a NSArray : let content = application["content"]!
When I print content, I have a String :
print(content) -> My content
But when I want to cast my variable to String : let content = application["content"]! as! String
I can't print my variable because it's null :
print(content) -> Could not cast value of type 'NSNull' (0x1a0507768) to 'NSString' (0x1a0511798).
Why ?
UPDATE :
My array when value is not casted :
{
"application_title" = "Marina Kaye";
"application_type" = discussions;
"application_type_name" = Discussions;
content = (
{
content = "Le nouvel album de Marina Kaye";
link = "?message_id=118";
},
{
content = "Son album est num\U00e9ro 1 des";
link = "?message_id=131";
},
{
content = "Le nouvel album s'appel";
link = "?message_id=126";
}
);
"content_title" = "Messages utiles";
"content_type" = "useful_messages";
}
My array when value is casted :
{
"application_title" = "Marina Kaye";
"application_type" = discussions;
"application_type_name" = Discussions;
content = "<null>";
"content_title" = "<null>";
"content_type" = "usefull_messages";
}
I can't cast content to NSArray and content_title to String.
MY CODE :
let applicationsArray = result["applications"]! as! NSArray
for application in applicationsArray {
let applicationTitle = application["application_title"]! as! String
let applicationType = application["application_type"]! as! String
let applicationTypeName = application["application_type_name"]! as! String
let content = application["content"]! as! NSArray
let contentTitle = application["content_title"]! as! String
let contentType = application["content_type"]! as! String
self.listApplications.append(Application(applicationTitle: applicationTitle, applicationType: applicationType, applicationTypeName: applicationTypeName, content: content, contentTitle: contentTitle, contentType: contentType))
}
As you are coding in Swift, you do not need the legacy NSArray and NSDictionary types. Instead, these are now Array and Dictionary, but you do not even have to care about that.
To declare an array, you usually specify the type in square brackets, such as [String]. For a dictionary, you need this for both key and value, separated by a colon, e.g. [String: AnyObject].
From your log output, you have a Dictionary of type [String: AnyObject] with 6 keys; all of them point to String objects, except the "content" one.
The "content" key apparently points to an array of dictionaries. This is written like this: [[String: AnyObject]]. Thus it is not surprising that casting this to String is not successful.
Here is how you can parse the application dictionary's "content":
if let content = application["content"] as? [[String: AnyObject]] {
for item in content {
let text = content["content"] as? String
let link = content["link"] as? String
// do something with this data
}
}
I would recommend defining a class or struct to capture the application object. Your code will be much clearer and easier to maintain.
Related
In this I am getting data from server response after posting parameters and here I need to display it on table view and it should be displayed like shown below in the image 0 is the price for the particular shipping method
already i had written model class for server response data and here it is
struct ShippingMethod {
let carrierCode : String
let priceInclTax : Int
let priceExclTax : Int
let available : Any
let carrierTitle : String
let baseAmount : Int
let methodTitle : String
let amount : Int
let methodCode : String
let errorMessage : Any
init(dict : [String:Any]) {
self.carrierCode = dict["carrier_code"] as! String
self.priceInclTax = dict["price_incl_tax"]! as! Int
self.priceExclTax = dict["price_excl_tax"]! as! Int
self.available = dict["available"]!
self.carrierTitle = dict["carrier_title"] as! String
self.baseAmount = dict["base_amount"]! as! Int
self.methodTitle = dict["method_title"]! as! String
self.amount = dict["amount"]! as! Int
self.methodCode = dict["method_code"] as! String
self.errorMessage = (dict["error_message"] != nil)
}
}
by using this I had formed an array type like this by using code
var finalDict = [String: [String]]()
var responseData = [ShippingMethod]()
do
{
let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]]
for item in array! {
self.responseData.append(ShippingMethod.init(dict: item))
}
print(self.responseData)
}
catch let error
{
print("json error:", error)
}
print(self.responseData)
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [String]()
}
self.finalDict[carrierTitle]!.append(methodTitle)
}
print(self.finalDict)
the output of this finalDict is ["Flat Rate": ["Fixed"], "Best Way": ["Table Rate"]] in this carrier title key value pair should be displayed as section title and is Flat Rate and method title key value pair should be displayed as rows in section Fixed but the problem is I need amount key value pair with it also for corresponding method title can anyone help me how to get this ?
Why don't you create another struct for displaying row data:
struct CarrierInfo {
let name:String
let amount:Int
}
Change your finalDict to
var finalDict = [String: [CarrierInfo]]()
and create CarrierInfo instance and set it in finalDict
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
let amount = dict.amount
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [CarrierInfo]()
}
self.finalDict[carrierTitle]!.append(CarrierInfo(name: carrierTitle, amount: amount))
}
Likewise you can make other required changes. This would neatly wrap your row display data inside a structure.
PS: I have not tested the code in IDE so it may contain typos.
You can assign another dictionary with key as methodTitle and amount as value. i.e., ["fixed":"whatever_amount"]
OR
You can use finalDict differently, like ["Flat Rate": ["tilte":"Fixed","amount":"0"], "Best Way": ["title":"Table Rate","amount":"0"]]
If it is difficult for you to code this, you can revert back.
Edit
You can use the following code to create the array in the second solution I suggested above:
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
let amount = dict.amount
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [[String:String]]()
}
let innerDict = ["title":methodTitle,"amount":amount]
self.finalDict[carrierTitle]!.append(innerDict)
}
I want get the below json to my array for showing in UITableview
{
MyPets = (
{
breed = "";
breedvaccinationrecord = "";
"city_registration" = "";
"date_of_birth" = "";
"emergency_contacts" = "";
gender = m;
"pet_id" = 475;
"pet_name" = "IOS PET";
petinfo = "http://name/pet_images/";
"prop_name" = "";
"qr_tag" = 90909090;
species = Canine;
"vaccination_records" = "";
vaccinationrecord = "http://Name/vaccination_records/";
"vet_info" = "";
}
);
}
i am using below code to get values into array
if let dict = response.result.value {
print(response)
let petListArray = dict as! NSDictionary
self.petListArray = petListArray["MyPets"] as! [NSMutableArray]}
in cellForRowAtIndexPath i am using this line to display name in UILabel in TableCell
cell?.petName.text = self.petListArray[indexPath.row].valueForKey("pet_name") as? String
but it is crashing like
fatal error: NSArray element failed to match the Swift Array Element type
i am new to swift 2 please help me thanks in advance
First of all declare petListArray as Swift Array, do not use NSMutable... collection types in Swift at all.
By the way the naming ...ListArray is redundant, I recommend either petList or petArray or simply pets:
var pets = [[String:Any]]()
The root object is a dictionary and the value for key MyPets is an array, so cast
if let result = response.result.value as? [String:Any],
let myPets = result["MyPets"] as? [[String:Any]] {
self.pets = myPets
}
In cellForRow write
let pet = self.pets[indexPath.row]
cell?.petName.text = pet["pet_name"] as? String
It's highly recomenended to use a custom class or struct as model. That avoids a lot of type casting.
I'm having a lot of frustration with Swift when it comes to working with Dictionaries and NSDictionaries.
I am pulling data from a server. One of the values is a Bool.
I started with a Swift Dictionary and moved to NSDictionary out of frustration. However, I still cannot get the values from the dictionary.
All of the following fail with contradictory errors:
let unread:Bool = data!["unread"] as! Bool
let unread:Bool = data?["unread"] as! Bool
let unread:Bool = data?.objectForKey("unread") as! Bool
let unread:NSNumber = data?["unread"] as! NSNumber
error: Could not cast value of type 'NSTaggedPointerString' (0x110c1eae8) to 'NSNumber' (0x10e0ab2a0).
Okay, looks like that data is coming in as a String... let's try:
let unreadStr:String = data!["unread"] as! String
let unreadStr:NSString = data!["unread"] as! NSString
error: Could not cast value of type '__NSCFBoolean' (0x1097413b8) to 'NSString' (0x106bcdb48).
So I'm confused. When I try to convert it to a Bool it says I cannot convert a String to a Number. When I try to convert it to a String, it says I cannot convert a number to a string.
Here is what the data looks like:
Optional({
senderId = 10154040;
sent = 1460844986973;
text = "Test Message 1";
unread = false;
})
You should try something along these lines:
let data: [String : Any] = ["first" : "test", "second" : 2, "third" : true]
let first = data["first"] as! String
let second = data["second"] as! Int
let third = data["third"] as! Bool
print(first)
print(second)
print(third)
I have the following class
class BannerResponse : NSObject{
let URL = "Url";
let CONTACT_NO = "ContactNo";
let IMAGE = "Image";
let BIG_IMAGE = "BigImage";
let ID = "Id";
let TITLE = "Title";
let NO_VIEW = "NoView";
let START_DATE = "StartDate";
let END_DATE = "EndDate";
var url:String;
var contactNo:String;
var image:String;
var bigImage:String;
var title:String;
var id:Int;
var noView:Int;
var startDate:String;
var endDate:String;
init(data : NSDictionary){
url = data[URL] as! String;
contactNo = data[CONTACT_NO] as! String;
image = data[IMAGE] as! String;
bigImage = data[BIG_IMAGE] as! String;
title = data[TITLE] as! String;
id = data[ID] as! Int;
noView = data[NO_VIEW] as! Int;
startDate = data[START_DATE] as! String;
endDate = data[END_DATE] as! String;
}
}
when I run the code, I got the following error
Could not cast value of type 'NSNull' (0x10a85f378) to 'NSString' (0x109eccb20).
EDIT
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary{
onSuccess(BannerResponse(data: json))
}
} catch {
onFail()
}
One of your data[SOME_KEY] is of type NSNull instead of String and because you're forcing the cast to String by using ! the app crashes.
You can do one of two things:
Change your variables on the BannerResponse class to be optional. And use ? instead of ! when setting the values in your init method. Like this:
`
var title: String?
init(data: NSDictionary)
{
self.title = data[TITLE] as? String
}
or
Use ? instead of ! when setting the values in your init method but set a default value whenever dict[SOME_KEY] is nil or is not the expected type. This would look something like this:
`
if let title = data[TITLE] as? String
{
self.title = title
}
else
{
self.title = "default title"
}
// Shorthand would be:
// self.title = data[TITLE] as? String ?? "default title"
And I guess a third thing is ensure that the server never sends down null values. But this is impractical because there's no such thing as never. You should write your client-side code to assume every value in the JSON can be null or an unexpected type.
You are getting null values for some of your keys. They get mapped to NSNull by NSJSONSerialization.
You need to do several things
Change all your variables (url, contactNo, etc) to optionals:
var url:String?
var contactNo:String?
Change all of your assignments to use ? instead of !:
url = noNulls[URL] as? String
contactNo = noNulls[CONTACT_NO] as? String
And finally, make your code handle nil values for all of your variables. (But do not use !. That path leads to crashes.)
I apologise for the title of this question. I have no idea what else to call it.
So... When calling the following:
let testData: [NSObject : AnyObject] = getTestData()
print(testData)
I get this output:
[data: {"TypeId":7,"DataList":null,"TypeName":"This is a test"}]
How would I be able to access the value 7 for the key "TypeId"?
EDIT:
Please note that it's holding { } brackets, not only [ ], thus a cast to NSDictionary is not possible as far as I have tried.
Kind regards,
Anders
You can achieve plist-like nested structures using Any type for dictionary values which is Swift's somewhat counterpart to Objective-C's id type but can also hold value types.
var response = Dictionary()
response["user"] = ["Login": "Power Ranger", "Password": "Mighty Morfin'"]
response["status"] = 200
Any seems to be better than AnyObject because in the above code response["status"] is of type Swift.Int, while using value type of AnyObject it is __NSCFNumber.
The way most people do it is to parse annoying JSON data as custom objects. That should be done as soon as you get the JSON. Ideally, data as JSON should not be used outside your communication code, example:
First, let's define a class to hold your server data:
class MyServerObject {
let typeId: Int
let typeName: String
let dataList: [AnyObject]?
init(dictionary: Dictionary<String, AnyObject>) {
let dataDictionary = dictionary["data"] as! Dictionary<String, AnyObject>
self.typeId = dataDictionary["TypeId"] as! Int
self.typeName = dataDictionary["TypeName"] as! String
self.dataList = dataDictionary["DataList"] as? [AnyObject]
}
}
Note that init method is already parsing the JSON. This doesn't have to be done in init, you could also create a static parse method that will return a new instance.
Usage:
// demo data
let jsonString = "{\"data\": {\"TypeId\":7,\"DataList\":null,\"TypeName\":\"This is a test\"}}"
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// parsing
let myServerObject = MyServerObject(dictionary: json as! Dictionary<String, AnyObject>)
// now we can simply read data as properties
print(myServerObject.typeId)
print(myServerObject.typeName)
One of the good thing about this solution is that we can check the JSON format and all the properties are parsed with the correct types.
Parsing can be hierarchical, for example, if your dataList contains complex objects, let's call them DataListItem, your parsing method can parse each item separately and put them into a [DataListItem], e.g.
if let dataListJSON = dataDictionary["DataList"] as? [Dictionary<String, AnyObject>] {
self.dataList = dataListJSON.map({ DataListItem($0) })
}
Also note that when parsing as! will crash the app when the format is invalid. as? will return nil if the types don't match. as? is very useful for types that can be nil because they are parsed as NSNull instances.
taking in account your data ...
print(testData)
/*
[data: {
DataList = null;
TypeId = 7;
TypeName = "This is a test";
}]
*/
// DataList type should be declared somewhere
class DataList {}
// parse data or set default value, if 'key' doesn't exist
if let data = testData["data"] as? [String:AnyObject] {
let dataList = data["DataList"] as? DataList // nil
let typeId = data["TypeId"] as? Int ?? 0 // 7
let typeName = data["TypeName"] as? String ?? "" // This is test
}