WCSession sendMessageData not working in watchOS 3 - ios

I am trying to send image from iOS to watchOS and I am getting below error.
sendMessageData getting error: Error Domain=WCErrorDomain Code=7014
"Payload could not be delivered."
UserInfo={NSLocalizedDescription=Payload could not be delivered.
My code in ViewController Class
var session: WCSession?
override func viewDidLoad() {
super.viewDidLoad()
session?.delegate = self
if (WCSession.isSupported()) {
session = WCSession.default()
session?.delegate = self
session?.activate()
}
}
let image = UIImage(named: "img1")!
let data = UIImagePNGRepresentation(image)
session?.sendMessageData(data!, replyHandler: { (data) in
print(data)
}) { (error) in
print(error)}
}
In InterfaceController Class
override func willActivate() {
super.willActivate()
if (WCSession.isSupported()) {
session = WCSession.default()
session.delegate = self
session.activate()
}
}
func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
guard let image = UIImage(data: messageData) else {
return
}
print(image)
}
Thanks,

I think you need to try below protocol as mentioned here.
func session(_ session: WCSession, didReceiveMessageData messageData: Data, replyHandler: #escaping (Data) -> Void) {
guard let image = UIImage(data: messageData) else {
return
}
print(image)
imageSet.setImage(image)
}

Related

URLSession delegates not working after app resume

