Append string while saving it to attribute and remove while calling it - swift

I like to add "abc" to eventTextField.text and save it to the attributeeventName below
eventInformation.setValue(eventTextField.text, forKey: "eventName")
I tried this
let abcString = "abc"
eventInformation.setValue(eventTextField.text?.append(abcString), forKey: "eventName")
but my app is crashing with following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for
attribute: property = "eventName"; desired type = NSString; given type
= _SwiftValue; value = ().'

The error occurs because append is mutating but does not return anything,
that's the _SwiftValue; value = () (Void)
You need an extra step:
let abcString = "abc"
eventTextField.text?.append(abcString)
eventInformation.setValue(eventTextField.text, forKey: "eventName")

Related

How to get a list of files with shared-link using GoogleAPIClientForREST [Swift]

I am building an app where users can download files with Google Drive's shared-link.
Trying to get a list of files with shared folder link, but couldn't find any document explaining how to do that.
What I have tried so far
to use GoogleAPIClientForREST 'fetchObject'
googleDriveService.fetchObject(with: url, objectClass: nil, executionParameters: nil) { ticket, any, e in
print("thicket", ticket, any, e)
}
(where I tested with 'link' as https://drive.google.com/drive/folders/1EVHGkbGwlFAi16DhVG4ZoYEng6UQ7_Km?usp=sharing)
But it returns error below
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Got unexpected content type 'text/html; charset=utf-8''
to use GoogleAPIClientForREST 'query'
let query = GTLRDriveQuery_FilesList.query()
query.q = "'\(url)'"
query.spaces = "drive"
query.corpora = "user"
googleDriveService.executeQuery(query) { (_, result, error) in
}
Which returns 'Invalid query' error.
to use GoogleAPIClientForREST 'query' with fileID
guard let url = URL(string: text) else {
return
}
googleDriveService.executeQuery(GTLRDriveQuery_FilesGet.query(withFileId: url.lastPathComponent)) { ticket, any, e in }
Which again, returns below error.
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Got unexpected content type 'text/html; charset=utf-8''
Is it possible to do this with GoogleAPIClientForREST?
If not, what would be the alternate?
If I need to provide more details, I am happy to do so.
Thank you for your time.
Solved it by myself.
I could simply send query below using GoogleAPIClientForREST.
It returns a list of files!
let comps = sharedURL.components(separatedBy: "/")
guard let folderID = comps.last?.components(separatedBy: "?").first else {
failed()
return
}
let query = GTLRDriveQuery_FilesList.query()
query.q = "'\(folderID)' in parents"
query.spaces = "drive"
query.corpora = "allDrives"
query.includeItemsFromAllDrives = true
query.supportsAllDrives = true

saving data array causes crash swift

I tried adding an item to an arrar and saving in Userdefault but the app crashed and I would love anyone to point me to what I am doing wrong
private func putArray(_ value: GMSAutocompletePrediction?, forKey key: String) {
guard let value = value else {
return
}
log("THE MESSAGE \(value)", .fuck)
var newArray = getArray(forKey: key)
log("THE MESSAGE ARRAY \(newArray)", .fuck)
if newArray.contains(value) {
newArray.remove(at: newArray.firstIndex(of: value)!)
} else {
newArray.append(value)
}
storage.setValue(NSKeyedArchiver.archivedData(withRootObject: newArray), forKey: key)
}
error from crash
[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0
2019-09-26 13:40:07.300856+0100 MAX.NG Staging Debug[4440:1410011] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GMSAutocompletePrediction encodeWithCoder:]: unrecognized selector sent to instance 0x2818f9ce0'
GMSAutocompletePrediction doesn't conform to NSCoding so you can't save it to user defaults , you may extract important details from it and make a custom model to save

Ignore records in FirebaseDB with swift

Im working on a swift app that displays records from firebase to a table view controller.
I have successfully been pulling in all data, But I have since added another field to the DB called "secretKey".. This doesn't not need to be used on the table view as its used elsewhere in the app
But now each time I try to run the app I get the following errors
2018-05-07 12:24:24.616490+0100 Loop Guardian[21847:9857567] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTaggedPointerString 0xa030818c015ea1f9> valueForUndefinedKey:]: this class is not key value coding-compliant for the key createdAt.'
*** First throw call stack:
(0x18204b164 0x181294528 0x18204ae2c 0x1829fe434 0x182944e20 0x182944874 0x18297d930 0x1030084b0 0x103008740 0x1030f2840 0x1044892cc 0x10448928c 0x10448dea0 0x181ff3344 0x181ff0f20 0x181f10c58 0x183dbcf84 0x18b6695c4 0x10301de44 0x181a3056c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This only happens when the secretKey is present in the DB.. If I remove it the app works fine.
I somehow need to ignore this field
Heres the code used to pull the records from the DB
func observeMessages() {
let key = UserDefaults.standard.value(forKey: "uid") as! String
DBrefs.databaseMessages.child(key).observe(.value, with: { (snapshot) in
if snapshot.exists() {
let messageData = snapshot.value as! Dictionary<String, AnyObject>
self.dataArr = []
for (key,data) in messageData {
self.dataArr.append(data)
}
//THIS IS WHERE THE ERROR IS THROWN.. THREAD 1: SIGNAL SIGABRT
self.dataArr = (self.dataArr as NSArray).sortedArray(using: [NSSortDescriptor(key: "createdAt", ascending: true)]) as [AnyObject]
self.tblMessage.reloadData()
}
else {
}
})
}
Any help is appreciated
Thanks
Oliver
for (key,data) in messageData {
if (key == "secreyKey") {
continue;
}
self.dataArr.append(data)
}
Also use Swift method to sort the Array. Don't use NSArray use Array instead.
Like below code:
self.dataArr.sorted(by: {$0["createdAt"] as? Int64 ?? 0 < $1["createdAt"] as? Int64 ?? 0})

How to save an array of Tuple in swift3

I am trying to save an array of Tuple in UserDefaults. To do this I found on the internet that NSKeyedArchiver.archivedData can be use to convert the Tuple data into the NSData type. After conversion the tuple data can easily be saved in UserDefaults.
Below is the Tuple array which I want to save
[((Color:Color, ID:ID),(DefectType:Type,DefectCode:Code))]
but It gives me the below error
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[_SwiftValue
encodeWithCoder:]: unrecognized selector sent to instance 0x1702d47b0
Below is the code I am using
let DATA = ((Color:Color, ID:ID),(DefectType:Type,DefectCode:Code))
let ArchivedDATA = NSKeyedArchiver.archivedData(withRootObject: [DATA])
print("ArchivedDATA =",ArchivedDATA)
defaults.setValue(ArchivedDATA, forKeyPath: "\(self.CodeLabel.text!)")
if let data = defaults.object(forKey: "\(self.AuditCodeLabel.text!)") as? NSData{
SavedDefects = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? [((Color:UIColor, ID:String),(DefectType:String,DefectCode:String))]
print("dataUnarchived =",SavedDefects)
}
Please anyone help me to save tuple array into the UserDefaults.If I am going wrong, kindly tell me the proper way to save this.
Thank you

Adding contacts using swift file

I am trying to write a swift file that will create new contacts in my address book
import Contacts
let newContact = CNMutableContact()
newContact.givenName = "First"
newContact.familyName = "Last"
let number = CNPhoneNumber(stringValue: "(555) 555-5555")
newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberMobile, value: number)]
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.addContact(newContact, toContainerWithIdentifier:nil)
try store.executeSaveRequest(saveRequest)
When I run the file in terminal, it gives a very long error message, most of which is code that I don't understand. However, the first line says
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "fullNumber"; desired type = NSString; given type = CNPhoneNumber; value = .'
If I pass CNLabeledValue a String instead of a CNPhoneNumber like so
let number: NSString = "(555) 555-5555"
newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberMobile, value: number)]
it says this
*** Terminating app due to uncaught exception 'CNPropertyInvalidTypeException', reason: 'Labeled value !$_, value=(555) 555-5555> value (555) 555-5555 has incorrect type __NSCFString. It should be CNPhoneNumber.'
It's also worth noting that commenting out the final line
try store.executeSaveRequest(saveRequest)
Gets rid of the error, but of course does not add anything to my address book.
Needless to say, I am extremely confused