學習新技術時碰上watchConnectivity,

它可使iOS app與appleWatch app兩者傳遞資料,

圖檔文字皆可, 但目前只使用過傳遞文字,

而由於就專案使用objectiveC製作, 

線上的watchOS2較多Swift資源, 

所以此範例在watch上則使用swift,

首先在viewdidload中得先加入以下程式碼, watch與主app都要

if([WCSession isSupported])
    {
        self.watchSession = [WCSession defaultSession];
        self.watchSession.delegate = self;
        [self.watchSession activateSession];
    }

 已上主要是確保兩者之間有確定連線狀態, 最後啟動activateSession

 在watch端則使用digitalCrown去控制傳輸之數字, 所以使用WKInterfacepicker

 傳輸資料則寫在sendMessage當中,

watch端完整程式碼如下 

import WatchKit
import Foundation
import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {

    let session = WCSession.defaultSession()
    
    @IBOutlet var picker: WKInterfacePicker!
    @IBAction func digitalCrownChange(value: Int) //抓取picker改變數值時丟入
    {
        if WCSession.isSupported()
        {
            let data = ["number" : value]
            session.sendMessage(data, replyHandler:
                { (content:[String : AnyObject]) -> Void in print("Our counterpart sent something back.")},
                errorHandler: {(error ) -> Void in print(error.domain)})
            print("send message")
            
        }
        print("digitalCrownChanged")
    }
    
    override func awakeWithContext(context: AnyObject?)
    {
        super.awakeWithContext(context)
        
        // Configure interface objects here.
        
        /* create picker items */
        var pickerItems: [WKPickerItem]! = []
        
        for (var i=1; i<=10; i++)
        {
            let pickerItem = WKPickerItem()
            pickerItem.title = "\(i)"
            pickerItems.append(pickerItem)
        }
        picker.setItems(pickerItems)

    }
    

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
        
        if(WCSession.isSupported()){
            session.delegate = self
            session.activateSession()
        }
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

}

app端則要創建一個receiver來接受sendMessage傳送之數值, 完整範例如下

#import "ViewController.h"
#import <Foundation/Foundation.h>

static int num = 100;

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel *numLabel;
@property (nonatomic) WCSession* watchSession;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _numLabel.text = [NSString stringWithFormat:@"%d", num];
    
    if([WCSession isSupported])
    {
        self.watchSession = [WCSession defaultSession];
        self.watchSession.delegate = self;
        [self.watchSession activateSession];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message
{
    NSLog(@"received message");
    NSNumber *watchNumber = [message objectForKey:@"number"];
    
    dispatch_async(dispatch_get_main_queue(), ^()
    {
        _numLabel.text =[NSString stringWithFormat:@"%@", watchNumber];
        NSLog(@"received message");
    });
}



@end

 

arrow
arrow
    文章標籤
    watchConnectivity watchOS2
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()