传递字典以观看

时间:2015-09-07 15:37:52

标签: xcode swift parse-platform watchkit watch-os-2

我正在尝试从iPhone传递数据 - >通过Application Context方法使用后台传输,通过Watch Connectivity观看

iPhone TableViewController

private func configureWCSession() {
    session?.delegate = self;
    session?.activateSession()
    print("Configured WC Session")
}

func getParsePassData () {
    let gmtTime = NSDate()

    // Query Parse
    let query = PFQuery(className: "data")
    query.whereKey("dateGame", greaterThanOrEqualTo: gmtTime)

    query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
        if error == nil
        {
            if let objectsFromParse = objects as? [PFObject]{
                for MatchupObject in objectsFromParse
                {
                    let matchupDict = ["matchupSaved" : MatchupObject]

                    do {
                        try self.session?.updateApplicationContext(matchupDict)
                        print("getParsePassData iPhone")
                    } catch {
                        print("error")
                    }
                }
            }
        }
    }

}

我在日志中得到error两次print ed(我在Parse中有两个matchup s所以也许它知道有两个对象,这就是为什么它抛出两个错误呢?)

Configured WC Session
error
error

所以我甚至没有达到print在Watch应用程序中查看matchup是否正确传递的程度。

观看InterfaceController

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
    let matchupWatch = applicationContext["matchupSaved"] as? String

    print("Matchups: %@", matchupWatch)
}

有什么想法吗?将发布您需要的任何额外代码。谢谢!

编辑1:

Per EridB回答,我尝试将编码添加到 getParsePassData

func getParsePassData () {
    let gmtTime = NSDate()

    // Query Parse
    let query = PFQuery(className: "data")
    query.whereKey("dateGame", greaterThanOrEqualTo: gmtTime)

    query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
        if error == nil
        {
            if let objectsFromParse = objects as? [PFObject]{
                for MatchupObject in objectsFromParse
                {
                    let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject)

                    let matchupDict = ["matchupSaved" : data]

                    do {
                        try self.session?.updateApplicationContext(matchupDict)
                        print("getParsePassData iPhone")
                    } catch {
                        print("error")
                    }
                }
            }
        }
    }

}

但是在日志中得到这个:

-[PFObject encodeWithCoder:]: unrecognized selector sent to instance 0x7fbe80d43f30

*** -[NSKeyedArchiver dealloc]: warning: NSKeyedArchiver deallocated without having had -finishEncoding called on it.

编辑2:

Per EridB回答,我也尝试将函数粘贴到我的代码中:

func sendObjectToWatch(object: NSObject) {
    //Archiving
    let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject)

    //Putting it in the dictionary
    let matchupDict = ["matchupSaved" : data]

    //Send the matchupDict via WCSession
    self.session?.updateApplicationContext(matchupDict)
}

但是在函数的第一行得到了这个错误:

“使用未解析的标识MatchupObject

我确信我一定不能理解如何正确使用EridB的答案。

编辑3:

NSCoder方法:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    //super.init(coder: aDecoder)

    configureWCSession()

    // Configure the PFQueryTableView
    self.parseClassName = "data"
    self.textKey = "matchup"
    self.pullToRefreshEnabled = true
    self.paginationEnabled = false
}

1 个答案:

答案 0 :(得分:2)

错误

您收到该错误,因为您要将NSObjectMatchupObject)与您要传递的字典中的NSCoding不符。

来自Apple Docs

  

对于大多数类型的传输,您提供了一个NSDictionary对象   您要发送的数据。字典的键和值必须   所有都是属性列表类型,因为数据必须序列化   无线发送。 (如果您需要包含不属性的类型   列表类型,将它们打包在NSData对象中或将它们写入文件   在发送它们之前。)另外,你发送的词典应该是   紧凑,仅包含您真正需要的数据。保持你的   字典小确保它们快速传播并做到   不要在两台设备上消耗太多电量。

详细

您需要将NSObject's归档到NSData,然后将其放入NSDictionary。如果您归档NSObject不符合NSCodingNSData,则nil将为NSObject

example极大地展示了如何使NSCoding符合//Send the dictionary to the watch func sendObjectToWatch(object: NSObject) { //Archiving let data = NSKeyedArchiver.archivedDataWithRootObject(MatchupObject) //Putting it in the dictionary let matchupDict = ["matchupSaved" : data] //Send the matchupDict via WCSession self.session?.updateApplicationContext(matchupDict) } //When receiving object from the other side unarchive it and get the object back func objectFromData(dictionary: NSDictionary) -> MatchupObject { //Load the archived object from received dictionary let data = dictionary["matchupSaved"] //Deserialize data to MatchupObject let matchUpObject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MatchupObject return matchUpObject } ,如果您实施这些内容,那么您只需按照以下代码操作:

getKeyValue("'username', 'userid'")


    private Function getKeyValue(ByVal keyList as String) 
          Dim output As Dictionary (Of String, String)
          Dim systemkeysql As String = "select key_code, key_value from system_key_table where key_code in (@keycodelist) "

                Try
                    Using connection As New SqlConnection(getConnectionString())
                        Using command As New SqlCommand(systemkeysql, connection)

                            With (command.Parameters)
                                .Add(New SqlParameter("@keycodelist", System.Data.SqlDbType.NVarChar)).Value = keylist
                            End With

                            connection.Open()
                            Using reader As SqlDataReader = command.ExecuteReader()
                                While reader.Read()
                                    output.Add(reader(0), reader(1))

                                End While
                            End Using

                        End Using
                        connection.Close()
                    End Using

                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.OkOnly)
                End Try 
        Return Output
End Function

由于你使用 Parse ,修改对象可能无法完成(我暂时没有使用 Parse ,所以肯定是IDK),但是从他们的论坛我发现了这个问题:https://parse.com/questions/is-there-a-way-to-serialize-a-parse-object-to-a-plain-string-or-a-json-string这可以帮助你比上面看到的更容易解决这个问题:)