I want to delete a row with the given value (contactID), which is also the primary key, in SQLite.Swift:
let delRowCo = ContactTable.filter(ContactID == contactID)
try db.run(delRowCo.delete())
The given contactID surely exists, but it doesn't delete the row ...
Try with some error handling. You'll catch if there are any errors.
do {
if try db.run(delRowCo.delete()) > 0 {
print("deleted")
} else {
print("row not found")
}
} catch {
print("delete failed: \(error)")
}
Try this too.
let mytable = Table("ContactTable")
let delRowCo = mytable.filter(ContactID == 'contact_id')
try db.run(delRowCo.delete())
Related
Not sure why i'm getting this.. any suggestions would be grateful!
I ran into issues with my original coding where I had Firebase pod and Firebase Package.. so I started from scratch since that wasnt fixing itself.. now I get this.. and I am at a loss for how to resolve it.
static func fetchUsers() -> AnyPublisher<[UserProfile], Error> {
Future< [UserProfile], Error > { promise in
self.db.collection("Users")
.getDocuments { (snapshot, error) in
if let error = error {
promise(.failure(error))
return
}
guard let snapshot = snapshot else {
promise(.failure(FirebaseError.badSnapshot))
return
}
var users = [UserProfile]()
snapshot.documents.forEach { document in
print(users.count)
if let user = try? document.data(as: UserProfile.self){
if users.contains(where: { $0.id == user.id}) {return}
users.append(user)
} else {
print("Not working")
}
}
promise(.success(users))
}
}
.eraseToAnyPublisher()
}
I believe this is the syntax you're after:
var users = [UserProfile]()
users = snapshot.documents.compactMap { (document) -> UserProfile? in
if users.contains(where: { $0.id == user.id}) {
return nil
} else {
return try? document.data(as: UserProfile.self)
}
}
Also be aware that when you iterate something in Swift and encounter a false condition on an iteration, return will return out of the greater scope, not just that iteration. Therefore, use continue.
for x in y {
guard x > 0 else {
continue // continues loop
}
// ...
}
I want to put an annotation on every grocery store within a specific area. I already have my mkmapview working and tracking my current location.
Thanks in advance!
Give it a try, unfortunately I'm not in situation to test it right now, but this piece of code should serve your requirement:
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "Groceries"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search:
\(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
for item in response!.mapItems {
print("Name = \(item.name)")
print("Phone = \(item.phoneNumber)")
}
}
})
I can't find a solution for the fact that the line with: "CNContactVCardSerialization" keeps throwing an error. Any ideas on what can be wrong here and/or how to fix it? Getting the array with CNContacts works ok.
let contactStore = CNContactStore()
var contacts = [CNContact]()
var vcardFromContacts = NSData()
let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])
do{
try contactStore.enumerateContacts(with: fetchRequest, usingBlock: {
contact, cursor in
contacts.append(contact)})
} catch {
print(">>>[ERROR] Unable to get contacts: \(error)")
}
// Returns the vCard representation of the specified contacts
print(">>>[INFO ] Number of contacts found: \(contacts.count)")
do {
try vcardFromContacts = CNContactVCardSerialization.data(with: contacts) as NSData
} catch {
print(">>>[ERROR] Unable to create Vcard information: \(error)")
}
I am trying to print out the value "username" from my coredata entity.
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
var results = context.executeFetchRequest(request, error: nil)
if (results?.count > 0) {
for result: AnyObject in results! {
println(result.username)
}
}
The line println(result.username) is giving me a compile error of 'AnyObject' does not have a member named 'username'.
You have to cast the array of managed object to the correct type:
for result in results! as [Users] {
println(result.username)
}
This assumes that you have created a managed object subclass for the "Users" entity.
You should also distinguish whether executeFetchRequest() returned nil
(i.e. the fetch request failed), or 0 (i.e. no objects found),
and use the error parameter:
var error : NSError?
if let results = context.executeFetchRequest(request, error: &error) {
if (results.count > 0) {
for result in results as [Users] {
println(result.username)
}
} else {
println("No Users")
}
} else {
println("Fetch failed: \(error)")
// Handle error ...
}
Update for Swift 2/Xcode 7 with try/catch error handling:
do {
let results = try context.executeFetchRequest(request) as! [Users]
if (results.count > 0) {
for result in results {
print(result.username)
}
} else {
print("No Users")
}
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
Note that the forced cast as! [Users] is acceptable here.
The returned objects are always instances of the corresponding class as configured in the Core Data model inspector, otherwise you have
a programming error which should be detected early.
Martin's answer definitely lets you access the properties of your object, but the cast is forced. Like it or not, Swift's strong type system is the future. When returning results from a fetch request, you might consider testing for the type.
func executeFetchRequestT<T:AnyObject>(request:NSFetchRequest, managedObjectContext:NSManagedObjectContext, error: NSErrorPointer = nil) -> [T]? {
var localError: NSError? = nil
if let results:[AnyObject] = managedObjectContext.executeFetchRequest(request, error: &localError) {
if results.count > 0 {
if results[0] is T {
let casted:[T] = results as [T]
return .Some(casted)
}
if error != nil {
error.memory = NSError(domain: "error_domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Object in fetched results is not the expected type."])
}
} else if 0 == results.count {
return [T]() // just return an empty array
}
}
if error != nil && localError != nil {
error.memory = localError!
}
return .None
}
Using this approach you can type your results and get an error if the type is incorrect.
var fetchError:NSError? = nil
if let results:[Users] = executeFetchRequestT(fetchRequest, managedObjectContext: managedObjectContext, error: &fetchError) {
for user in results {
// access the results with confidence of the correct type
}
} else {
// should have an error condition, handle it appropriately
assertFailure("something bad happened")
}
Change your for loop to this
for result: AnyObject in results! {
if let user: AnyObject = result.valueForKey("username") {
println(user)
}
}
The fix is using valueForKey("String")
I have a NSTokenField Where the tokens are created upon hitting enter. I would like to limit the number of tokens in this field. Say for example, User should be allowed to enter only 2 tokens one after the other. Later, neither user should be allowed to set the Token nor user should be allowed to search further. In short, User should be blocked after 2 tokens.
Could any one please help me in achieving this???
Thanks in advance :)
The solution is divided in 2 parts:
-(NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index
{
//limit the tokens
if(self.tokensLimit)
{
NSArray * tokensArray = [_tokenField objectValue];
if([tokensArray count] > 0)
{
if([tokens isEqualToArray:tokensArray])
{
return tokens;
}
else if([tokensArray count]>=self.tokensLimit)
{
return #[];
}
else if([tokens count]>0)
{
tokens = [tokens subarrayWithRange:NSMakeRange(0, MIN([tokens
count], self.tokensLimit))];
}
else
return #[];
}
else
{
tokens = [tokens subarrayWithRange:NSMakeRange(0, MIN([tokens count], self.tokensLimit))];
}
}
return tokens;
}
where tokensLimit is an int > 0
the delegate covers all the cases like tokens added by copy/paste, completion list, drag&drop, manually written etc..
this other delegate cover the case where the user write a string and hit "TAB"
- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
if(self.tokensLimit)
{
NSArray * tokensArray = [_tokenField objectValue];
tokensArray = [tokensArray subarrayWithRange:NSMakeRange(0, MIN([tokensArray count], self.tokensLimit))];
[_tokenField setObjectValue:tokensArray];
}
return YES;
}
If you save the tokens in a db, you can count the number of rows of the particular users id, and add an if statement to limit it to 2.
Behold:
var maximumTokens: Int = 2
func tokenField(_ tokenField: NSTokenField, shouldAdd tokens: [Any], at index: Int) -> [Any] {
var count = 0
if let textView = tokenField.currentEditor() as? NSTextView {
for scalar in textView.string.unicodeScalars {
if scalar.value == unichar(NSAttachmentCharacter) {
count += 1
}
}
}
return tokens.filter({ _ in
count += 1
return count <= maximimTokens
})
}
I've tested it and it works when you are typing tags or even copying & pasting them in.