我对Swift非常陌生。我有以下代码可以完美运行。即我正在从PhoneBook获取联系人并成功更新到sqlite。
我的要求
我想在后台运行代码,即在我的下面的代码中,我正在做的是在电话簿中添加/删除某些联系人时我正在更新sqlite。这个功能一直是我想要的。它应该始终在后台运行。
这是我的代码
func getContactNames()
{
if !self.determineStatus()
{
print("not authorized")
return
}
let contactList: NSArray = ABAddressBookCopyArrayOfAllPeople(adbk).takeRetainedValue()
print("records in the array \(contactList.count)")
var firstName : String = String()
var contactNumber : String = String()
var lastName : String = String()
var email : String = String()
var fullName : String = String()
let db = ContactsDBModel.sharedInstance()
var contacts : [ContactsModel!]?
contacts = db.selectAllFromContact()
print(contacts?.count)
if contacts?.count != contactList.count
{
db.deleteAllFromContact()
for record:ABRecordRef in contactList
{
if (ABRecordCopyValue(record,
kABPersonPhoneProperty) != nil)
{
if (ABRecordCopyValue(record,
kABPersonFirstNameProperty) != nil)
{
firstName = (ABRecordCopyValue(record, kABPersonFirstNameProperty)?.takeRetainedValue() as? String)!
let numbers:ABMultiValue = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue()
contactNumber = (ABMultiValueCopyValueAtIndex(numbers,0)?.takeRetainedValue() as? String)!
// print("first name =\(firstName)")
// print("contact number=\(contactNumber)")
if (ABRecordCopyValue(record,
kABPersonLastNameProperty) != nil)
{
lastName = (ABRecordCopyValue(record,
kABPersonLastNameProperty).takeRetainedValue()as? String)!
// print("last name =\(lastName)")
}
let emails: ABMultiValueRef = ABRecordCopyValue(record, kABPersonEmailProperty).takeRetainedValue()
for (var i = 0; i < ABMultiValueGetCount(emails); i++)
{
email = ABMultiValueCopyValueAtIndex(emails, i).takeRetainedValue() as! String
// print("email of person=\(email)")
}
}
}
fullName = firstName + lastName;
lastName = "";
print("fullName of person=\(fullName)")
print("email of person=\(email)")
print("contact number=\(contactNumber)")
db.insertIntoContact(contactNumber: contactNumber, contactName: fullName, contactEmail: email)
}
contacts = db.selectAllFromContact()
print(contacts?.count)
}
print(contacts?.count)
}
上面的代码我想在后台运行。
更新
viewDidLoad中
override func viewDidLoad()
{
super.viewDidLoad()
var emptyDictionary: CFDictionaryRef?
var addressBook: ABAddressBookRef?
func extractABAddressBookRef(abRef: Unmanaged<ABAddressBookRef>!) -> ABAddressBookRef?
{
if let ab = abRef
{
return Unmanaged<NSObject>.fromOpaque(ab.toOpaque()).takeUnretainedValue()
}
return nil
}
if (ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.NotDetermined)
{
print("requesting access...")
var errorRef: Unmanaged<CFError>? = nil
addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
if success {
self.getContactNames()
}
else
{
print("error")
}
})
}
else if (ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.Denied || ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.Restricted)
{
print("access denied")
}
else if (ABAddressBookGetAuthorizationStatus() == ABAuthorizationStatus.Authorized)
{
print("access granted")
getContactNames()
}
}
dispatch_async
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
我听说过使用dispatch_async我们可以在后台运行代码。但是在哪里放上我的代码?情景是什么?
答案 0 :(得分:1)
我们可以使用dispatch_async 例如,这是下载一些图像并存储在后台的UserDefaults中
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
let imageData = NSData(contentsOfURL: NSURL(string: thankYouImageURL)!)
if let data = imageData {
print("Success Thanks Image")
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "registerThanksImage")
}else{
print("failure thanks image")
}
}
一般语法
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
// do background task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
答案 1 :(得分:1)
Swift中的语法糖用于Grand Central Dispatch中的异步调度。您可以在此处找到它:https://github.com/duemunk/Async
在后台运行代码非常容易。
就像这样:
Async.background {
println("This is run on the background queue")
}.main {
println("This is run on the main queue, after the previous block")
}