I've recently been integrating Background Transfer Service into an application so that the user is able to download files in the background.
Everything works as expected. But my delegate methods stops getting called after sending the application into the background and then re-opening the application.
File is actually being downloaded in the background but I am not receiving any call to my delegate methods. So cant show any progress to the users. So it feels like download is got stuck.
I had to remove our app from the app store as it is hurting our app. I need to resubmit the app as soon as possible. But with this problem, it's not possible.
My download manager code:
import Foundation
import Zip
import UserNotifications
////------------------------------------------------------
//// MARK: - Download Progress Struct
////------------------------------------------------------
public struct DownloadProgress {
public let name: String
public let progress: Float
public let completedUnitCount: Float
public let totalUnitCount: Float
}
protocol DownloadDelegate: class {
func downloadProgressUpdate(for progress: DownloadProgress)
func unzipProgressUpdate(for progress: Double)
func onFailure()
}
class DownloadManager : NSObject, URLSessionDownloadDelegate {
//------------------------------------------------------
// MARK: - Downloader Properties
//------------------------------------------------------
static var shared = DownloadManager()
private lazy var session: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).bookDownloader")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
var delegate: DownloadDelegate?
var previousUrl: URL?
var resumeData: Data?
var task: URLSessionDownloadTask?
// ProgressHandler --> identifier, progress, completedUnitCount, totalUnitCount
typealias ProgressHandler = (String, Float, Float, Float) -> ()
//------------------------------------------------------
// MARK: - Downloader Initializer
//------------------------------------------------------
override private init() {
super.init()
}
func activate() -> URLSession {
// Warning: If an URLSession still exists from a previous download, it doesn't create a new URLSession object but returns the existing one with the old delegate object attached!
return session
}
//------------------------------------------------------
// MARK: - Downloader start download
//------------------------------------------------------
func startDownload(url: URL) {
if let previousUrl = self.previousUrl {
if url == previousUrl {
if let data = resumeData {
let downloadTask = session.downloadTask(withResumeData: data)
downloadTask.resume()
self.task = downloadTask
} else {
let downloadTask = session.downloadTask(with: url)
downloadTask.resume()
self.task = downloadTask
}
} else {
let downloadTask = session.downloadTask(with: url)
downloadTask.resume()
self.task = downloadTask
}
} else {
let downloadTask = session.downloadTask(with: url)
downloadTask.resume()
self.task = downloadTask
}
}
//------------------------------------------------------
// MARK: - Downloader stop download
//------------------------------------------------------
func stopDownload() {
if let task = task {
task.cancel { resumeDataOrNil in
guard let resumeData = resumeDataOrNil else {
// download can't be resumed; remove from UI if necessary
return
}
self.resumeData = resumeData
}
}
}
//------------------------------------------------------
// MARK: - Downloader Progress Calculator
//------------------------------------------------------
private func calculateProgress(session : URLSession, completionHandler : #escaping ProgressHandler) {
session.getTasksWithCompletionHandler { (tasks, uploads, downloads) in
let progress = downloads.map({ (task) -> Float in
if task.countOfBytesExpectedToReceive > 0 {
return Float(task.countOfBytesReceived) / Float(task.countOfBytesExpectedToReceive)
} else {
return 0.0
}
})
let countOfBytesReceived = downloads.map({ (task) -> Float in
return Float(task.countOfBytesReceived)
})
let countOfBytesExpectedToReceive = downloads.map({ (task) -> Float in
return Float(task.countOfBytesExpectedToReceive)
})
if let name = UserDefaults.standard.string(forKey: UserDefaultKeys.OnBookDownload) {
if name.isEmpty {
return self.session.invalidateAndCancel()
}
completionHandler(name, progress.reduce(0.0, +), countOfBytesReceived.reduce(0.0, +), countOfBytesExpectedToReceive.reduce(0.0, +))
}
}
}
//------------------------------------------------------
// MARK: - Downloader Notifiers
//------------------------------------------------------
func postUnzipProgress(progress: Double) {
if let delegate = self.delegate {
delegate.unzipProgressUpdate(for: progress)
}
// NotificationCenter.default.post(name: .UnzipProgress, object: progress)
}
func postDownloadProgress(progress: DownloadProgress) {
if let delegate = self.delegate {
delegate.downloadProgressUpdate(for: progress)
}
// NotificationCenter.default.post(name: .BookDownloadProgress, object: progress)
}
func postNotification() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Download Completed".localized(), arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Quran Touch app is ready to use".localized(), arguments: nil)
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "com.qurantouch.qurantouch.BookDownloadComplete"
// Deliver the notification in 60 seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 2.0, repeats: false)
let request = UNNotificationRequest.init(identifier: "BookDownloadCompleted", content: content, trigger: trigger)
// Schedule the notification.
center.add(request)
}
//------------------------------------------------------
// MARK: - Downloader Delegate methods
//------------------------------------------------------
// On Progress Update
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let name = UserDefaults.standard.string(forKey: UserDefaultKeys.OnBookDownload) {
if name.isEmpty {
return self.session.invalidateAndCancel()
}
} else {
return self.session.invalidateAndCancel()
}
if totalBytesExpectedToWrite > 0 {
calculateProgress(session: session, completionHandler: { (name, progress, completedUnitCount, totalUnitCount) in
let progressInfo = DownloadProgress(name: name, progress: progress, completedUnitCount: completedUnitCount, totalUnitCount: totalUnitCount)
print(progressInfo.progress)
self.postDownloadProgress(progress: progressInfo)
})
}
}
// On Successful Download
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
if let name = UserDefaults.standard.string(forKey: UserDefaultKeys.OnBookDownload) {
if name.isEmpty {
return self.session.invalidateAndCancel()
}
let folder = URL.createFolder(folderName: "\(Config.bookFolder)\(name)")
let fileURL = folder!.appendingPathComponent("\(name).zip")
if let url = URL.getFolderUrl(folderName: "\(Config.bookFolder)\(name)") {
do {
try FileManager.default.moveItem(at: location, to: fileURL)
// Download completed. Now time to unzip the file
try Zip.unzipFile((fileURL), destination: url, overwrite: true, password: nil, progress: { (progress) -> () in
if progress == 1 {
App.quranDownloaded = true
UserDefaults.standard.set("selected", forKey: name)
DispatchQueue.main.async {
Reciter().downloadCompleteReciter(success: true).done{_ in}.catch{_ in}
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let backgroundCompletionHandler =
appDelegate.backgroundCompletionHandler else {
return
}
backgroundCompletionHandler()
self.postNotification()
}
// Select the book that is downloaded
// Delete the downlaoded zip file
URL.removeFile(file: fileURL)
}
self.postUnzipProgress(progress: progress)
}, fileOutputHandler: {(outputUrl) -> () in
})
} catch {
print(error)
}
}
} else {
return self.session.invalidateAndCancel()
}
}
// On Dwonload Completed with Failure
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
debugPrint("Task completed: \(task), error: \(error)")
guard let error = error else {
// Handle success case.
return
}
let userInfo = (error as NSError).userInfo
if let resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? Data {
self.resumeData = resumeData
}
if let delegate = self.delegate {
if !error.isCancelled {
delegate.onFailure()
}
}
}
// On Dwonload Invalidated with Error
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
guard let error = error else {
// Handle success case.
return
}
if let delegate = self.delegate {
if !error.isCancelled {
delegate.onFailure()
}
}
}
}
// MARK: - URLSessionDelegate
extension DownloadManager: URLSessionDelegate {
// Standard background session handler
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
let completionHandler = appDelegate.backgroundCompletionHandler {
completionHandler()
appDelegate.backgroundCompletionHandler = nil
}
}
}
}
And in app delegate:
var backgroundCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: #escaping () -> Void) {
backgroundCompletionHandler = completionHandler
}
Finally found a workaround for the issue. Once the application did return from background mode, make sure to call resume on all running tasks. This seems to reactivate callbacks to the delegate.
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
DownloadManager.shared.session.getAllTasks(completionHandler: { tasks in
for task in tasks {
task.resume()
}
})
}
For more information on this topic, Follow this link:
https://forums.developer.apple.com/thread/77666
You need to resume all tasks once you come back to active state.
URLSession.shared.getAllTasks { (tasks) in
for task in tasks
{
task.resume()
}
}

