Casting NSManagedObject property from num to Bool in swift - xcode

I know that question has been asked many times, but the solutions didn't work with me. I have the following NSManaged object class:
#NSManaged var cellColor: AnyObject
#NSManaged var des: String
#NSManaged var name: String
#NSManaged var switcher: NSNumber
And when trying to assign this value to a var as a bool when loading the managed object, I get an error. This is an example of assigning the value to a var:
func loadData(){
var appDel = UIApplication.sharedApplication().delegate as AppDelegate
var context = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Row")
var result:NSArray = context.executeFetchRequest(request, error: nil)!
if result.count > 0 {
for i in result{
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher:Bool{
get{
return i.switcher == NSNumber(bool: true)
//the problem happens here
However, when I try a simple example of casting in this way, It works well.
How to solve that ??

I think it just like this:
for i in results {
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher: Bool {
return Bool(i.switcher)
}
}
Didn't test that though.

Related

how to parse json with alamofire and swiftjson?

I'm using swiftjson and alamofire to parse the json.pls help fix my code.
here the json array
Below are my code
RestClient.sharedClient.getUserWallet(uid: uid!, token: token!) { (json, error) in
print(json as Any)
self.tableRows = json!["data"].count
//ALL BELOW IS DONE BY SWIFTYJSON
let jsonArray = json?["data"].array
if jsonArray != nil {
for object in jsonArray! {
let walletCells: UserWalletCells = UserWalletCells(json: object)
self.userWalletCells.append(walletCells)
}
}
class PackageList {
var id: Int?
var user_id: String?
var amount: Int?
var currency_id: Int?
var release_rate: Double?
var release_per_day: Int?
var release_date: String?
var end_date: String?
var total_release: Int?
var tier_id: Int?
var is_active: Int?
var created: String?
var modified: String?
var remainingdays: Int?
init(json: JSON){
self.id = json["id"].intValue
self.user_id = json["user_id"].stringValue
self.amount = json["amount"].intValue
self.currency_id = json["currency_id"].intValue
self.release_rate = json["release_rate"].doubleValue
self.release_per_day = json["release_per_day"].intValue
self.release_date = json["release_date"].stringValue
self.end_date = json["end_date"].stringValue
self.total_release = json["total_release"].intValue
self.tier_id = json["tier_id"].intValue
self.is_active = json["is_active"].intValue
self.created = json["created"].stringValue
self.modified = json["modified"].stringValue
self.remainingdays = json["remainingdays"].intValue
}
}
I'm using swiftjson and alamofire to parse the json.pls help fix my code.
Please try this it will help you
let json = JSON(response)
let dictResult = json["data"].dictionaryValue
let arrayValue = dictResult["apckage"].arrayValue
var arrList = [PackageList]()
for i in 0..<arrayValue.count{
let packageList = PackageList()
let dictRespose = arrayValue[i]
packageList. id = dictRespose["id"].stringValue
packageList. user_id = dictRespose["user_id"].stringValue
packageList. amount = dictRespose["amount"].stringValue
arrList.append(packageList)
}
return arrTaxLis
Like this you put all your key. It may helps you. Thank you.

How to change link color in UITextView in xamarin.ios

We have created a clickable text in UITextView by using this code
var urlString = #"<a href=""https://www.google.com"" >Google</a>";
var documentAttributes = new NSAttributedStringDocumentAttributes { DocumentType = NSDocumentType.HTML };
NSError error = null;
var attributedString = new NSAttributedString(NSData.FromString(urlString, NSStringEncoding.UTF8), documentAttributes, ref error);
// Should really check the NSError before applying
MyTextView.AttributedText = attributedString;
but its showing by default blue color for the link and underlined text. We want to change the color for the text and also remove underline.
Please guide/help me to implement this.
You can change these properties just adding UIStringAttributeKey.ForegroundColor and UIStringAttributeKey.UnderlineStyl to your dictionary and set it to WeakLinkTextAttributes property
var key1 = UIStringAttributeKey.ForegroundColor;
var value1 = UIColor.Red;
var key2 = UIStringAttributeKey.UnderlineStyle;
var value2 = new NSNumber(0); // 0 without underline 1 with underline
var dict = new NSDictionary(key1, value1, key2, value2);
var urlString = #"<a href=""https://www.google.com"" >Google</a>";
var documentAttributes = new NSAttributedStringDocumentAttributes {
DocumentType = NSDocumentType.HTML };
NSError error = null;
var attributedString = new NSAttributedString(NSData.FromString(urlString, NSStringEncoding.UTF8), documentAttributes, ref error);
yourTextView.AttributedText = attributedString;
yourTextView.WeakLinkTextAttributes = dict;

Realm is returning an empty object when I convert it to an array

Using Realm in a Swift application. I'm fetching users from Realm and want to return an array of users (as my app also uses Parse, it's easier if they are all arrays I'm guessing).
Here is my code:
class func fetchUsersFromDB() -> [User]{
var users = [User]()
let realm = Realm()
var allUsers = realm.objects(User)
users = Array(allUsers)
return users
}
When I do a dump of allUsers I can see a Realm result. But when I dump users it shows me the object with default values.
Any ideas what I'm doing wrong?
Here is how I declare the User model
class User: Object {
dynamic var objectId: String = ""
dynamic var username: String = ""
dynamic var password: String = ""
dynamic var emailVerified: Bool = false
dynamic var email: String = ""
dynamic var firstName: String = ""
dynamic var defaultRelationshipId: String = ""
dynamic var picture: NSData = NSData()
dynamic var updatedAt: NSDate = NSDate()
dynamic var createdAd: NSDate = NSDate()
override static func primaryKey() -> String? {
return "objectId"
}
}

Dictionaries not working inside a struct SWIFT

Why is this not working!?
struct ChocolateBox {
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
}
I tried this without the struct, still doesn't work:
var caramelDelight = []
caramelDelight["flavor"] = "caramel"
I have to add initial values into the array for it to work, for example:
var caramelDelight = ["test":"test"]
caramelDelight["flavor"] = "caramel"
Please explain.
Your var caramelDelight = [] doesn't create an empty dictionary.
To create an empty dictionary use [:]() and specify the types of the keys and values, example: var caramelDelight = [String:String]().
There's also this alternative syntax: var caramelDelight: [String:String] = [:].
Also to modify the var in your struct you need to create an instance of the struct first:
struct ChocolateBox {
var caramelDelight = [String:String]()
}
var cb = ChocolateBox()
cb.caramelDelight["flavor"] = "caramel"
println(cb.caramelDelight) // [flavor: caramel]
UPDATE:
You can also create an initializer for your struct if you need to prepopulate the dictionary:
struct ChocolateBox {
var caramelDelight: [String:String]
init(dict: [String:String]) {
self.caramelDelight = dict
}
}
var cb = ChocolateBox(dict: ["flavor": "caramel"])
Of course then you can update the dictionary as usual:
cb.caramelDelight["color"] = "brown"
println(cb.caramelDelight) // [color: brown, flavor: caramel]
That is because caramelDelight is actually an array, not a dictionary. You can fix that by doing var caramelDelight: [String:String] = [:]

Signal SIGABRT in Swift using NSuserdefaults

I'm building a swift game and a need to set up a class. My code works for all the elements in my class, but not for this.
func saveInformationMember(){
var MembersDefaultName = NSUserDefaults.standardUserDefaults()
MembersDefaultName.setValue(globalCurrentMembers, forKey: "globalCurrentMembersData")
MembersDefaultName.synchronize()
}
GlobalCurrentMembers is an array of Member which looks like that:
class Member {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func Init(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
To save your class this way, Member needs to conform to the NSCoding protocol.
Thx to Aaron Brager for is response. This is the response :
func saveInformationMember(){
let data = NSKeyedArchiver.archivedDataWithRootObject(globalCurrentMembers)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "member")}
func loadInformationMember(){
if let data = NSUserDefaults.standardUserDefaults().objectForKey("member") as? NSData {
globalCurrentMembers = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Member]
}
And my class:
class Member : NSObject, NSCoding {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func initiation(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
required convenience init(coder decoder: NSCoder) {
self.init()
self.image = decoder.decodeObjectForKey("image") as String!
self.name = decoder.decodeObjectForKey("name") as String!
self.progression = decoder.decodeIntegerForKey("progression") as Int!
self.round = decoder.decodeIntegerForKey("round") as Int!
self.level = decoder.decodeIntegerForKey("level") as Int!
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.image, forKey: "image")
coder.encodeObject(self.name, forKey: "name")
coder.encodeInt(Int32(self.progression), forKey: "progression")
coder.encodeInt(Int32(self.round), forKey: "round")
coder.encodeInt(Int32(self.level), forKey: "level")
}}

Resources