CNContactVCardSerialization.dataWithContacts giving exception - ios

I'm trying to convert a CNContact array to vCard using the method CNContactVCardSerialization.dataWithContacts(). But it is giving me the following error.
2016-07-25 14:05:00.115 AddressBook-ios9[902:28918] Exception writing contacts to vCard (data): A property was not requested when contact was fetched.
I made sure that I'm passing an valid array of CNContacts, but still it is giving this exception. Can anybody guide to me to what I've done wrong?
I'm attaching the source code below.
func getVcardFromSearchingName(name: String) -> NSData? {
do {
if let contacts = searchMultiContacts(name) {
print(contacts)
let vCard = try CNContactVCardSerialization.dataWithContacts(contacts)
return vCard
} else {
return nil
}
} catch {
return nil
}
}

I found out my mistake. On the keys to fetch contact, I was missing CNContactVCardSerialization.descriptorForRequiredKeys(). After adding it, the code is working flawlessly.

Related

Swift: how to detect the error type using the debugger?

I'm new in iOS development, so maybe I'm thinking in the wrong way. I coded a view model with a function that calls an API, and everything works fine.
class SearchCityViewModel : ViewModelProtocol {
//OBSERVABLES
var cities = PublishSubject<[City]>()
var networkError = PublishSubject<Void>()
var generalError = PublishSubject<Void>()
init(){
print("Init SearchCityViewModel")
reinit()
}
func reinit(){}
func searchCity(stringToSearch: String){
async {
do {
if stringToSearch.count>=2 {
let cities = try await(api.getCities(cityToSearch: stringToSearch)).payload!
self.cities.onNext(cities)
}
else {
self.cities.onNext([])
}
}
catch {
self.generalError.onNext(Void())
}
}
}
Now I want to handle errors. In the catch block I want to distinguish all the errors I want to handle gracefully, and for the other ones I just want to emit a general error. To do that, firstly I need to know which error is thrown when the situation I want to handle occurs. I usually do this with the debugger. For instance, I disable the internet connection, and i create a breakpoint inside the catch block. The idea is to check which error is thrown when the internet connection is disabled, in order to create a catch block for that kind of error.
Image of the debugger
I'm struggling because with the debugger I only see that is an AFError instance, but it's not telling me nothing more that can help me to catch it.
What is wrong with my workflow? Do I really need to read all the docs every time? For each library I use?
Thank you!
Perhaps you can read the articles and then you will know how to do it better, you can use the framework -oslog instead of using print function.
debugging your logging info
I found the way. What I was missing is casting the error as NSError. In this way, with the debugger is possible to see the domain and the code of the error. In the case of Alamofire, the real error is wrapped, and it's accessible through the underlyingError attribute. Once I had the domain and the code of the error, I wrote the following code:
class SearchCityViewModel : ViewModelProtocol {
//OBSERVABLES
var cities = PublishSubject<[City]>()
var networkError = PublishSubject<Void>()
var generalError = PublishSubject<Void>()
init(){
print("Init SearchCityViewModel")
reinit()
}
func reinit(){}
func searchCity(stringToSearch: String){
async {
do {
if stringToSearch.count>=2 {
let cities = try await(api.getCities(cityToSearch: stringToSearch)).payload!
self.cities.onNext(cities)
}
else {
self.cities.onNext([])
}
}
catch {
if let afError = asAFError, let underlyingError = afError.underlyingError as NSError?, underlyingError.domain == NSURLErrorDomain, underlyingError.code == NSURLErrorNotConnectedToInternet || underlyingError.code == NSURLErrorTimedOut {
self.networkError.onNext(Void())
}
else {
self.generalError.onNext(Void())
}
}
}
}

Ios Swift Place Photo with google places sdk

I want to show the first photo of the place with the geo-coordinates from google API but I am not getting any proper way. But what I got is https://developers.google.com/places/ios-api/photos now this needs Place-id I am even unable to find place-id with geo-coordinates. Can anyone tell me how can I extract photos of the place with geo-coordinate? Any Help would be appreciated.
You should first search first for the place with the API.
The response contains an 'placeID', now you can use this ID in your 2nd request.
try this
func loadFirstPhotoForPlace(placeID: String) {
GMSPlacesClient.shared().lookUpPhotos(forPlaceID: placeID) { (photos, error) -> Void in
if let error = error {
// TODO: handle the error.
print("Error: \(error.localizedDescription)")
} else {
if let firstPhoto = photos?.results.first {
self.loadImageForMetadata(photoMetadata: firstPhoto)
}
}
}
}

iOS9 Contacts Framework get identifier from newly saved contact

I need the identifier of a newly created contact directly after the save request. The use case: Within my app a user creates a new contact and give them some attributes (eg. name, address ...) after that he can save the contact. This scenario is working as aspected. My code looks like this:
func createContact(uiContact: Contact, withImage image:UIImage?, completion: String -> Void)
{
let contactToSave = uiContact.mapToCNContact(CNContact()) as! Cnmutablecontawctlet
if let newImage = image
{
contactToSave.imageData = UIImageJPEGRepresentation(newImage, 1.0)
}
request = CNSaveRequest()
request.addContact(contactToSave, toContainerWithIdentifier: nil)
do
{
try self.contactStore.executeSaveRequest(request)
print("Successfully saved the CNContact")
completion(contactToSave.identifier)
}
catch let error
{
print("CNContact saving faild: \(error)")
completion(nil)
}
}
The Contact Object (uiContact) is just an wrapper of CNContact.
In the closure completion I need to return the identifier but on this time I have no access to them, because he is creating by the system after the write process.
One solution could be to fetch the newly saved CNContact with predicate
public func unifiedContactsMatchingPredicate(predicate: NSPredicate, keysToFetch keys: [CNKeyDescriptor]) throws -> [CNContact]
but this seems to me like a bit unclean because this contact could have only a name and more than one could exist. Something like a callback with the created identifier would be nice. But there isnĀ“t.
Is there a other way to solve this problem?
This may be a little late but in case someone needs this.
By using the latest SDK (iOS 11), I was able to get the identifier just by:
NSError *error = nil;
saveReq = [[CNSaveRequest alloc] init];
[saveReq addContact:cnContact toContainerWithIdentifier:containerIdentifier];
if (![contactStore executeSaveRequest:saveReq error:&error]) {
NSLog(#"Failed to save, error: %#", error.localizedDescription);
}
else
{
if ([cnContact isKeyAvailable:CNContactIdentifierKey]) {
NSLog(#"identifier for new contact is: %#", cnContact.identifier);
// this works for me everytime
} else {
NSLog(#"CNContact identifier still isn't available after saving to address book");
}
}
swift 4
This is the way to get contact id when creating contact
do {
try store.execute(saveRequest)
if contactToAdd.isKeyAvailable(CNContactIdentifierKey) {
print(contactToAdd.identifier) // here you are getting identifire
}
}
catch {
print(error)
}

Parse iOS - How to capture the findObjects() error being thrown?

I am coding in Swift and attempting to use the findObjects() function for the Parse iOS SDK. However, I can't seem to figure out what type of error is being thrown by Parse if this function call fails. I'm a novice in Swift so that may be my issue. I attempt to call the function in a do->catch block and use the try keyword on the function call however I'm not sure what to catch. I can catch the error using the _ but I would like to grab the description from the error. Thanks!
P.S. I don't want to use the findObjectsInBackground() method.
do {
let object = try query.getFirstObject()
// do something with the object
} catch _ {
// this is where I would like to print out the error description
}
In Obj-C, which I assume will be similar, I print out the error.userInfo[#"error"] parameter of the NSError that is returned.
All you need is print(error). An example here:
func getReferenceNumberAsStringSync() -> String? {
let query = PFQuery(className: "PropertyCount")
do {
let object = try query.getFirstObject()
if let referenceNumber = object["count"] as? Int {
return String(referenceNumber)
}
} catch {
print(error)
}
return nil
}

Delete duplicated object in core data (swift)

I'm saving objects to core data from a JSON, which I get using a for loop (let's say I called this setup function.
Because the user might stop this loop, the objects saved in core data will be partial. The user can restart this setup function, restarting the parsing and the procedure to save object to core data.
Now, I'm getting duplicated objects in core data if I restart the setup().
The object has an attribute which is id.
I've thought I could fetch first objects that could eventually already exist in core data, save them to an array (a custom type one), and test for each new object to add to core data if already exist one with the same id.
The code used is the following:
if !existingCards.isEmpty {
for existingCard in existingCards {
if id == existingCard.id {
moc.deleteObject(existingCard)
println("DELETED \(existingCard.name)")
}
}
}
...
// "existingCards is the array of object fetched previously.
// Code to save the object to core data.
Actually, the app return
EXC_BAD_ACCESS(code=1, address Ox0)
Is there an easier way to achieve my purpose or what should I fix to make my code work? I'm quite new to swift and I can't figure other solution.
The main purpose is to delete duplicated core data, BTW.
Swift 4 code to delete duplicate object:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Card")
var resultsArr:[Card] = []
do {
resultsArr = try (mainManagedObjectContext!.fetch(fetchRequest) as! [Card])
} catch {
let fetchError = error as NSError
print(fetchError)
}
if resultsArr.count > 0 {
for x in resultsArr {
if x.id == id {
print("already exist")
mainManagedObjectContext.deleteObject(x)
}
}
}
At the end, I managed to make it work.
I had to rewrite my code, because I realized moc.deleteObject() works with a fetch before, which in my previous code wasn't in the same function, but it was in viewDidLoad().
// DO: - Fetch existing cards
var error: NSError?
var fetchRequest = NSFetchRequest(entityName: "Card")
if let results = moc.executeFetchRequest(fetchRequest, error: &error) as? [Card] {
if !results.isEmpty {
for x in results {
if x.id == id {
println("already exist")
moc.deleteObject(x)
}
}
}
} else {
println(error)
}
No more existingCards, the result of the the fetch is now processed as soon as possible. Something isn't clear to me yet, but now my code works. If you have any improvements/better ways, they're welcome.
P.S.: I actually found Apple reference useful but hard to understand because I don't know Obj-C. Often I can figure what the code do, but in swift functions and properties are a bit different.

Resources