快速将数据从IOS应用程序发送到Apple手表

时间:2016-09-03 06:35:41

标签: ios swift uiimage uilabel apple-watch

在我的应用中,我将数据从ios应用程序发送到Apple Watch。数据由4个标签和1个图像组成。我正在使用带有FMDB包装器的SQlite数据库。我的数据库由6列组成,名为“imagePath”,“imageName”,“ticket_category”,“ticket_type”,“date”,“time”。现在,当我在模拟器上运行应用程序时,数据正在成功发送到观看状态,如下图所示

watch app screenshot

输出控制台打印: -

{
    data =     {
        Watchdat =         {
            date = "Sep 3, 2016";
            imageName = "image_494576556.033698.png";
            imagePath = "/Users/apple/Library/Developer/CoreSimulator/Devices/FD79D273-F36A-4CBB-B7AB-2D0C1BCBFC19/data/Containers/Data/Application/036A0694-6C3A-4F8E-8704-6A8289CD1272/Documents/image_494576556.033698.png";
            "ticket_category" = Bus;
            "ticket_type" = 1212;
            time = "11:52 AM";
        };
    };
}
data---- Optional(<89504e47 0d0a1a0a 0000000d 49484452 00000113 00000113 08020000 009acb75 ef000000 01735247 4200aece 1ce90000 001c6944 4f540000 00020000 00000000 008a0000 00280000 008a0000 00890001 7f41549e 859e0000 40004944 41547801 7cbc7750 5b5bbbe6 b9c841a0 1c113967 b0c139e7 9c23ce19 83c1e40c 92402001 02219173 ce607232 19db38db e79c2ff6 7743dfe9 b9d5d333 3535ff4c 55575757 cd54cdb3 b57c747d bfaee953 6fed5ada 6c09e1b3

在真实设备上运行时,手表上只显示标签,图像不显示。输出控制台打印: -

{
    data =     {
        Watchdat =         {
            date = "03-Sep-2016";
            imageName = "image_494577137.890975.png";
            imagePath = "/var/mobile/Containers/Data/Application/528D9F6A-F6B5-4C91-B63E-84CCA1EED94A/Documents/image_494577137.890975.png";
            "ticket_category" = Bus;
            "ticket_type" = thug;
            time = "12:02 PM";
        };
    };
}
data---- nil

表侧的源代码:

    class InterfaceController: WKInterfaceController, WCSessionDelegate {

    var session: WCSession!

    var MessageData = NSMutableDictionary()

    @IBOutlet var watch_displayImage: WKInterfaceImage!
    @IBOutlet var watch_ticket_category: WKInterfaceLabel!
    @IBOutlet var watch_ticketType: WKInterfaceLabel!
    @IBOutlet var watch_ticketTime: WKInterfaceLabel!
    @IBOutlet var watch_ticketDate: WKInterfaceLabel!

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

        if WCSession.isSupported()
        {

            session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()

        }

    }

    override func willActivate()
    {

        super.willActivate()

    }

       func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)
      {

        MessageData = NSMutableDictionary(object: message, forKey: "data")
        print("\(MessageData)")
        watch_ticket_category.setText("\(MessageData["data"]!["Watchdat"]!!["ticket_category"] as! String)")


        watch_displayImage.setImageData(NSData(contentsOfFile: MessageData["data"]!["Watchdat"]!!["imagePath"] as! String))
        watch_ticketType.setText("\(MessageData["data"]!["Watchdat"]!!["ticket_type"] as! String)")
        watch_ticketTime.setText("\(MessageData["data"]!["Watchdat"]!!["time"] as! String)")
        watch_ticketDate.setText("\(MessageData["data"]!["Watchdat"]!!["date"] as! String)")
        print("data----",NSData(contentsOfFile: MessageData["data"]!["Watchdat"]!!["imagePath"] as! String))


   }

