ios开发——实用技术篇Swift篇&地址薄、短信、邮件

     //返回按钮事件
     @IBAction func backButtonClick()
     {
         self.navigationController?.popViewControllerAnimated(true)
     }

     //新增联系人
     @IBAction func addPeople ()
     {
         //取得电话薄句柄
         var error:Unmanaged<CFError>?
         var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

         var newContact:ABRecordRef! = ABPersonCreate().takeRetainedValue()
         var success:Bool = false

         //昵称
         success = ABRecordSetValue(newContact, kABPersonNicknameProperty, "Gaven", &error)
         println("设置昵称是否成功: \(success)")

         //设置姓
         success = ABRecordSetValue(newContact, kABPersonFirstNameProperty, "zhang", &error)
         println("设置姓是否成功: \(success)")

         //设置名
         success = ABRecordSetValue(newContact, kABPersonLastNameProperty, "wu", &error)
         println("设置名是否成功:\(success)")

         //添加电话
         let tmpMutableMultiPhones:ABMutableMultiValue = ABMultiValueCreateMutable(
             ABPropertyType(kABStringPropertyType)).takeRetainedValue()

         success = ABMultiValueAddValueAndLabel(tmpMutableMultiPhones, ", "companyPhone", nil);
         println("设置电话标题是否成功:\(success)")

         success = ABRecordSetValue(newContact, kABPersonPhoneProperty, tmpMutableMultiPhones, nil)
         println("设置电话是否成功:\(success)")

         //添加邮箱
         let addr:ABMutableMultiValue = ABMultiValueCreateMutable(
             ABPropertyType(kABStringPropertyType)).takeRetainedValue()
         ABMultiValueAddValueAndLabel(addr, "185@leadingdo.com", "companyEmail", nil)
         println("设置邮箱标题是否成功:\(success)")

         ABRecordSetValue(newContact, kABPersonEmailProperty, addr, nil)
         println("设置邮箱是否成功:\(success)")

         //保存记录
         success = ABAddressBookAddRecord(addressBook, newContact, &error)
         println("保存记录是否成功:? \(success)")

         //保存数据库
         success = ABAddressBookSave(addressBook, &error)
         println("修改数据库是否成功: \(success)")
     }

     //删除联系人
     @IBAction func deletePeople()
     {
         //定义错误标记
         var error:Unmanaged<CFError>?

         //取得电话薄句柄
         var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

         //读取通讯录
         let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()

         if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined {
             // Need to ask for authorization
             var authorizedSingal:dispatch_semaphore_t = dispatch_semaphore_create()
             var 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)
         }

         var sysContacts:NSArray  =  ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray

         //遍历通讯录
         for contact in sysContacts {
             var currentContact:Dictionary = [String:String]()

             // 姓
 //            var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""

             //2015年5月2号修改
             var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""

             println("姓:\(firstName)")

             // 名
 //            var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as String? ?? ""

              //2015年5月2号修改
             var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""

             println("名:\(lastName)")

             var success:Bool = false

             if firstName == "zhang" && lastName == "wu"
             {
                  success = ABAddressBookRemoveRecord(addressBook, contact, nil);
                 println("删除是否成功: \(success)")
             }

             //保存数据库
             success = ABAddressBookSave(addressBook, &error)
             println("修改数据库是否成功: \(success)")
         }
     }

     //代码获取地址薄
     @IBAction func codeToAddressButtonClick()
     {
         //定义错误标记
         var error:Unmanaged<CFError>?

         //取得电话薄句柄
         var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

         //发出授权信息,界面会弹出提示窗口
         let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()

         //获取电话薄
         if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined {
             // Need to ask for authorization
             var authorizedSingal:dispatch_semaphore_t = dispatch_semaphore_create()

             var askAuthorization:ABAddressBookRequestAccessCompletionHandler = { success, error in
                 if success {
                     //获取的联系人信息数组
                     var sysContacts:NSArray  = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray

                     //循环读取联系人
                     for contact in sysContacts {
                         var currentContact:Dictionary = [String:String]()

                         /*
                         部分单值属性
                         */
                         // 姓
 //                        var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""
                         println("姓:\(firstName)")

                         // 名
 //                        var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""
                         println("名:\(lastName)")

                         // 昵称
 //                        var nikename = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var nikename = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as! String? ?? ""

                         println("昵称:\(nikename)")

                         // 公司(组织)
 //                        var  organization = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var  organization = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as! String? ?? ""
                         println("公司(组织):\(organization)")

                         // 职位
 //                        var jobTitle = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var jobTitle = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as! String? ?? ""

                         println("职位:\(jobTitle)")

                         // 部门
 //                        var department = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var department = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as! String? ?? ""

                         println("部门:\(department)")

                         //备注
 //                        var note = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as String? ?? ""

                         //2015年5月2号修改
                         var note = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as! String? ?? ""

                         println("备注:\(note)")

                         /*
                         部分多值属性
                         */
                         // 电话
                         var propertyValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonPhoneProperty)?.takeRetainedValue()

                         if propertyValues != nil {

                              ..< ABMultiValueGetCount(propertyValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(propertyValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(propertyValues, i)
                                 var phone = value.takeRetainedValue() as? String ?? ""

                                 println("\(label):\(phone)");
                             }
                         }

                         // E-mail
                         var emailValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonEmailProperty)?.takeRetainedValue()

                         if emailValues != nil {

                              ..< ABMultiValueGetCount(emailValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(emailValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(emailValues, i)
                                 var email = value.takeRetainedValue() as? String ?? ""

                                 println("\(label):\(email)");
                             }
                         }

                         // 地址
                         var addressValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonAddressProperty)?.takeRetainedValue()

                         if addressValues != nil {

                              ..< ABMultiValueGetCount(addressValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(addressValues, i).takeRetainedValue() as String

 //                                var value = ABMultiValueCopyValueAtIndex(addressValues, i)
 //                                var addrNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
 //
 //                                var _Country = addrNSDict.valueForKey(kABPersonAddressCountryKey) as? String ?? ""
 //                                var _State = addrNSDict.valueForKey(kABPersonAddressStateKey) as? String ?? ""
 //                                var _City  = addrNSDict.valueForKey(kABPersonAddressCityKey) as? String ?? ""
 //                                var _Street = addrNSDict.valueForKey(kABPersonAddressStreetKey) as? String ?? ""
 //                                var _Contrycode = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey) as? String ?? ""

                                 //2015年5月2号修改
                                 var value = ABMultiValueCopyValueAtIndex(addressValues, i)
                                 var addrNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary

                                 var _Country = addrNSDict.valueForKey(kABPersonAddressCountryKey as String) as? String ?? ""
                                 var _State = addrNSDict.valueForKey(kABPersonAddressStateKey as String) as? String ?? ""
                                 var _City  = addrNSDict.valueForKey(kABPersonAddressCityKey as String) as? String ?? ""
                                 var _Street = addrNSDict.valueForKey(kABPersonAddressStreetKey as String) as? String ?? ""
                                 var _Contrycode = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey as String) as? String ?? ""

                                 //或
 //                                var _Country = ""
 //                                var _State = ""
 //                                var _City  = ""
 //                                var _Street = ""
 //                                var _Contrycode = ""
 //
 //                                if let value:String = addrNSDict.valueForKey(kABPersonAddressCountryKey as String) as? String
 //                                {
 //                                    _Country = value
 //                                }
 //
 //                                if let value:String = addrNSDict.valueForKey(kABPersonAddressStateKey as String) as? String
 //                                {
 //                                    _State = value
 //                                }
 //
 //                                if let value:String = addrNSDict.valueForKey(kABPersonAddressCityKey as String) as? String
 //                                {
 //                                    _City = value
 //                                }
 //
 //                                if let value:String = addrNSDict.valueForKey(kABPersonAddressStreetKey as String) as? String
 //                                {
 //                                    _Street = value
 //                                }
 //
 //                                if let value:String = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey as String) as? String
 //                                {
 //                                    _Contrycode = value
 //                                }

                                 println("\(label)==_Country:\(_Country) _State:\(_State) _City:\(_City) _Street:\(_Street) _Contrycode:\(_Contrycode)");
                             }
                         }

                         // 纪念日
                         var dateValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonDateProperty)?.takeRetainedValue()

                         if dateValues != nil {

                              ..< ABMultiValueGetCount(dateValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(dateValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(dateValues, i)
                                 var date = (value.takeRetainedValue() as? NSDate)?.description

                                 println("\(label):\(date)");
                             }
                         }

                         // URL
                         var urlValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonURLProperty)?.takeRetainedValue()

                         if urlValues != nil {

                              ..< ABMultiValueGetCount(urlValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(urlValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(urlValues, i)
                                 var url = value.takeRetainedValue() as? String ?? ""

                                 println("\(label):\(url)");
                             }
                         }

                         // SNS
                         var snsValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonSocialProfileProperty)?.takeRetainedValue()

                         if snsValues != nil {

                              ..< ABMultiValueGetCount(snsValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(snsValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(snsValues, i)
 //                                var snsNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
 //                                var _Username = snsNSDict.valueForKey(kABPersonSocialProfileUsernameKey) as? String ?? ""
 //                                var _URL = snsNSDict.valueForKey(kABPersonSocialProfileURLKey) as? String ?? ""
 //                                var _Serves = snsNSDict.valueForKey(kABPersonSocialProfileServiceKey) as? String ?? ""

                                 //2015年5月2后修改
                                 var snsNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary

                                 var _Username = snsNSDict.valueForKey(kABPersonSocialProfileUsernameKey as String) as? String ?? ""
                                 var _URL = snsNSDict.valueForKey(kABPersonSocialProfileURLKey as String) as? String ?? ""
                                 var _Serves = snsNSDict.valueForKey(kABPersonSocialProfileServiceKey as String) as? String ?? ""

                                 println("\(label)==_Username:\(_Username) _URL:\(_URL) _Serves:\(_Serves)");
                             }
                         }

                         // IM
                         var imValues:ABMultiValueRef? = ABRecordCopyValue(contact, kABPersonInstantMessageProperty)?.takeRetainedValue()

                         if imValues != nil {

                              ..< ABMultiValueGetCount(imValues)
                             {
                                 var label:String = ABMultiValueCopyLabelAtIndex(imValues, i).takeRetainedValue() as String

                                 var value = ABMultiValueCopyValueAtIndex(imValues, i)
 //                                var imNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
 //                                var _Serves = imNSDict.valueForKey(kABPersonInstantMessageServiceKey) as? String ?? ""
 //                                var _Username = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey) as? String ?? ""

                                 //2015年5月2后修改
                                 var imNSDict:NSMutableDictionary = value.takeRetainedValue() as! NSMutableDictionary

                                 var _Serves = imNSDict.valueForKey(kABPersonInstantMessageServiceKey as String) as? String ?? ""
                                 var _Username = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey as String) as? String ?? ""

                                 println("\(label)==_Serves:\(_Serves) _Username:\(_Username)");
                             }
                         }
                     }

                     dispatch_semaphore_signal(authorizedSingal)
                 }
             }

             ABAddressBookRequestAccessWithCompletion(addressBook, askAuthorization)
             dispatch_semaphore_wait(authorizedSingal, DISPATCH_TIME_FOREVER)
         }
     }

     //UI打开地址薄
     @IBAction func uiToAddressButtonClick()
     {
         var picker = ABPeoplePickerNavigationController()
         picker.peoplePickerDelegate = self
         self.presentViewController(picker, animated: true, completion: { () -> Void in

         })
     }

     // MARK: - ABPeoplePickerNavigationControllerDelegate
     func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!)
     {
         // 姓
 //        var firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""

         //2015年5月2号修改
         var firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""

         println("选中人的姓:\(firstName)")

         // 名
 //        var lastName = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as String? ?? ""

         //2015年5月2号修改
         var lastName = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""

         println("选中人的名:\(lastName)")
     }

     func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecord!, property: ABPropertyID, identifier: ABMultiValueIdentifier)
     {

     }

     func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController!)
     {
         //取消
         peoplePicker.dismissViewControllerAnimated(true, completion: { () -> Void in

         })
     }

     func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, shouldContinueAfterSelectingPerson person: ABRecord!) -> Bool
     {
         return true
     }

     func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, shouldContinueAfterSelectingPerson person: ABRecord!, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool
     {

         return true
     }

     //发短信
     //    添加MessageUI.framework框架
     //
     //    为ViewController类
     //    添加UINavigationControllerDelegate, MFMessageComposeViewControllerDelegate 接口
     //    实现func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult)
     @IBAction func sendSMSButtonClick()
     {
         //判断
         if MFMessageComposeViewController.canSendText(){
             let controller = MFMessageComposeViewController()

             // 设置短信内容
             controller.body = "短信内容短信内容"

             // 设置收件人列表
             controller.recipients = ["15900001111,18900001111,17011112222"]

             //设置代理
             controller.messageComposeDelegate = self

             //打开界面
             self.presentViewController(controller, animated: true, completion: nil)
         } else {
             let alert = UIAlertView(title: "提示信息", message: "本设备不能发短信", delegate: nil, cancelButtonTitle: "确定")
             alert.show()
         }
     }

     //代理
     func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {

         controller.dismissViewControllerAnimated(true, completion: nil)

         switch result.value{
         case MessageComposeResultSent.value:
             println("短信已发送")
         case MessageComposeResultCancelled.value:
             println("短信已取消")
         case MessageComposeResultFailed.value:
             println("短信发送失败")
         default:
             break
         }
     }

     //打电话
     @IBAction func phoneButtonClick()
     {
         //调用打电话功能--最简单最直接的方式:直接跳到拨号界面
         UIApplication.sharedApplication().openURL(NSURL(string: "tel://10086")!)

     }

 //    该实例说明了如何使用MessageUI框架组成并在程序内部发送邮件和短信。
 //
 //    该应用使用MessageUI框架的MFMailComposeViewController类和MFMessageComposeViewController类,这两个类分别管理用户界面并充许用户在程序内部集成发送邮件和短信。
 //
 //    该实例显示两个按钮,一个为“发送邮件”,另一个为“发送短信”。
 //
 //    当用户单击“发送邮件”与“发送短信”时,应用分别显示集成的邮件集成界面与短信集成界面。
 //
 //    应用不但检查它们的集成界面是否存在,还检查设备是否已经配置为了可以发送邮件和短信。另处,它提供了反馈消息。

 //    MFMailComposeViewControllerDelegate

     //发邮件
     @IBAction func sendEmailButtonClick()
     {
         if MFMailComposeViewController.canSendMail()
         {
             var picker = MFMailComposeViewController()
             picker.mailComposeDelegate = self

             //设置主题
             picker.setSubject("这是一个主题")

             //设置发件人
             picker.setToRecipients(["1@leadingdo.com","2@leadingdo.com","3@leadingdo.com"])

             //设置抄送人
             picker.setCcRecipients(["cc1@leadingdo.com","cc2@leadingdo.com"])

             //设置密送人
             picker.setBccRecipients(["bcc@leadingdo.com"])

             //添加图片附件
             var path = NSBundle.mainBundle().pathForResource("SwiftClassWeiXin.png", ofType: "")
             var myData = NSData(contentsOfFile: path!)
             picker.addAttachmentData(myData, mimeType: "image/png", fileName: "swift.png")

             //设置邮件正文内容-支持html
             picker.setMessageBody("这是邮件正文", isHTML: false)

             //打开界面
             self.presentViewController(picker, animated: true, completion: nil)
         }
         else
         {
             let alert = UIAlertView(title: "提示信息", message: "本设备不能发邮件", delegate: nil, cancelButtonTitle: "确定")
             alert.show()
         }
     }

     //发送邮件代理方法
     func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!)
     {

         controller.dismissViewControllerAnimated(true, completion: nil)

         switch result.value{
             case MFMailComposeResultCancelled.value:
                 println("邮件已取消")
             break;
             case MFMailComposeResultSaved.value:
                 println("邮件已保存")
             break;
                 case MFMailComposeResultSent.value:
                 println("邮件已发送")
             break;
                 case MFMailComposeResultFailed.value:
                 println("邮件发送失败")
             break;
             default:
                 println("邮件没有发送")
             break;
         }
     }

     override func viewDidLoad() {
         super.viewDidLoad()

         if titleString != nil && titleString != ""{
             titleLabel.text = titleString
         }else{
             titleLabel.text = "第12章 地址薄、短信、邮件";
         }

         // Do any additional setup after loading the view.
     }
 
上一篇:Win10 安装 Linux子系统 Ubuntu18.04 / Kali Linux 的体验


下一篇:ios开发——实用技术篇Swift篇&拍照