I have NSMutableDictionary with (key,value) pairs.For JournalId the key is "journalId".I just want to check whether my dictionary contains specific "journalId", for eg, 29. If it exists, need to print the corresponding title and userId.
eg.
{
journalId = 28;
title = Creed;
userId = 105; } {
journalId = 29;
title = Fg;
userId = 105; } {
journalId = 30;
title = Dhh;
userId = 105; }
I want to check in my dictionary whether it has journalId value = 28.
if (dictValues["journalId"] == 28){
print(dictValues["title"]
}
The above method shows error.
Thanks in advance.
guard dictValues["journalId"] as! Int == 28 else {
print("key Not found")
return // exit the function
}
let title = dictValues["title"] as! String
print("\(title)")
Try this:
if let journalId = dictValues["journalId"] as? Int, journalId == 28 {
print(dictValues["title"])
}
NSDictionary subsctiption returns an object of type AnyObject?.
This code should resolve your problem
if (dictValues["journalId"] as? Int == 28) {
print(dictValues["title"])
}
Related
I'm very lost parsing the following response from an AF request – let json = result as! NSDictionary – in Swift:
{
errors = (
);
get = statistics;
parameters = {
country = germany;
};
response = (
{
cases = {
"1M_pop" = 14303;
active = 317167;
critical = 4179;
new = "+15161";
recovered = 863300;
total = 1200006;
};
continent = Europe;
country = Germany;
day = "2020-12-08";
deaths = {
"1M_pop" = 233;
new = "+380";
total = 19539;
};
population = 83900328;
tests = {
"1M_pop" = 347331;
total = 29141172;
};
time = "2020-12-08T09:15:08+00:00";
}
);
results = 1;
}
Any idea how to get the actual case numbers, i.e. for example the number of new cases?
So far I have tried the following (error throwing) approach:
if let responseDict = result as? NSDictionary {
if let data = responseDict.value(forKey: "response") as?
[NSDictionary] {
// Get case numbers
guard let cases = data[0]["cases"] else { return }
guard let casesPerOneMil = cases[0] as! Int else { return }
print(casesPerOneMil)
}
}
Basically don't use NS... collection types in Swift at all, use native types.
And don't use value(forKey, use key subscription.
And you have to conditional downcast Any to the expected concrete type.
There is another mistake: The object for cases is a dictionary, note the {} and you have to get the value for casesPerOneMil with key subscription, too
if let responseDict = result as? [String:Any],
let dataArray = responseDict["response"] as? [[String:Any]],
let firstDataItem = dataArray.first {
// Get case numbers
guard let cases = firstDataItem["cases"] as? [String:Any] else { return }
guard let casesPerOneMil = cases["1M_pop"] as? Int else { return }
print(casesPerOneMil)
}
}
I've got a problem with storing an NSDictionary object with 39 parameters (key and value) into a UserDefault object. The code crashes where I left the comment. self.userDefaults.set(data, forKey: "userData")
This is the error I'm getting:
[User Defaults] Attempt to set a non-property-list object {
city = "";
country = "";
cover = "default.png";
date = "2019-10-02";
description = "";
email = "hashdoge#outlook.com";
"email_comment" = 0;
"email_like" = 0;
"email_new_friend" = 0;
"email_newsletter" = 1;
facebook = "";
"first_name" = "";
follower = 3;
following = 2;
gender = 0;
gplus = "";
idu = 42;
image = "default.png";
ip = "";
"last_name" = "";
lastfm = "";
likes = 3;
"login_token" = "<null>";
"logout_time" = 0;
myspace = "";
notificationc = 1;
notificationd = 1;
notificationf = 1;
notificationl = 1;
offline = 0;
online = 1570879800;
password = "$2y$107675ze1wZ/riJgQ2e";
private = 0;
salted = "$2y$10$GKUmSJGcq932DMJGMA8791RIO";
soundcloud = "";
suspended = 0;
totaltracks = 0;
tumblr = "";
twitter = "";
username = HashDoge;
vimeo = "";
website = "";
youtube = "";} as an NSUserDefaults/CFPreferences value for key userData
Here is the code that I'm trying to make work
Code:
func callApigetLoginResponse(){
FTIndicator.showProgressWithmessage("", userInteractionEnable: false)
let parameters = ["useremail":txtEmail.text!,"password":txtPassword.text!]
SignInGet.ApiGetSignIn(parameters: parameters as NSDictionary) { (Result, Error) in
// print(Result!)
if Error != nil{
print(Error!)
}else{
let dataDict:NSDictionary = Result as! NSDictionary
if (dataDict["success"]as! Int == 1){
let loginResponse = dataDict["userlogin"] as! NSArray
let data = loginResponse[0] as! NSDictionary
let uid = data["idu"] as! String
self.sendTokenaApi(uid: uid)
self.userDefaults.set(uid, forKey: "id")
self.userDefaults.set(data, forKey: "userData") // code crashes here
self.userDefaults.synchronize()
let updateUserInfo = UpdateUserInfoUtl()
updateUserInfo.callApigetUserDataResponse()
self.pushToHomeController()
}else if (dataDict["success"]as! Int == 0) {
let message = dataDict["userlogin"] as! String
FTIndicator.showInfo(withMessage: message)
}
}
}
}
I fixed it. The problem was the "< n u l l >" in the login_token.
I made it as an empty string "" in the database and it worked.
I am trying to parse gcm.notification.createdAt key, but its value is not being casted as Int.
Strangely it is not working even though the value type is clearly Int as you can see.
Any idea what am I doing wrong here?
userInfo is [AnyHashable("gcm.notification.chatUID"): -LgHYXKFNmP-mQo7s9nB,
AnyHashable("gcm.notification.type"): chat,
AnyHashable("gcm.notification.createdAt"): 1559389303,
AnyHashable("google.c.a.e"): 1,
AnyHashable("gcm.message_id"): 0:1559389316529351%e413fc3ee413fc3e,
AnyHashable("aps"): {
alert = {
body = "You have a new message";
title = "New Message from Lehz Raus";
};
badge = 1;
sound = default;
}]
let userInfo = response.notification.request.content.userInfo
guard let createdAt = userInfo["gcm.notification.createdAt"] as? Int else {
print("gcm.notification.createdAt is not showing")
return
}
//this works as expected
guard let chatUUUUID = userInfo["gcm.notification.chatUID"] as? String else {
print("no chatUUUUID printed")
return
}
I suspect your value is not really an Int.
You can investigate the underlying type by printing:
print(type(of: userInfo["gcm.notification.createdAt"]!))
From the comments, you said it returned: __NSCFString so the server is giving you a String. You can convert that to an Int with an additional line in your guard statement:
guard let createdAt = userInfo["gcm.notification.createdAt"] as? String,
let createdAtInt = Int(createdAt) else {
print("gcm.notification.createdAt is not showing")
return
}
New to contacts trying to retrieve Mobile Phone number. I have address name email but cannot figure out mobile phone. This is what I got. The portion marked with ** is where I am going wrong.
if let oldContact = self.contactItem {
let store = CNContactStore()
do {
let mykeysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactEmailAddressesKey, CNContactPostalAddressesKey,CNContactImageDataKey, CNContactImageDataAvailableKey,CNContactPhoneNumbersKey]
let contact = try store.unifiedContactWithIdentifier(oldContact.identifier, keysToFetch: mykeysToFetch)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if contact.imageDataAvailable {
if let data = contact.imageData {
self.contactImage.image = UIImage(data: data)
}
}
self.fullName.text = CNContactFormatter().stringFromContact(contact)
self.email.text = contact.emailAddresses.first?.value as? String
self.phoneNumber.text = contact.phoneNumbers.first?.value as? String
**if contact.isKeyAvailable(CNContactPhoneNumbersKey){
if let phoneNum = contact.phoneNumbers.first?.value as? String {
self.phoneNumber.text = phoneNum as String
}
}**
if contact.isKeyAvailable(CNContactPostalAddressesKey) {
if let postalAddress = contact.postalAddresses.first?.value as? CNPostalAddress {
self.address.text = CNPostalAddressFormatter().stringFromPostalAddress(postalAddress)
} else {
self.address.text = "No Address"
}
}
})
} catch {
print(error)
}
}
If you want a list of the mobile phones for a contact, you look at phoneNumbers which is an array of CNLabeledValue, and find those with a label of CNLabelPhoneNumberMobile or CNLabelPhoneNumberiPhone.
For example, you could do something like:
let mobilePhoneLabels = Set<String>(arrayLiteral: CNLabelPhoneNumberMobile, CNLabelPhoneNumberiPhone, "cell", "mobile") // use whatever you want here; you might want to include a few strings like shown here to catch any common custom permutations user may have used
let mobileNumbers = contact.phoneNumbers.filter { mobilePhoneLabels.contains($0.label) && $0.value is CNPhoneNumber }
.map { ($0.value as! CNPhoneNumber).stringValue }
So if you want the first one:
let mobileNumber = mobileNumbers.first ?? "" // or use `if let` syntax
Or if you want a string representation of the list of them:
let mobileNumberString = mobileNumbers.joinWithSeparator(" ; ")
What you do with this array of mobile numbers is up to you, but hopefully this illustrates the basic idea.
I think I'm looking at some outdated code:
#IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
if let id = cell.productId? {
var newStockLevel:Int?;
if let stepper = sender as? UIStepper {
newStockLevel = Int(stepper.value);
}
else if let textfield = sender as? UITextField {
if let newValue = textfield.text.toInt()? {
newStockLevel = newValue;
}
}
if let level = newStockLevel {
products[id].4 = level;
cell.stockStepper.value = Double(level);
cell.stockField.text = String(level);
}
}
break;
}
}
displayStockTotal();
}
}
But in the first line of the function I get " '?' must be followed by a call, member lookup, or subscript" (for the question mark after as)
What does this error mean and how does this code change for Swift 1.2?
Actually the as? are all fine. The problem is this line:
if let id = cell.productId?
Just remove the question mark at the end of that. It makes no sense.
In 1.2, toInt is gone. So,
if let newValue = textfield.text.toInt()?
Should be replaced with:
if let newValue:Int? = Int(textField.text!)
The problem is the if let newValue = textfield.text.toInt()? { .. If toInt() returns an Int? then just get rid of the ? there.