gpt4 book ai didi

ios - swift 将数据发送到Apple Watch

转载 作者:可可西里 更新时间:2023-11-01 02:15:11 28 4
gpt4 key购买 nike

在我的应用程序中,我正在向 Apple Watch 发送数据(即“UILabels”和“UIImage”)。正在成功发送。现在在我的 watch 主视图中显示从 ios 应用程序发送的数据,我有一个按钮打开一个表格 View ,我在其中拍摄了 1 个 ImageView 和 4 个标签。现在我也希望在表格 View 中显示相同的数据,即每次我将数据从 ios 应用程序发送到 watch 应用程序时,应该显示我从 ios 应用程序发送的每个条目并且也应该保存。我希望数据显示为与保存在我的 ios 应用程序中的数据相同,如下图所示 ios app image :

watch app simulator layout

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)
}
}

我 watch 的源代码

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

MessageData = NSMutableDictionary(object: message, forKey: "data")
print("\(MessageData)")
watch_ticket_category.setText("\(MessageData["data"]!["Watchdat"]!!["ticket_category"] as! String)")
watch_displayImage.setImage(UIImage(named: 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)")
}

最佳答案

您可能需要使用 updateApplicationContext(_:),并将传输的数据存储在 iPhone 上,并始终通过 updateApplicationContext 共享,它始终会更新数据.

关于ios - swift 将数据发送到Apple Watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39285814/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com