how to debug watch connectivity

I am attempting to start an HKWorkoutSession on the Apple Watch and send the heart rate data near-instantaneously to the iPhone for near real-time display. To accomplish this, I'm using WatchConnectivity's sendMessage method. I do not need replies from the phone/watch, so I'm using the version of sendMessage that doesn't use a reply handler.
The heart rate data isn't making it to the phone, and I'm struggling to understand why. I'm not getting any sorts of error messages that are helpful. How do I find out what is going wrong? I have attached both the phone app and the watch app to the debugger, but since the message never gets to the phone, I'm having a ton of trouble figuring out what's going on because obviously my breakpoints in the phone code aren't being reached. Earlier, I was using the replyHandler version of sendMessage, which has a closure for error handling. Using that, I was able to see that my errors were (sometimes) due a timeout in receiving a return message. The didReceiveMessage delegate on the phone was never reached, though, so I'm not surprised that it never sent its return message. I assume there's something wrong with the connection between the phone app and watch app, but I've checked the isReachable boolean, as well as isPaired and isWatchAppInstalled.
So I guess I'm wondering if you have any tips about debugging techniques for Watch Connectivity. And, if you want to take a look at my code too, here it is. Let me know if you see anything glaringly wrong about it. (Sorry it's a tad sloppy--just trying to get things to work right now.)
ViewController:
class ViewController: UIViewController, WCSessionDelegate {
#IBOutlet weak var bpmLabel: UILabel!
let healthStore = HKHealthStore()
var bpmArray = [Double]()
var wcSession: WCSession?
// WC Session Delegate methods
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("WC Session activation failed with error: \(error.localizedDescription)")
return
}
}
func sessionDidBecomeInactive(_ session: WCSession) {
print("WC has become inactive")
}
func sessionDidDeactivate(_ session: WCSession) {
print("WC was deactivated")
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
guard let bpm = message["bpm"] as? Double else { return }
DispatchQueue.main.async {
self.bpmArray.append(bpm)
self.bpmLabel.text = String(bpm)
}
override func viewDidLoad() {
super.viewDidLoad()
if WCSession.isSupported() {
wcSession = WCSession.default
wcSession?.delegate = self
wcSession?.activate()
}
if !(wcSession?.isPaired)! || !(wcSession?.isWatchAppInstalled)! {
print("PAIRING PROBLEM")
}
}
InterfaceController:
var wcSession: WCSession?
#IBOutlet var bpm: WKInterfaceLabel!
let healthStore = HKHealthStore()
var workoutSession: HKWorkoutSession?
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("WC Session activation failed with error: \(error.localizedDescription)")
return
}
}
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
print("here")
}
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {
print("Workout session failure")
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
workoutSession?.delegate = self
guard let wcSess = self.wcSession else { return }
wcSess.activate()
}
// modified from https://github.com/coolioxlr/watchOS-2-heartrate/blob/master/VimoHeartRate%20WatchKit%20App%20Extension/InterfaceController.swift
func createHeartRateStreamingQuery() -> HKQuery? {
if !HKHealthStore.isHealthDataAvailable() {
print("health data not available")
}
guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return nil }
let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: nil, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
self.updateHeartRate(samples: sampleObjects)
}
heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
self.updateHeartRate(samples: samples)
}
return heartRateQuery
}
// modified from https://github.com/coolioxlr/watchOS-2-heartrate/blob/master/VimoHeartRate%20WatchKit%20App%20Extension/InterfaceController.swift
func updateHeartRate(samples: [HKSample]?) {
guard let heartRateSamples = samples as? [HKQuantitySample] else { return }
guard let sample = heartRateSamples.first else { return }
let value = sample.quantity.doubleValue(for: HKUnit(from: "count/min"))
DispatchQueue.main.async() {
self.bpm.setText(String(UInt16(value)))
}
let dataToSendToPhone = ["bpm":String(value)]
if (wcSession?.isReachable)! {
self.wcSession?.sendMessage(dataToSendToPhone, replyHandler: nil)
}
else {
print("WC Session not reachable")
}
}
override func willActivate() {
super.willActivate()
if WCSession.isSupported() {
wcSession = WCSession.default
wcSession?.delegate = self
wcSession?.activate()
}
}
override func didDeactivate() {
super.didDeactivate()
}
#IBAction func recordIsTapped() {
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .other
workoutConfiguration.locationType = .unknown
// Inspired by https://developer.apple.com/library/content/samplecode/SpeedySloth/Introduction/Intro.html
do {
try self.workoutSession = HKWorkoutSession(configuration: workoutConfiguration)
healthStore.start(self.workoutSession!)
if HKHealthStore.isHealthDataAvailable() {
if let query = createHeartRateStreamingQuery() {
self.healthStore.execute(query)
}
}
else {
print("Healthkit unavailable")
}
}
catch {
fatalError(error.localizedDescription)
}
}

