从iPhone到watchkit应用程序发送字典数组

时间:2015-03-03 13:39:40

标签: swift watchkit

代码:  AppDelegate.swift

 func application(application:UIApplication!,
        handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!,
                reply: (([NSObject : AnyObject]!) -> Void)!)
            {
                let entityDescription =
                NSEntityDescription.entityForName("Quote",
                    inManagedObjectContext: managedObjectContext!)

                let request = NSFetchRequest()
                request.entity = entityDescription

                let pred = NSPredicate(format: "(quoteDate = %@)", "2015-03-08")
                request.predicate = pred

                var error: NSError?

                var objects = managedObjectContext?.executeFetchRequest(request,
                    error: &error)

                if let results = objects {

                    if results.count > 0 {
                         arrQuotes = NSMutableArray()

                        for(var i=0;i<results.count;i++){
                            let match = results[i] as! NSManagedObject
                            var quote = match.valueForKey("quote") as! NSString
                            arrQuotes.addObject(quote)
                        }
                        var dict = ["test": arrQuotes]
                        reply(dict)
                    } else {

                    }
                }

catecontroller.swift

override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
         arrQuotes = NSMutableArray()
        var dict = ["test" : arrQuotes]

        if !WKInterfaceController.openParentApplication(dict, reply: { (reply,error) -> Void in
            println("\(reply)") //your reply data as Dictionary
            self.arrQuotes = dict["test"]!
           println("\(self.arrQuotes.count)")
        }) {
            println("ERROR")
        }

我正在做一个示例watchkit项目。我想要做的是从iPhone端获取数据并将其发送到watchkit app.I尝试将值作为字典数组返回。但在watchkit端我得到数组计数为零。我不知道我哪里出错了?任何帮助都会受到赞赏。谢谢你提前

1 个答案:

答案 0 :(得分:1)

我猜你的iOS应用功能有些麻烦。我认为你的reply关闭很可能没有被调用。我会首先尝试简化您的逻辑,以确保reply实际上正确回归。然后,您可以正确地传递数据。我首先简单介绍以下逻辑:

<强> catecontroller.swift

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    WKInterfaceController.openParentApplication(["dummy": "dictionary"]) { reply, error in
        println("Reply: \(reply)")
        println("Error: \(error)")
    }
}

<强> AppDelegate.swift

func application(
    application: UIApplication!,
    handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!,
    reply: (([NSObject : AnyObject]!) -> Void)!)
{
    // Worry about this logic later...

    reply(["test": "value"])
}

一旦你有这个简化的版本正确传递数据没有错误,那么你可以添加数据传递逻辑。