2016-12-23 30 views
-5

如何將所有聯繫人電話號碼都放入數組中?我需要這個,將數組發送到我的服務器/數據庫來檢查數據庫中是否存在一個或多個數字。我如何將所有聯繫人的電話號碼存入數組?

我仍然迅速2工作,後來還與SWIFT 3.

此代碼的工作,但我認爲,它有一個更美好的版本。你可以幫我嗎?

感謝您的支持。

 // With help: http://stackoverflow.com/questions/37039103/how-to-fetch-only-mobile-numbers-in-swift-using-cncontacts 
    // With help: http://stackoverflow.com/questions/32669612/how-to-fetch-all-contacts-record-in-ios-9-using-contacts-framework/34095632 

    let store = CNContactStore() 

    store.requestAccessForEntityType(.Contacts, completionHandler: { 
     granted, error in 

     guard granted else { 
      let alert = UIAlertController(title: "Can't access contact", message: "Please go to Settings -> MyApp to enable contact permission", preferredStyle: .Alert) 
      alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) 
      self.presentViewController(alert, animated: true, completion: nil) 
      return 
     } 

     let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey] 
     let request = CNContactFetchRequest(keysToFetch: keysToFetch) 
     var cnContacts = [CNContact]() 

     do { 
      try store.enumerateContactsWithFetchRequest(request){ 
       (contact, cursor) -> Void in 
       cnContacts.append(contact) 
      } 
     } catch let error { 
      NSLog("Fetch contact error: \(error)") 
     } 


     var mobilenumbers: [String] = [] 


     NSLog(">>>> Contact list:") 
     for contact in cnContacts { 
      let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "No Name" 
      NSLog("\(fullName): \(contact.phoneNumbers.description)") 




      // If phoneNo a Mobilenumber, then put into Array: 
      for phoneNo in contact.phoneNumbers { 
       if phoneNo.label == CNLabelPhoneNumberMobile { 
        let istEineMobileNummer = (phoneNo.value as! CNPhoneNumber).stringValue 


         mobilenumbers.append(istEineMobileNummer) 

       } 
      } 


     } 

     print("Print all Mobilenumbers:") 
     print(mobilenumbers) 


    }) 

回答

1

您可以嘗試使用Contacts Framework來做到這一點。

在訪問此信息之前,您需要徵求用戶的許可。

+0

感謝您的回答。上面我添加了一個示例代碼,可以工作。但我認爲,這個代碼還不夠完美...... – Andi

相關問題