//
// ViewController.m
// 08-蓝牙 GameKit
//
// Created by Romeo on 15/9/26.
// Copyright © 2015年 itheima. All rights reserved.
//
#import "ViewController.h"
#import <GameKit/GameKit.h>
@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, GKPeerPickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
/** 会话对象 管理数据的接受和发送 */
@property (nonatomic, strong) GKSession *session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - 连接设备
- (IBAction)connectDeviceClick:(id)sender {
//1. 创建连接控制器
GKPeerPickerController *picker = [GKPeerPickerController new];
//2. 设置代理
picker.delegate = self;
//3. 显示连接控制器 show
[picker show];
}
#pragma mark PeerPickerController 代理方法
//当连接到设备时会调用
//peerID : 另外一台设备 ID
//session: 会话对象(管理数据发送和接受)
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
//1. 保留 Session (发送数据不在此方法)
self.session = session;
//2. 接受到数据应该做些处理 --> 设置句柄 --> 相当于设置代理. 一旦实现此方法, 必须配合另一个方法
[self.session setDataReceiveHandler:self withContext:nil];
//3. 消失控制器
[picker dismiss];
}
#pragma mark setDataReceiveHandler必须要实现的方法
// 接受到数据才会调用此方法
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
// 当前程序接受另外一个程序发过来的 image
// 应该显示 image 到控制器上
//1. 接受到的数据转换成 image
UIImage *image = [[UIImage alloc] initWithData:data];
//2. 让 image显示到图形上
self.imageView.image = image;
}
#pragma mark - 发送照片
- (IBAction)sendImageClick:(id)sender {
// 需要获取图像来发送数据
//1. 获取图像
NSData *data = UIImageJPEGRepresentation(self.imageView.image, 0.5);
//2. 需要 session 类来发送数据
//GKSendDataReliable 数据可到达 --> 如果数据没有发送成功, 会继续发送
//GKSendDataUnreliable 数据不可到达 --> 数据发送失败, 不会继续发送
[self.session sendDataToAllPeers:data withDataMode:GKSendDataReliable error: nil];
}
#pragma mark - 选择照片
- (IBAction)selectImageClick:(id)sender {
UIImagePickerController *picker = [UIImagePickerController new];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
#pragma mark 选择照片代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
//1. 获取选中的图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
NSLog(@"imag: %@",image);
//2. 显示照片
self.imageView.image = image;
//3. 消失控制器
[picker dismissViewControllerAnimated:YES completion:nil];
}
@end