我正在尝试在Swift for OS X中创建一个代码,其中一个功能是搜索Address Book条目。 下面的代码可以找到条目,并且可以在一个搜索词中正常工作,让人们说出名字John。但是,如果使用第二个搜索词:即名字和姓氏" John Doe" (空格分隔)它返回名称的所有匹配" John"和姓氏的所有比赛" Doe"。
如何强制代码搜索字符串的其余部分,即仅在已经输入的sting的第一部分匹配的地址簿条目中的姓氏,即姓名?
搜索John Dow我只想获得John Doe的地址簿条目,而不是John Doe,John Roe,John Moe,Andrew Doe和#34;等?
抱歉我的英文
let addressBook = ABAddressBook.sharedAddressBook()
var dataArray:[NSDictionary] = [["personCell": "", "emailCell": ""]]
var foundPeople = 0
var personNo = 0
var searchString = "John Doe"
func searchAB() -> NSArray {
var mySearchWord = searchString.componentsSeparatedByString(" ")
for word in mySearchWord {
var searchWord = mySearchWord.removeAtIndex(mySearchWord.endIndex.predecessor())
let comparison: ABSearchConjunction = CFIndex(kABContainsSubStringCaseInsensitive.value)
let firstNameSearch = ABPerson.searchElementForProperty(kABFirstNameProperty,
label: nil,
key: nil,
value: searchWord,
comparison: comparison)
let middleNameSearch = ABPerson.searchElementForProperty(kABMiddleNameProperty,
label: nil,
key: nil,
value: searchWord,
comparison: comparison)
let lastNameSearch = ABPerson.searchElementForProperty(kABLastNameProperty,
label: nil,
key: nil,
value: searchWord,
comparison: comparison)
let comparisons = [firstNameSearch, middleNameSearch, lastNameSearch]
let orComparison = ABSearchElement(forConjunction: CFIndex(kABSearchOr.value), children: comparisons)
let found = addressBook.recordsMatchingSearchElement(orComparison) as! [ABRecord]
for person in found {
let firstName = person.valueForProperty(kABFirstNameProperty) as! String? ?? ""
let middleName = person.valueForProperty(kABMiddleNameProperty) as! String? ?? ""
let lastName = person.valueForProperty(kABLastNameProperty) as! String? ?? ""
let emailsProperty = person.valueForProperty(kABEmailProperty) as! ABMultiValue?
foundPeople++
var tmpFirstName = firstName
var booleanFName = tmpFirstName.isEqualToString(firstName)
if let emails = emailsProperty {
for i in 0..<emails.count() {
let email = emails.valueAtIndex(i) as! String
var emailType = ABLocalizedPropertyOrLabel(emails.labelAtIndex(i)) //telefono numerio tipas
if (booleanFName) {
personNo++
if (personNo == 1) { // first person
dataArray = [["personCell": "\(firstName) \(middleName) \(lastName)", "emailCell": "\(email) (\(emailType))"]]
} else {
dataArray += [["personCell": "\(firstName) \(middleName) \(lastName)", "emailCell": "\(email) (\(emailType))"]]
} // end if personNo
println("\n• \(personNo) \(firstName) \(middleName) \(lastName)")
println("\t\t\(email) (\(emailType))")
booleanFName = false
} else {
dataArray += [["emailCell": "\(email) (\(emailType))"]]
println("\t\t\(email) (\(emailType))")
} // end booleanFName
} // end for i
} // end if let emails
} // end for person in found
} // end for word
return dataArray;
} // end func