Swift電話本ツール類

6168 ワード

//
//  AddressBookUtils.swift
//  ArtCircle
//
//  Created by wupeng on 15/12/15.
//
//
import UIKit
import AddressBook
import Contacts
class AddressBookUtils: NSObject {
    @available(iOS 8.0, *)
    static func getSysContacts() -> [[String:String]] {
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        
        if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined {
            // Need to ask for authorization
            //            var error:Unmanaged<CFError>?
//            let addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
//            let authorizedSingal:dispatch_semaphore_t = dispatch_semaphore_create(0)
//            let askAuthorization:ABAddressBookRequestAccessCompletionHandler = { success, error in
//                if success {
//                    ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
//                    dispatch_semaphore_signal(authorizedSingal)
//                }
//            }
//            ABAddressBookRequestAccessWithCompletion(addressBook, askAuthorization)
//            dispatch_semaphore_wait(authorizedSingal, DISPATCH_TIME_FOREVER)
            return []
        } else {
            return AddressBookUtils.analyzeSysContacts( ABAddressBookCopyArrayOfAllPeople(ABAddressBookCreate().takeRetainedValue()).takeUnretainedValue() as NSArray )
        }
    }
    @available(iOS 8.0, *)
    static func analyzeSysContacts(sysContacts:NSArray) -> [[String:String]] {
        var allContacts:Array = [[String:String]]()
        for contact in sysContacts {
            var currentContact:Dictionary = [String:String]()
            //  
            var firstName = ""
            let tempFirstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as? String
            if tempFirstName != nil {
                firstName = tempFirstName!
            }
//             
            var lastName = ""
            let tempLastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as? String
            if tempLastName != nil {
                lastName = tempLastName!
            }
            //  
            let tempPhone = ABRecordCopyValue(contact, kABPersonPhoneProperty).takeRetainedValue() as? ABMultiValueRef
            let phone = ABMultiValueCopyValueAtIndex(tempPhone,0).takeRetainedValue() as? String
            currentContact["\(firstName)\(lastName)"] = phone
            allContacts.append(currentContact)
        }
        return allContacts
    }
//    IOS9 contact
    @available(iOS 9.0, *)
    static func getContacts() -> [CNContact] {
        let status = CNContactStore.authorizationStatusForEntityType(.Contacts)
        if status == CNAuthorizationStatus.Denied || status == CNAuthorizationStatus.NotDetermined {
//             
            return [CNContact]()
        } else {
            let store = CNContactStore()
            let keysToFetch =  [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey]
            let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)
            var contacts = [CNContact]()
            do {
                try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
                    contacts.append(contact)
                })
            }
            catch let error as NSError {
                print(error.localizedDescription)
            }
            return contacts
        }
    }
    static func uploadContacts(withSuccessHandler handler:( (value:AnyObject) -> Void )) {
        var params:Dictionary<String,String> = Dictionary()
        params["contact"] = AddressBookUtils.generateUploadContactString()
        NetworkUtils.postRequest(GetUrlUtils.getUrlUploadContacts(), parameters: params, successHandler: { response in
            handler(value: response.result.value!)
            }) { response in
                
        }
    }
    static func generateUploadContactString() -> String {
        var uploadParamsString = ""
        if #available(iOS 9.0, *) {
            let contacts = AddressBookUtils.getContacts()
            for (_,object) in contacts.enumerate() {
                let contact = object 
                let userName = "\(contact.givenName)\(contact.familyName)"
                var userNameEncode = StringUtils.URLEncodedString(userName)
                for number in contact.phoneNumbers {
                    let phoneNumber = number.value as! CNPhoneNumber
                    userNameEncode = userNameEncode?.stringByAppendingString(":")
                    let phoneNum = phoneNumber.stringValue.stringByReplacingOccurrencesOfString("-", withString: "")
                    userNameEncode = userNameEncode?.stringByAppendingString(phoneNum)
                    userNameEncode = userNameEncode?.stringByAppendingString(";")
                }
                uploadParamsString = uploadParamsString.stringByAppendingString(userNameEncode!)
            }
        } else {
            // Fallback on earlier versions
            let contacts = AddressBookUtils.getSysContacts()
            for dict in contacts {
                for (name,phone) in dict {
                    let fullName = name
                    let phoneNumber = phone
                    var userNameEncode = fullName.URLEncodedString()
                    userNameEncode = userNameEncode!.stringByAppendingString(":")
                    let phoneNum = phoneNumber.stringByReplacingOccurrencesOfString("-", withString: "")
                    userNameEncode = userNameEncode!.stringByAppendingString(phoneNum)
                    userNameEncode = userNameEncode!.stringByAppendingString(";")
                    uploadParamsString = uploadParamsString.stringByAppendingString(userNameEncode!)
                }
            }
        }
        return  uploadParamsString
    }
}