i am developing a application in which i add contact to contact List. i am able to basic info like name, address, email, phone, notes etc. but i want to add some custom field like userLabel1, userValue1 , bioPersonal, bioWork, bioOther. so i want to add custom fields to address Book'contacts.
whether it is possible to add custom field to contact? if yes , then please suggest any link or sample code?
Basically, there is no way to do that. Address Book doesn't let you add custom fields. However, what you can do is put your data in the "Notes" field for each contact. That will, however, look weird in apps other than yours.
let store = CNContactStore()
// phoneNumberToEdit is the CNContact which you need to update
guard var mutableCont = phoneNumberToEdit?.mutableCopy() as? CNMutableContact else { return }
let phoneNumber = CNPhoneNumber(stringValue: "0123456789")
var currentContact = CNLabeledValue(label: "MyCustomLabel", value: phoneNumber)
mutableCont.phoneNumbers = [currentContact]
let request2 = CNSaveRequest()
request2.update(mutableCont)
do{
try store.execute(request2)
} catch let error{
print(error)
}
Related
I don't know how to get data from Firebase to my UITableView. All tutorials I have been watching used Firebase Authentication, in their videos all worked out fine but while trying to replicate it, I failed.
Here is what I tried:
First there is my Database struct:
And here is my code:
func observePosts(){
let postsRef = Database.database().reference().child("posts")
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children {
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let text = dict["text":""] as? String
{
let post = Post(text: text)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
So my question is: How do I get for example the message from a database structure like this?
let text = dict["text":""] as? String {
let post = Post(text: text)
tempPosts.append(post) }
This is wrong. There is nothing like dict["text":""] . First you dont have any data for text keyword , Second you dont write this :""] , you can call as dict["text"].
I think you solution is let text = dict["title"] as? String . But you architecture is wrong. You can declare just one keyword . title 1 , title 2 is wrong. You have to set just title.
If you have followed YouTube tutorials, there's a high chance you did not modify your firebase rules to reflect on non-authenticated users. If you didn't, Firebase ignores every read/write request. To enable this, Edit your firebase rules by:
Set the rules to TRUE
{
"rules": {
".read": true,
".write": true
}
}
However, there's more to it. Don't do it this way unless you're in test mode. Google has some nice docs about it:
Visit https://firebase.google.com/docs/database/security to learn more about security rules.
What is the correct way to set CNContact.predicateForContacts to select the field "email" in CNContacts? Like in SQL where email like "%lbs%"?
This is my function to delete a lot of imported contacts I want to get rid of. But the function return 0 hits. But there are more than 1000 contacts with "lbs" in the field email.
func deleteContacts(){
let store = CNContactStore()
let predicate = CNContact.predicateForContacts(matchingName: "lbs")
let toFetch = [CNContactEmailAddressesKey]
do{
let contacts = try store.unifiedContacts(matching: predicate,keysToFetch: toFetch as [CNKeyDescriptor])
guard contacts.count > 0
else{
print("No contacts found")
return
}
guard let contact = contacts.first else{
return
}
let req = CNSaveRequest()
let mutableContact = contact.mutableCopy() as! CNMutableContact
req.delete(mutableContact)
do{
try store.execute(req)
print("Success, deleted the data: Count: \(contacts.count)")
} catch let e{
print("Error = \(e)")
}
} catch let err{
print(err)
}
}
Your predicate is trying to find contacts where the person's name matches the string lbs.
There is no built-in predicate for finding contacts that have an email address containing a specific string. The solution is to use enumerateContacts and look at each individual contact's list of email addresses. You will then need to check to see if any of the contact's email address contains the string you wish to check.
I have a desktop app that receives e-mail URLs ("message://" scheme) from the drag&drop pasteboard and I want to get the Subject from the relevant message. The only clue I have, so far, is that the QuickLook library might give me an information object where I can retrieve this info from.
Since the QuickLook API seems to be rather in flux at the moment and most examples show how to use it in iOS, I simply cannot find a way to set up my "Preview" object using a URL and get the information from there.
I would like to avoid setting up my project as a QuickLook plugin, or setting up the whole preview pane / view scaffolding; at the moment I just want to get out what QuickLook loads before it starts displaying, but I can't comprehend what paradigm Apple wants me to implement here.
XCode 7.3.1.
It turns out I misinterpreted the contents of draggingInfo.draggingPasteboard().types as a hierarchical list containing only one type of info (URL in this case).
Had to subscribe to dragged event type kUTTypeMessage as String and retrieve the e-mail subject from the pasteboard with stringForType("public.url-name")
EDIT: Note that the current Mail.app will sometimes create a stack of mails when you drag an e-mail thread. Although the method above still works to get the subject of the stack, there is no URL in the dragging info then and since there's no list of Message-IDs available either, I had to resort to scraping the user's mbox directory:
// See if we can resolve e-mail message meta data
if let mboxPath = pboard.stringForType("com.apple.mail.PasteboardTypeMessageTransfer") {
if let automatorPlist = pboard.propertyListForType("com.apple.mail.PasteboardTypeAutomator") {
// Get the latest e-mail in the thread
if let maxID = (automatorPlist.allObjects.flatMap({ $0["id"]! }) as AnyObject).valueForKeyPath("#max.self") as? Int {
// Read its meta data in the background
let emailItem = draggingEmailItem
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Find the e-mail file
if let path = Util.findEmlById(searchPath: mboxPath, id: maxID) {
// Read its contents
emailItem.properties = Util.metaDataFromEml(path)
dispatch_async(dispatch_get_main_queue(), {
// Update UI
});
}
}
}
}
}
Util funcs:
/* Searches the given path for <id>.eml[x] and returns its URL if found
*/
static func findEmlById(searchPath searchPath: String, id: Int)-> NSURL? {
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(searchPath)
while let element = enumerator?.nextObject() as? NSString {
switch (element.lastPathComponent, element.pathExtension) {
case (let lpc, "emlx") where lpc.hasPrefix("\(id)"):
return NSURL(fileURLWithPath: searchPath).URLByAppendingPathComponent(element as String)!
case (let lpc, "eml") where lpc.hasPrefix("\(id)"):
return NSURL(fileURLWithPath: searchPath).URLByAppendingPathComponent(element as String)!
default: ()
}
}
return nil
}
/* Reads an eml[x] file and parses it, looking for e-mail meta data
*/
static func metaDataFromEml(path: NSURL)-> Dictionary<String, AnyObject> {
// TODO Support more fields
var properties: Dictionary<String, AnyObject> = [:]
do {
let emlxContent = try String(contentsOfURL: path, encoding: NSUTF8StringEncoding)
// Parse message ID from "...\nMessage-ID: <...>"
let messageIdStrMatches = emlxContent.regexMatches("[\\n\\r].*Message-ID:\\s*<([^\n\r]*)>")
if !messageIdStrMatches.isEmpty {
properties["messageId"] = messageIdStrMatches[0] as String
}
}
catch {
print("ERROR: Failed to open emlx file")
}
return properties
}
Note: If your app is sandboxed you will need the com.apple.security.temporary-exception.files.home-relative-path.read-only entitlement set to an array with one string in it: /Library/
I saved my account through Locksmith Keychain, everything works fine, right now i need to parse the data stored to a textField, how can i do it please?
Here is the code that i use to save my account:
let accountsave = Locksmith.saveData(["account": self.txtAccount.text], forUserAccount: "myUserAccount", inService: "myAccount").
Right now i need to parse the data store to a textfield in swift. Please help
From what I understand of your question you're asking for something similar to this:
let (dictionary, error) = Locksmith.loadDataForUserAccount("myUserAccount", inService: "myAccount")
if let userData = dictionary as? [String:String] {
if let account = userData["account"] {
self.txtAccount.text = account
}
}
How should I access columns that I've added to the User table when I have a currentUser object?
I have a PFUser.currentUser() and I want to access the nickname column that I added via the web interface.
Can I use the currentUser to get the data e.g.:
var nickname = PFUser.currentUser()["nickname"] as String
Or do I have to use a user query? e.g.:
var query = PFUser.query()
query.whereKey("username", equalTo:PFUser.currentUser().username)
var user = query.findObjects().first as PFUser
var nickname = user["nickname"]
If you added date to the column locally, then you have to use the first way as you wrote, or if you added date in the browser, or uploaded to parse.com some way, you have to use the second way.
I would like to give my two cents too. First of all, Daniel was right in saying that if you added the date in the browser or uploaded it to parse.com, you need to use the second way. This is an updated answer with iOS 9 and Xcode 7.2:
var query = PFUser.query()
query!.whereKey("username", equalTo:PFUser.currentUser()!.username!)
do {
user = try query!.findObjects().first as! PFUser
} catch {
print("Error finding user")
}
if user?["rankNumber"] as? Int == nil {
user!["rankNumber"] = 0
user!.saveInBackground()
} else {
print(user!["rankNumber"] as! Int)
}
If I did it any other way, xcode would give me an error saying "failing to unwrap optional". I hope this can help someone!