Google ChromeCast iOS (Swift 3) can't play video

I need help! Once i connected the device to chromecast, it crashed right when it's about to load. I have no clue why it cause that. I followed GoogleCast for Docs and few examples and seems that it's missing something. Could you guys help me?
This my code
This is on my OnCreate
override func viewDidLoad() {
sessionManager = GCKCastContext.sharedInstance().sessionManager
sessionManager?.add(self)
castMediaController = GCKUIMediaController()
if isCastEnabled() {
playSelectedItemRemotely()
}
}
//////////////////////////////////////////////////////
// //
// Start du Google ChromeCast //
// //
//////////////////////////////////////////////////////
private func buildMediaInformation() -> GCKMediaInformation {
let metadata = GCKMediaMetadata(metadataType: GCKMediaMetadataType.generic)
metadata.setString("Title", forKey: kGCKMetadataKeyTitle)
metadata.setString("Studio", forKey: kGCKMetadataKeyStudio)
let mediaInfo = GCKMediaInformation(contentID: "streamURL",
streamType: GCKMediaStreamType.none,
contentType: "video/m3u",
metadata: metadata,
streamDuration: 60,
mediaTracks: nil,
textTrackStyle: nil,
customData: nil)
print(mediaInfo.contentID)
return mediaInfo
}
func isCastEnabled() -> Bool {
switch GCKCastContext.sharedInstance().castState {
case GCKCastState.connected:
print("cast connected")
return true
case GCKCastState.connecting:
print("cast connecting")
return true
case GCKCastState.notConnected:
print("cast notConnected")
return false
case GCKCastState.noDevicesAvailable:
print("cast noDevicesAvailable")
return false
}
}
func playSelectedItemRemotely() {
let castSession = GCKCastContext.sharedInstance().sessionManager.currentCastSession
if (castSession != nil) {
castSession?.remoteMediaClient?.loadMedia(self.buildMediaInformation(), autoplay: true)
self.dismiss(animated: true, completion: nil)
}
else {
print("no castSession!")
}
}
func sessionManager(_ sessionManager: GCKSessionManager, didStart session: GCKSession) {
playSelectedItemRemotely()
}
func sessionManager(_ sessionManager: GCKSessionManager, didResumeSession session: GCKSession) {
}
func sessionManager(_ sessionManager: GCKSessionManager, didEnd session: GCKSession, withError error: Error?) {
let castSession = GCKCastContext.sharedInstance().sessionManager.currentCastSession
castSession?.endAndStopCasting(true)
}
func sessionManager(_ sessionManager: GCKSessionManager, didFailToStart session: GCKSession, withError error: Error) {
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// playerView.player?.replaceCurrentItem(with: nil)
//
// //this stops the session manager sending callbacks to your VideoVC
// sessionManager?.remove(self)
}
And this is on my AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let castAppID = "myKey"
let options = GCKCastOptions.init(receiverApplicationID: castAppID)
GCKCastContext.setSharedInstanceWith(options)
GCKLogger.sharedInstance().delegate = self
I got it. My issue was in the Google Cast Console i had a remote receiver. Need to have a custom style receiver or media. So make sure you have that right!! Or just use a kGCKMediaDefaultReceiverApplicationID on your AppID to get the default one.

Send Name and Birthday to Watch using WatchConnectivity

