Error accessing recordFields in CKQueryNotification - swift

When I access the recordFields on a CKQueryNotification returned from a subscription, I get this error:
Could not cast value of type '__NSCFDictionary' (0x1009f0630) to 'CKRecordValue' (0x1009fc050).
I process the notification like this:
let notification: CKNotification = CKNotification(fromRemoteNotificationDictionary: userInfo as! [String : NSObject])
It seems to work fine and I get a CKQueryNotification.
The notification recordFields prints out like:
<CKQueryNotification: 0x156ef2bf0; notificationType=1, notificationID=<CKNotificationID: 0x156ef41e0; UUID=ba82325d-ab9e-4805-bb26-994a1122900b>, containerIdentifier=iCloud.com.skyvalleystudio.RaceTiming, subscriptionID=Marks for 06597454-4EAD-434E-BC03-CE51D987C79F, queryNotificationReason=1, recordFields={
location = {
altitude = 0;
course = "-1";
horizontalAccuracy = 0;
latitude = "37.33296424";
longitude = "-122.03937369";
speed = "-1";
timestamp = "484712160.263403";
verticalAccuracy = "-1";
};
timeStamp = 484712160;
user = "_2031e89e9ade8345c7d4248f3ec3a2e6";
}, recordID=<CKRecordID: 0x156ef1670; 568D257C-E849-4492-A810-CB7076FC5A22:(_defaultZone:__defaultOwner__)>, isPublicDatabase=1>
So it looks like the recordFields dictionary is there and populated.
I try to access is like this:
let timestamp = notification.recordFields!["timeStamp"] as? NSDate
Then I get the error.
UPDATE
I filed a Apple bug report 26251611.
The CLLocation is not being decoded in the CKNotification creation is my best guess.
One possible workaround is processing the userInfo directly, but I had problems with processing the CKReference. It seems like the CKRecordValue protocol adopters should be better handled when the CKNotification is created.
UPDATE
Closed as duplicate of 24643471. It's still open at this time...

Related

How to extract a value from [DDXMLElement] in Swift?

I want to extract the value of id in the stanza tag.
The stanza tag is:
[<stanza-id xmlns="urn:xmpp:sid:0" by="f.talebi#wepod.ir" id="1531235744929009"></stanza-id>]
This is a part of message received from Xmpp server. I need to extract "1531235744929009" value. Therefore, I wrote this:
var stanza = message.elements(forName: "stanza-id")
print(stanza)
var id = stanza.first?.attributes
if let attributes = stanza.first?.attributes {
let lastItem = attributes.last
if let stanzaID = lastItem?.stringValue {
print("stanzaID = \(stanzaID)")
}
}
This code works correctly, but its not a clean code. especially where I wrote this line lastItem = attributes.last because if the order changes this won't work.
just use stanza.attributed(forName: String)

accessing API's from openweathermap

I am trying to access two bits of data from OpenWeatherMap in Swift. The first is the description and the second is the temperature. I am accessing the description using the following code
if let description = ((jsonResult["weather"]as? NSArray)?[0]as? NSDictionary)?["main"]as? String {
DispatchQueue.main.sync(execute:) {
self.resultLabel.text = description
Now the issue I am having is accessing the temperature which is configured like this print("Temperature: (weather["main"]!["temp"]!!)") as opposed to print("Weather description: (weather["weather"]![0]!["description"]!!)")
How do I reconfigure the above code to access the temperature data. Thanks for looking into this for me.
After much research this worked for me.
if let main = jsonResult["main"] as? NSDictionary {
print(main)
if let temp = main["temp"] as? Double {
DispatchQueue.main.sync(execute:) {
self.tempLabel.text = String(format: "%.1fº Centigrade", temp)
}

NSUserDefafults returns wrong data

On my Cocoa application using Swift, I'm getting bad data from NSUserDefaults. If I go to the command line and do
defaults read my.bundle.identifier
It comes back with this:
{
NSNavLastRootDirectory = "~/Documents";
NSNavPanelExpandedSizeForSaveMode = "{712, 521}";
producer = 10;
version = "-1";
when = 1470502459;
}
Then, in my application I read the value of version like so:
let def = NSUserDefaults.standardUserDefaults()
let current = def.integerForKey("version")
print("Current version is \(current)")
It's printing out that current is 3, not -1. What in the world is going on?

PMCreateSession not creating print session

Trying to get printable rect for OS X app. Seems to involve creating a session, then a page format, validating the format, etc. Code compiles, but getting a status of -50 from PMCreateSession. Am I declaring printSession improperly? Normally don't have to deal so much with UnsafeMutablePointers.
Thanks!
let printSession: UnsafeMutablePointer<PMPrintSession> = nil
let pmPageFormat: UnsafeMutablePointer<PMPageFormat> = nil
var status = PMCreateSession(printSession)
status = PMCreatePageFormat(pmPageFormat)
status = PMSessionDefaultPageFormat(printSession.memory, pmPageFormat.memory)
let changed: UnsafeMutablePointer<DarwinBoolean> = nil
status = PMSessionValidatePageFormat(printSession.memory, pmPageFormat.memory, changed)
changed.destroy()
var pRect = PMRect()
status = PMGetAdjustedPageRect(pmPageFormat.memory, &pRect)
Swift.print("pRect \(pRect)")
status = PMRelease(pmPageFormat)
status = PMRelease(printSession)
Am I declaring printSession improperly?
One could acquire a PMPrintSession as follows:
// create a C Null pointer of type PMPrintSession
let printSession = unsafeBitCast(0, to: PMPrintSession.self)
// pass by & converts PMPrintSession to UnsafeMutablePointer<PMPrintSession>
PMCreateSession(&printSession)
…
// recast printSession to release memory
PMRelease( PMObject(printSession) )
Alternately, a PMPrintSession can be accessed from the Cocoa NSPrintInfo:
let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
Normally don't have to deal so much with UnsafeMutablePointers
For information more information on using an UnsafeMutablePointer see StackOverflow "How to use UnsafeMutablePointer in Swift?"
For a complete example of using Core Printing with Swift see 004.42Apple_CorePrintingExample on GitHub.

How to create dictionary from JSON

I receive JSON objects that looks like the one below. How can I convert it into a format that is easily handled by Swift 2.1 ? I will receive several of these and have to put them into an array and sort by createdAt.
Optional({
comment = "<null>";
completedAt = "<null>";
createdAt = "2015-11-02 15:01:04 +0000";
paid = 1;
paidAt = "2015-11-02 15:01:04 +0000";
startedAt = "<null>";
state = request;
type = doctor;
user = KTsCySacEAiz3eDnf;
userdata = {
birthdate = "<null>";
gender = "<null>";
};
})
As in the title you say you expect a Dictionary, you can get one by simply serializate the json and cast it to a Dictionary.
do{
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
}catch{
print("Something went wrong")
}
Where data is you json content as NSData. If you get a String you can easily convert it
let data = text.dataUsingEncoding(NSUTF8StringEncoding)