通过updateApplicationContext从Watch发送字典到iPhone

时间:2016-02-23 19:35:56

标签: ios watch-os-2 watchconnectivity

我遇到WatchConnectivity问题。

在我的应用程序中,我将带有数据的字典发送到AppleWatch。一切都在我的手表上。在那里,用户可以更改某些数据(我有一个艺术家列表,用户可以在其中检查或取消选中艺术家)。更改后,List应通过WatchConnectivity发送回我的iPhone。我使用函数updateApplicationContext。在我的AppDelegate类中,正确地读出了Dictionary,但之后我想将我的Artists设置为NSUserDefaults,但是如果我调试,我的NSUserDefaults中没有更改的值。

任何人都有一个想法如何将像Arrays等复杂对象发送回电话。

这是我的AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {

var window: UIWindow?


func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){


    if(applicationContext["myUserProfile"] != nil){
        Utils().importMyUserProfileFromSession(applicationContext, getCompletionHandler: {(artists) -> Void in

            Utils().saveArtists(artists, key: "profileArtistsFromWatch")
            //in artists  the Values are correct, so i save them here
            //but if i want to read them out(load and save Function works!) the Array is empty...
            let artists1 = Utils().loadArtists("profileArtistsFromWatch")
            })   
    }
}

}

这是我的函数importMyUserProfileFromSession

  func importMyUserProfileFromSession(applicationContext: [String: AnyObject], getCompletionHandler : (artists: [Artist]) -> Void){
    let me = self.getProfileData()
    var myArtists = me.artists


    if(applicationContext["myUserProfile"] != nil){
        let dictUser :[String: AnyObject] = applicationContext["myUserProfile"] as! [String: AnyObject]
        // print(dictUser)
        var artists : [Artist] = [Artist]()
        if dictUser["artists"] != nil{
            let dictArtists :[Int: AnyObject] = dictUser["artists"] as! [Int: AnyObject]
            for j in 0..<dictArtists.count{
                let dictArtist :[String: AnyObject] = dictArtists[j] as! [String: AnyObject]
                var a : Artist = Artist()
                if dictArtist["id"] != nil{
                    let indexOfArtist = self.getArtistById(dictArtist["id"] as! Int, artists: myArtists)
                    if(indexOfArtist != -1){
                        a.id = myArtists[indexOfArtist].id as! Int
                        print(a.id)
                    }
                    a.idInApp = dictArtist["id"] as! Int
                }
                if dictArtist["name"] != nil{
                    a.name = dictArtist["name"] as! String
                }
                if dictArtist["image"] != nil{
                    let imageData: NSData = dictArtist["image"] as! NSData
                    a.imageData = imageData

                }
                if dictArtist["active"] != nil{
                    let active: Bool = dictArtist["active"] as! Bool
                    a.display = active

                }

                artists.append(a)
            }
            getCompletionHandler(artists: artists)   
        }
    }

}

0 个答案:

没有答案