I’m accessing a users Contacts to send the contact Name and Birthday from the iPhone to the AppleWatch. I have access to the Contacts and can display the data on the phone, but I’m having trouble sending the info with WatchConnectivity. I'm using the Ray Wenderlich book WatchOS by Tutorials as a guide but am still having trouble.
Here is what I have on the Phone side to set up Watch Connectivity in AppDelegate.swift.
// MARK: Watch Connectivity
extension AppDelegate: WCSessionDelegate {
func sessionDidBecomeInactive(_ session: WCSession) {
print("WC Session did become inactive.")
}
func sessionDidDeactivate(_ session: WCSession) {
print("WC Session did deactivate.")
WCSession.default().activate()
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("WC Session activation failed with error:" + "\(error.localizedDescription)")
return
}
print("Phone activated with state:" + "\(activationState.rawValue)")
}
func setUpWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default()
session.delegate = self
session.activate()
}
}
}
And this in ViewController.swift
// MARK Watch Connectivity
extension ViewController {
func sendNameAndBirthdayToWatch() {
if WCSession.isSupported() {
let session = WCSession.default()
if session.isWatchAppInstalled {
let nameAndBirthday = ["name": nameLabel.text, "birthday": birthdayLabel.text]
do {
try session.updateApplicationContext(nameAndBirthday)
} catch {
print("Error")
}
}
}
}
}
I'm calling sendNameAndBirthdayToWatch() with a UIButton on the phone. As a prototype the phone currently displays the name and birthday on two separate labels pulled from the Contacts in the Xcode simulator so I at least know I'm getting the data.
On the watch in the ExtensionDelegate.swift I have.
// MARK: Watch Connectivity
extension ExtensionDelegate: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("Activation failed with error: \(error.localizedDescription)")
return
}
print("Watch activated with activation state: \(activationState.rawValue) ")
}
func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default()
session.delegate = self
session.activate()
}
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
if let name = applicationContext["name"] as? String, let birthday = applicationContext["birthday"] as? String {
InterfaceController.sharedInterfaceController.updateWatchLabel(name: name, birthday: birthday)
}
}
}
This is where I'm stuck. I'm not sure where I've gone wrong and/or how to move forward.
I'm calling updateWatchLabel() in the InterfaceController.swift on the watch, but I'm not seeing any results.
Thank you in advance for any help. I've been staring at this for a solid week and unfortunately the example project in the Wenderlich book is a bit too complicated for my understanding.
I'm using Xcode 8.2.1 and Swift 3.
In time I answered my own question.
Here is the code on the phone in ViewController.swift. The code remains the same as in my original post in AppDelegate.swift.
func sendMessageToWatch() {
if WCSession.isSupported() {
let session = WCSession.default()
if session.isWatchAppInstalled {
do {
let message = ["message": "A message as String"]
try session.updateApplicationContext(message)
} catch {
print("Error: \(error)")
}
} else if session.isWatchAppInstalled == false {
print("No watch app installed")
}
}
}
I am at the moment calling this function by pressing a UIButton on the phone. Then on the watch side in InterfaceController.swift for the receiving end. I basically moved the code from ExtensionDelegate.swift to InterfaceController.swift.
// MARK: Watch Connectivity
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if let error = error {
print("Activation failed with error: \(error.localizedDescription)")
return
}
print("Watch activated with activation state: \(activationState.rawValue) ")
}
func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default()
session.delegate = self
session.activate()
}
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
let message = applicationContext["message"] as? String
DispatchQueue.main.async(execute: {
self.label.setText(message)
})
}

WatchKit data not displaying

I'm passing data from iOS to WatchKit. I can't get the data to show that was received on the WatchKit side somehow though.
This works fine: iOS TableViewController
func getCloudKit() {
///...
let publicData = container.publicCloudDatabase
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
for play in results! {
let newPlay = Play()
newPlay.tColor = play["TColor"] as! String
do {
try WatchSessionManager.sharedManager.updateApplicationContext(["color" : newPlay.tColor])
NSLog("NewPColor: %#", newPlay.tColor)
} catch {
print(error)
}
self.objects.append(newPlay)
}
} else {
print(error)
}
}
}
This isn't calling any of the NSLogs or showing any of the data: WatchKit InterfaceController
import WatchConnectivity
class InterfaceController: WKInterfaceController, WCSessionDelegate {
#IBOutlet var colorLabel: WKInterfaceLabel!
private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
private func configureWCSession() {
session?.delegate = self;
session?.activateSession()
}
override init() {
super.init()
configureWCSession()
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
let colorWatch = applicationContext["color"] as? String
NSLog("Check if anything here: %#", colorWatch!)
dispatch_async(dispatch_get_main_queue()) {
if let colorWatch = colorWatch {
self.colorLabel.setText("From iPhone: \(colorWatch)")
NSLog("Heres all the strings %#", colorWatch)
} else {
NSLog("Nothing")
}
}
}
}
Any ideas? Thanks!
Try checking if session is nil with something like (my swift foo is weak):
private func configureWCSession() {
print("session: \(session?))
session?.delegate = self;
session?.activateSession()
}

Resources