내 프로젝트에서는 시계와 iPhone에서 메시지를주고 받는데 Watch Connectivity
을 사용합니다. 내가 응용 프로그램을 시작할 때 전화로 메시지를 보내고 문자열 배열을받을 수 있지만 작업을 사용할 때 다음과 같은 오류가 발생합니다."메시지 답장이 너무 오래 걸렸습니다." - Watch OS 3의 연결 문제보기
오류 도메인 = WCErrorDomain 코드 = 7012 "메시지 응답이 너무 오래 걸렸습니다."
다음은 설정 방법입니다.
먼저 시계가 전화로 메시지를 보내면 전화가 WKInterfaceTable
에 표시 할 문자열 배열을 보냅니다. 앱을로드 할 때 가끔씩 작동합니다. (나는 모든 NSManagedObjects이 Items
을 불러 watchItems
를라는 array
에 저장하기 위해 자신의 title
문자열 속성을 사용하여 가져옵니다.
을 내가 배열의 모든 항목을 삭제하고 새 데이터로 테이블을 새로 고치려면 시계에 대한 작업을해야하지만.
시계의 동작으로 sendMessage
함수를 사용하여 item
을 휴대 전화로 보내어 배열에서 삭제하면 전화가 새로운 업데이트 된 배열을 시계로 보내고 시계가 테이블을 업데이트합니다. 그러나 동일한 배열을 가져옵니다. back 또는 오류가 발생했습니다.
아주 간단하고, 너무 적습니다. Swift 3 및 Watch OS3/iOS 10 이전에는 실제로 제대로 작동했습니다. 전체 응용 프로그램이 작동하는 데 사용됩니다.
다음은 모든 설정 방법입니다.
전화 앱 위임
import WatchConnectivity
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {
var session : WCSession!
var items = [Items]()
func loadData() {
let moc = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest<Items>(entityName: "Items")
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
request.predicate = NSPredicate(format: "remove == 0", "remove")
do {
try
self.items = moc!.fetch(request)
// success ...
} catch {
// failure
print("Fetch failed")
}
}
//WATCH EXTENSION FUNCTIONS
//IOS 9.3
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
//HAVE TO INCLUDE
@available(iOS 9.3, *)
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?){
print("iPhone WCSession activation did complete")
}
@available(iOS 9.3, *)
func sessionDidDeactivate(_ session: WCSession) {}
func sessionWatchStateDidChange(_ session: WCSession) {}
func sessionDidBecomeInactive(_ session: WCSession) {
}
//APP DELEGATE FUNCTIONS
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
//Check if session is supported and Activate
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self;
session.activate()
}
return true
}
}
//DID RECIEVE MESSAGE
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Swift.Void) {
loadData()
func loadItems() {
watchItems.removeAll()
for a in self.items {
watchItems.append(a.title)
}
}
var watchItems = ["1","2","3","4","5"]
let value = message["Value"] as? String
//This is called when user loads app, and takes some time when using refresh action, sometimes times out
if value == "HELLOiPhone/[email protected]=" {
print("Hello Message Recieved")
loadItems()
//send a reply
replyHandler([ "Items" : Items ])
}
//Not sure if receiving but does not delete array and send back to watch
if value == "[email protected]+=-/" {
for index in self.items {
index.remove = 1
//Saves MOC
}
loadData()
loadTasksData()
//send a reply
replyHandler([ "Items" : Items ])
}
else {
for index in self.items {
if index.title == value {
index.remove = 1
//Saves MOC
}
}
loadData()
loadTasksData()
//send a reply
replyHandler([ "Items" : Items ])
}
}
시계
import WatchConnectivity
class SimplelistInterfaceController: WKInterfaceController, WCSessionDelegate {
/** Called when the session has completed activation. If session state is WCSessionActivationStateNotActivated there will be an error with more details. */
@available(watchOS 2.2, *)
public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
//Fetch data is a function which sends a "HELLOiPhone/[email protected]=" message to receive the array and displays in the table. This works
fetchData()
}
var session : WCSession!
var items = ["Refresh Items"]
override func didAppear() {
fetchData()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
//Check if session is supported and Activate
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self
session.activate()
}
fetchData()
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
fetchData()
}
@IBAction func refresh() {
print("Refresh")
//Works but sometimes message is delayed
fetchData()
}
@IBAction func removeAll() {
print("Remove All Items is called")
if WCSession.default().isReachable {
let messageToSend = ["Value":"[email protected]+=-/"]
print("\(messageToSend)")
session.sendMessage(messageToSend, replyHandler: { replyMessage in
if let value = replyMessage["Items"] {
self.items = value as! [String]
Not receiving message
print("Did Recieve Message, items = \(self.items)")
}
}, errorHandler: {error in
// catch any errors here
print(error)
})
}
fetchData()
}
}
'WCSession' API는 속성 목록 유형이있는 사전 만 사용하지만 'Items'를 보내는 중입니다. 이 객체들은 무엇이며, WCSession API에 의해 지원되는지 확실합니까? – ccjensen
@ccjensen 아이템은 실제로'NSManagedObject'입니다.하지만 시계를 보내기 전에 배열을 생성하기 위해 문자열 값을 사용하는 제목 속성을 사용합니다. 그러나 시계를 가져올 때마다 전화가 데이터를 업데이트하고 다시 가져와야합니다. 이것은 일어나지 않고 종종 오류가 발생합니다. – JUSDEV
또한 데이터를 표시 할 때 실제로 시계가 제대로 작동하지만 개체를 제거하려고하면 응답하지 않습니다. – JUSDEV