Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Is there a way I can fetch contacts using the Contacts framework without an attribute?
Example:
myContactArray = unifiedContactsNotCalled("John")
PS: I know that line is nothing like the real code, it's just a serving suggestion for illustrative purposes 😉
Before I outline how to find those that don't match a name, let's recap how one finds those that do. In short, you'd use a predicate:
let predicate = CNContact.predicateForContacts(matchingName: searchString)
let matches = try store.unifiedContacts(matching: predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) // use whatever keys you want
(Obviously, you'd wrap that in a do-try-catch construct, or whatever error handling pattern you want.)
Unfortunately, you cannot use your own custom predicates with the Contacts framework, but rather can only use the CNContact predefined predicates. Thus, if you want to find contacts whose name does not contain "John", you have to manually enumerateContacts(with:) and build your results from that:
let formatter = CNContactFormatter()
formatter.style = .fullName
let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]) // include whatever other keys you may need
// find those contacts that do not contain the search string
var matches = [CNContact]()
try store.enumerateContacts(with: request) { contact, stop in
if !(formatter.string(from: contact)?.localizedCaseInsensitiveContains(searchString) ?? false) {
matches.append(contact)
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
How can I check if the string is base64 encoded in swift?
Input = "tNC6umcfBS/gelbo2VJF3i4LAhUKMp4oDHWN5KyYUTWeJIQKKYx6oAcQnGncIrPJNC1tUYMKV4kJQj3q9voIOrxc1n7FmRFvDXeRgWGNcGYO66dH3VjoEgF0oxZOpfzwSZKSv3Jm7Q=="
let base64Regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$"
let predicate = NSPredicate(format: "SELF MATCHES %#", base64Regex)
let result = predicate.evaluate(with: "InputString")
You can also try to decode using the built-in Data:
let inputString = "..."
let isBase64Encoded = Data(base64Encoded: inputString) != nil
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I basically have this issue where this Reporting API only allows me to call it once each 90 seconds.
I'm building an app where I get the data each time you open it, to get the latest data, but I somehow need to stop the app from calling the API if it was before 90s wait and show cached data, how can I do this?
Each time you go to ping the API compare the current time to the last time it was done. Kinda like this:
// set defaults for storage
let userDefaults = UserDefaults.standard
// set time
let date = Date()
//Check Storage
if let theDate = userDefaults.object(forKey: "date") as? Date {
// on successful load compare times
if date.timeIntervalSince(theDate) > 90000 /* I think it runs in milliseconds so I put 90 seconds worth there*/ {
// do API call here
// save time
userDefaults.set(date as! Any, forKey: "date")
} else {
print("too soon")
} else {
// data not successfully loaded
// try to ping API here too
// save time
userDefaults.set(date as! Any, forKey: "date")
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I get the this string "85:ABC ,83:CFD" after downloading from a web service.I need to store these values to CoreData table TABLE_JOBTITLE. I have the below code
var designationDictionaryArray = results.componentsSeparatedByString(",")
var index: Int = 1
for item in designationDictionaryArray
{
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("TABLE_JOBTITLE",
inManagedObjectContext:managedContext)
let job = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
job.setValue(String(index), forKey: "column_Id")
job.setValue(String(item.componentsSeparatedByString(":")[0]), forKey: "column_Server_Id")
job.setValue(String(item.componentsSeparatedByString(":")[1]), forKey: "column_Job_Name")
print("Column_Id")
print(index)
print("Column_Server_Id")
print(String(item.componentsSeparatedByString(":")[0]))
print("column_Job_Name")
print(String(item.componentsSeparatedByString(":")[1]))
do {
try managedContext.save()
print("saved job title")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
self.desiginationArray.append(item.componentsSeparatedByString(":")[1])
index = index + 1
}
I am able to iterate through each data but the when i store it in the table..It get stored like below
coulmn_Id column_ServerId column_Job_Title
1 83 CFD
1 83 CFD
Could anyone help me with corrected code or reason for this bizarre behavior please..
I suspect one of two things:
The value in result is not as you expect.
The manner in which you are checking the output is faulty.
I lean towards the latter as I do not see any way both entities could be assigned the same column ID in a single run through.
Put breakpoints up top to check the value of results and the array returned from results.componentsSeparatedByString(",").
Show the code you used to iterate through the table to check it. My bet is that you are not showing the true output. What is the output from the print lines within the loop? If it looks something like this:
Column_Id
1
Column_Server_Id
85
column_Job_Name
ABC
Column_ID
2
Column_Server_ID
83
Column_ID
CFD
Then I'd say, for sure, you are not properly reading back your results from Core Data. Let us see where you are getting that final table.
I don't know what the problem was the same code worked as it should.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learner on iOS Development,today i try to code somethingenter image description here about FileManger,but this method return a type '()',how can i to resolve it?
the warning code as follow:
The problem is that your call to createDirectoryAtURL does not have a explicit return value. In Swift, that means it returns a Void which is represented by the empty tuple (). This is what your call should look like.
let temp = NSTemporaryDirectory()
let newDiretoryURL = NSURL.fileURLWithPath(temp + "/MyNewDirectory")
try fileManager.createDirectoryAtURL(newDiretoryURL, withIntermediateDirectories: false, attributes: nil)
print("Success")
}
} catch {
// handle errors here
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm working on creating a Tinder clone on Firebase 100%, from authentication up to real-time chat. I've been successful to the point of showing users their mutually interested matches on the Messages View Controller's tableview. Now my problem lies in creating a chatroom for the matched users. What is the most efficient way of going about this?
Do I create chatroom objects from the Firebase base reference, and assign the chatroom both users, and plug in the chatroom's key into both users?
I'm just confused on how to go about that, because I've written the code to start on that idea above, but how can I make sure that once a chatroom is created, the users will always have that room, and not have a brand new room initialized for them? I think I'm going about it the wrong way... The way I have the code now, the chat rooms will be made on the Messages View Controller when I run this block of code:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
currentUserKey = DataService.ds.REF_CURRENT_USER.key
DataService.ds.REF_CURRENT_USER.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let matchesInterestedIn = snapshot.value["matchesInterestedIn"] {
if matchesInterestedIn != nil {
for (_, value) in matchesInterestedIn as! [String: String] {
self.currentUserInterests.append(value)
}
}
}
})
DataService.ds.REF_USERS.observeSingleEventOfType(.Value, withBlock: { snapshot in
self.admirers = [Match]()
self.matches = [Match]()
if snapshot != nil {
for potentialMatch in snapshot.children {
let potentialMatchData = potentialMatch.valueInExportFormat()
if potentialMatchData["matchesInterestedIn"] != nil {
if let potentialMatchInterests = potentialMatchData["matchesInterestedIn"] as? Dictionary<String, String> {
if potentialMatchInterests.values.contains(self.currentUserKey) {
let interestedMatch = Match(snapshot: potentialMatch as! FDataSnapshot)
self.admirers.append(interestedMatch)
}
}
}
}
}
if self.admirers.count > 0 {
for potentialMatch in self.admirers {
if self.currentUserInterests.contains(potentialMatch.key) {
self.matches.append(potentialMatch)
let chatRoomInitializer = ["user1": self.currentUserKey, "user2": potentialMatch.key]
let chatRoomRef = DataService.ds.REF_CHATROOMS.childByAutoId()
let chatRoomID = chatRoomRef.key
// For some odd reason, the next two lines of code create an endless amount of chatroom objects from the base reference
let currentUserChatRoomRef = DataService.ds.REF_CURRENT_USER.childByAppendingPath("chatrooms").childByAutoId()
currentUserChatRoomRef.setValue(chatRoomID)
let potentialMatchRef = DataService.ds.REF_USERS.childByAppendingPath(potentialMatch.key).childByAppendingPath("chatrooms").childByAutoId()
potentialMatchRef.setValue(chatRoomRef.key)
chatRoomRef.setValue(chatRoomInitializer)
}
}
}
self.tableView.reloadData()
})
}
A common way is to create a room name based on the users in that room.
So if your uid is ron and mine is puf, we end up in a room puf_ron.
Note that I ordered the uids before concatenating, so that they are in the same order no matter who happened to end up first in the list of users.
This approach doesn't require keeping track of what rooms a user is in and ensures that the same two (or more) users always end up in the same room.