ios端的源代码:

    class TicketDetailViewController: UIViewController, WCSessionDelegate {
  let dic1  = NSMutableDictionary()
    var defaults = NSUserDefaults()
    var databasePath = NSString()
    var holding_Ticket_category: String = ""
    var holding_Image: UIImage?
    var hold_ticketName: String = ""
    var hold_ticketDate: String = ""
    var hold_ticketTime: String = ""
    var session: WCSession!
    var imageData: NSData!

    @IBOutlet weak var ticket_grey: UIImageView!
    @IBOutlet weak var cropped_frame: UIImageView!
    @IBOutlet weak var display_image: UIImageView!
    @IBOutlet weak var ticket_type_name: UILabel!
    @IBOutlet weak var ticket_date: UILabel!
    @IBOutlet weak var ticket_time: UILabel!
    @IBOutlet weak var ticket_category: UILabel!


    override func viewDidLoad()
    {
        super.viewDidLoad()
        if WCSession.isSupported(){
            self.session  = WCSession.defaultSession()
            self.session.delegate = self
            self.session.activateSession()
        }

        defaults = NSUserDefaults.standardUserDefaults()
        display_image.image = self.holding_Image
        ticket_type_name.text = hold_ticketName
        ticket_date.text = hold_ticketDate
        ticket_time.text = hold_ticketTime
        ticket_category.text = holding_Ticket_category

        let filemgr =  NSFileManager.defaultManager()
        let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let docsDir = dirPaths[0]
        var ticketDB: FMDatabase

        databasePath = (docsDir as NSString).stringByAppendingPathComponent("ticket_Pass.sqlite")


        if !filemgr.fileExistsAtPath(databasePath as String)
        {

            ticketDB = FMDatabase(path: databasePath as String)
            if ticketDB.open()
            {

                let sql_stmt = "CREATE TABLE IF NOT EXISTS TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMAGEPATH TEXT, IMAGENAME TEXT, TICKET_CATEGORY TEXT, TICKET_TYPE TEXT, DATE TEXT, TIME TEXT)"
                if !ticketDB.executeStatements(sql_stmt)
                {
                    print("Error: \(ticketDB.lastErrorMessage())")
                }
                ticketDB.close()
            } else
            {
                 print("Error: \(ticketDB.lastErrorMessage())")
            }
        }else{
            ticketDB = FMDatabase(path: databasePath as String)
            if ticketDB.open()
            {

                let sql_stmt = "CREATE TABLE IF NOT EXISTS TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMAGEPATH TEXT, IMAGENAME TEXT, TICKET_CATEGORY TEXT, TICKET_TYPE TEXT, DATE TEXT, TIME TEXT)"
                if !ticketDB.executeStatements(sql_stmt)
                {
                    print("Error: \(ticketDB.lastErrorMessage())")
                }
                ticketDB.close()
            } else
            {

                print("Error: \(ticketDB.lastErrorMessage())")
            }

        }
    }

    func saveImageToFolder()
    {

        imageData = UIImagePNGRepresentation(holding_Image!)!
        let imageName = "image_\(NSDate.timeIntervalSinceReferenceDate()).png"
        let imagePath = (self.getDocumentsDirectory() as NSString).stringByAppendingPathComponent(imageName)
        print("imagePath:- \(imagePath)")
        print("image size: \(holding_Image?.size)")

        imageData.writeToFile(imagePath, atomically: true)
        NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "ImagePath")
        NSUserDefaults.standardUserDefaults().setObject(imageData, forKey: "ImageData")
        NSUserDefaults.standardUserDefaults().setObject(imageName, forKey: "ImageName")
        NSUserDefaults.standardUserDefaults().synchronize()

    }

    func getDocumentsDirectory() -> String{
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsPath = paths[0]
        print("document path:- \(documentsPath)")
        return documentsPath

    }


    @IBAction func addTickets(sender: UIButton)
    {
        let ticketDB = FMDatabase(path: databasePath as String)
        if ticketDB.open()
        {
                //self.saveImageToFolder()

                let insertSQL = "INSERT INTO TICKET (imagePath, imageName, ticket_category, ticket_type, date, time) VALUES ('\(NSUserDefaults.standardUserDefaults().objectForKey("ImagePath")!)', '\(NSUserDefaults.standardUserDefaults().objectForKey("ImageName")!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

                let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

                if !result
                {

                    print("Error: \(ticketDB.lastErrorMessage())")

                } else
                {

                    let alt = PMAlertController(title: "Success!", description: "Your data is saved to Database!", image: UIImage(named: ""), style: .Alert)

                    alt.addAction(PMAlertAction(title: "OK!", style: .Default, action: { (ACTION) -> Void in

                    self.navigationController?.popToRootViewControllerAnimated(true)

                    }))

                    self.presentViewController(alt, animated: true, completion: nil)
                    print(databasePath)

               }
        }
    }


    @IBAction func deleteTickets(sender: UIButton) {
        let alt = PMAlertController(title: "Delete Ticket Details!", description: "Are you sure?", image: UIImage(named: ""), style: .Alert)

        alt.addAction(PMAlertAction(title: "Cancel", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

            self.dismissViewControllerAnimated(true, completion: nil)

        }))
        alt.addAction(PMAlertAction(title: "OK", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

            self.navigationController?.popToRootViewControllerAnimated(true)
        }))
        self.presentViewController(alt, animated: true, completion: nil)
    }


    @IBAction func sendToWatch(sender: AnyObject)
    {

        let ticketDB = FMDatabase(path: databasePath as String)
        if ticketDB.open()
        {
            self.saveImageToFolder()
            let insertSQL = "INSERT INTO TICKET (imagePath, imageName, ticket_category, ticket_type, date, time) VALUES ('\(NSUserDefaults.standardUserDefaults().objectForKey("ImagePath")!)', '\(NSUserDefaults.standardUserDefaults().objectForKey("ImageName")!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

            let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

            if !result
            {

                print("Error: \(ticketDB.lastErrorMessage())")

            } else
            {

                let alt = PMAlertController(title: "Success!", description: "Your data is saved!", image: UIImage(named: ""), style: .Alert)

                alt.addAction(PMAlertAction(title: "OK!", style: .Default, action:
                { (ACTION) -> Void in


                        let ticketDB = FMDatabase(path: self.databasePath as String)
                        if ticketDB.open()
                        {

//                            let querySQL = "SELECT * FROM TICKET ORDER BY ID DESC LIMIT 1"
                             let querySQL = "SELECT * FROM TICKET "

                            let result: FMResultSet? = ticketDB.executeQuery(querySQL, withArgumentsInArray: nil)

                            if let result = result
                            {

                                let ticketDataArray:NSMutableArray = NSMutableArray()
                                while result.next()
                                {

                                    self.dic1.setObject(result.stringForColumn("imagePath"), forKey: "imagePath")
                                    self.dic1.setObject(result.stringForColumn("imageName"), forKey: "imageName")
                                    self.dic1.setObject(result.stringForColumn("ticket_category"), forKey: "ticket_category")
                                    self.dic1.setObject(result.stringForColumn("ticket_type"), forKey: "ticket_type")
                                    self.dic1.setObject(result.stringForColumn("date"), forKey: "date")
                                    self.dic1.setObject(result.stringForColumn("time"), forKey: "time")

                                    ticketDataArray.addObject(self.dic1)

                                }
                                print("ticketDataArray :  \(self.dic1)")
                            }else
                            {
                                print("Error: \(ticketDB.lastErrorMessage())")

                            }

                          ticketDB.close()

                        }
                      self.navigationController?.popToRootViewControllerAnimated(true)
                        if WCSession.defaultSession().reachable
                        {
                            let dict = ["Watchdat":self.dic1]
                            self.session.sendMessage(dict, replyHandler: { (replayDic: [String:AnyObject]) in
                                print("success!")
                                }, errorHandler: { (error:NSError) in
                                    print("error")
                            })
                        }

                }))

                self.presentViewController(alt, animated: true, completion: nil)
                print(databasePath)

            }
        }

0 个答案:

没有答案