CoreData - Safely Check Value of CoreData Object - ios

The way I currently have my code arranged, the following line will run for various managed-object-contexts. Some of the fetched entities will have "complededDate" and others will not have a "completedDate" attribute.
let task = retrieved_MgObjCntxt[(indexPath as NSIndexPath).row]
if let itemFinDate = task.value(forKey: "completedDate") {
...
I thought by using if-let, that if this failed then it'd be okay... but I'm getting an "lldb" crash. I've been playing with trying to solve it using do/catch and throw but I'm not super familiar with how those work.
Is there a way to safely check so that if "completedDate" doesn't exist, it just skips the code within the if-closure??

let task = retrieved_MgObjCntxt[(indexPath as NSIndexPath).row]
if task.entity.propertiesByName.keys.contains("completeDate") {
...
}

You can find all the keys for you objects entity type by using:
managedObject.entity.attributesByName
And then see if that dictionary's keys contains "completedDate"

Related

Swift 4 - querying facebook with FBSDKGraphRequest

I try to create a function for querying the Facebook database. Unfortunately, the syntax changed with the last version of swift. Maybe someone can post me the solution ?
Thx.
Func donneesFB
It's a lot easier to help you if you post your code as text instead of in an image.
Two things that will likely help you out here:
First, cast your result to the type of dictionary you are expecting before trying to access it:
guard let resultDict = result as? [String:Any] else { return }
You should now be able to use it like you tried to:
let nom = resultDict["name"] as? String
Secondly, for the error on your first line, simply get rid of the argument labels, nom, prenom and so on, leaving just the types.

How to remove all data from DynamoDB without for loop?

Suppose i have 100 data in DynamoDB then to remove all data i have to execute for loop .So is there any way to remove all data without for loop ?
let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
for var key in 0 ..<100 {
let itemToDelete: CategoriesDB = CategoriesDB()
itemToDelete._index = key
dynamoDbObjectMapper.remove(itemToDelete, completionHandler:
{(error: Error?) -> Void in
if let error = error {
print(" Amazon DynamoDB Save Error: \(error)")
return
}
print("A Category was deleted.")
})
}
If you want to remove all the data in a DynamoDB table, it is better to just delete the table and create it again as that wouldn't cost Write Capacity Units.
Ignoring the swift SDK for a moment, DynamoDB has the DeleteItem method to remove a single item from a table, but it also has a batch method.
Quote
In addition to DeleteItem, Amazon DynamoDB supports a BatchWriteItem
action for deleting multiple items at the same time.
The problem is, I can't see a way to access BatchWriteItem through the swift SDK. Even if you could use BatchWriteItem, it can only take 25 items at a time, so you would still end up having to write a loop.
Sorry its not a more complete answer, but thought this might be useful. As far as I know there isn't a simple (single) method for doing this.

In Realm Mobile Platform, how do I call self.realm.objects to List<Item>

Im trying to work out how to call self.realm.objects(...) and assign to results: List.
There isn't anything for that it seems, but if I change my results to a Results, I can't append using an add method later on.
Not sure which way to proceed
Converting a Results collection to List is really straightforward, you just call List(results) and you are left with a List<T> collection. You can also do Array(results) to get an array instead of a Realm list.
In context:
let realm = try! Realm()
let objects = realm.objects(MyObject.self)
let listOfObjects = List(objects)
Or you can do the last two steps in one line as well
let objects = List(realm.objects(MyObject.self))

What is wrong with this line of Swift iOS Code?

I have created an iOS app using Swift and everything is working fine and dandy on the simulator. I get no errors or crashes at all, but when I submit my app to put up on the app store Apple rejects it and lets me know that it crashes when the user makes a selection. I cannot recreate this error/crash. I took the crash logs and symbolicated them. This line of code came up as the culprit for the crashes:
linksToPass = getLinks(season) as [String:[String]]
This line is trying to store the resulting Dictionary from the getLinks() function I created. It for sure is getting a dictionary and if there is no dictionary to send back I create a dictionary which has error information in it, so it is for sure returning a dictionary in that format no matter what. Seeing as I cannot recreate the crash, I am just trying to error check this line of code in any way possible so it does't crash when I resubmit to Apple.
I tried checking if the resulting dictionary was nil like so:
if(getLinks(seasons) != nil){
linksToPass = getLinks(season) as [String:[String]]
}
This is not valid though, and XCode lets me know that UInt8 is not compatible with NSDictionary or something of that nature.
I then fixed that line and changed it to this:
if(getLinks(seasons) != ["":[""]]){
linksToPass = getLinks(season) as [String:[String]]
}
I am just not sure if this is even a good way to check for errors. I was wondering if there were any suggestions on how I may go about making sure this line does not fail and result in a crash. Thank you very much.
EDIT:
Here is my getLinks() function if that helps add more info to the problem:
var season = ""
let hymn_links = Hymn_Links()
func getLinks (nameofseason:String) -> NSDictionary
{
switch (nameofseason)
{
default:
return ["Maps Not Found": []]
}
}
EDIT #2:
This is my updated getLinks() function with the use of optionals.
func getLinks (nameofseason:String) -> NSDictionary?
{
switch (nameofseason)
{
default:
return nil
}
}
Also in my statement of linksToPass I changed it to:
if let links = getLinks(season) as? [String:[String]]
{
linksToPass = links
hymnnames = [String] (linksToPass.keys)
}
There are some known issues with the Swift optimiser. Some people have resorted to shipping with debug builds.
My suggestion would be to test with an optimised build to see if you can reproduce it. You can then try shipping a debug build to the App store.
General Code Comments
Why are you returning an NSDictionary rather than a Swift dictionary anyway? Without knowing the contents and creation method for your hymn_links object I can't be sure how good it is.
I would avoid as casts until Swift 1.2 and stick to using as? and then handling the nil case. At least in your "Edit 2" a nil will cause a crash as nil cannot be cast to [String:[String]] although [String:[String]]? should be possible.
Can you guarantee that all of the items returned by the switch statement will never under any circumstances be nil? If not getLinks should return an Optional.
Note that is is virtually impossible for getLinks to know that one of the items will never be nil and in Swift un-handed nils are a crash waiting to happen. Unless all these methods correctly handle nil.
Return an Optional and handle that in the statement that calls getLinks.
Languages handle nils differently, Objective-C handles them rather well, Java and Swift by crashing. But Swift has a mechanism to handle nils without crashing: Optionals, use it.

parsing json in swift

I'm trying to read the Linkedin response in swift.
My object is something like this ["positions":["values":["data1","data2","data3"]]]
if let positions: NSDictionary = info["positions"] as NSDictionary!{
if let positionsInfo: [NSDictionary] = positions["values"] as? [NSDictionary]{
for position : NSDictionary! in positionsInfo {
dosomething(position, person:usr)
}
}
}
If I do a StepOver line by line it works correctly. But if I run it i'll get a EXC_BAD_ADDRESS(code=1,address=0x7966b04) I enabled Zombie objects and ran it on Instruments. I'm pretty sure this is the code which is causing the problem. But not sure what is wrong with it.
The moment you used ! you opened yourself up for crashes if there were any problem. You must use as? to make sure that the data is actually what you think it is.
There are many blog posts out there on how to safely parse JSON into Swift data structures. It's now almost a rite of passage for Swift bloggers.
http://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics
http://chris.eidhof.nl/posts/json-parsing-in-swift.html
https://github.com/owensd/json-swift
https://github.com/lingoer/SwiftyJSON
Of course the many packages: https://github.com/search?q=%5Bswift%5D+json
http://robnapier.net/functional-wish-fulfillment - My own version on top of all the others

Resources