流程是:
1、显示蓝牙设备选择控制器,设置代理协议
2、实现代理方法
3、发送数据,设置接收函数
GKsession使用
#import "ViewController.h"
#import <GameKit/GameKit.h>
@interface ViewController ()<GKPeerPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *pic;
@property (nonatomic,strong) GKSession *session;
- (IBAction)selectPic:(id)sender;
- (IBAction)sendPic:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//显示其他蓝牙设备
GKPeerPickerController *ppController=[[GKPeerPickerController alloc] init];
ppController.delegate=self;
[ppController show];
}
- (void)peerPickerController:(nonnull GKPeerPickerController *)picker didConnectPeer:(nonnull NSString *)peerID toSession:(nonnull GKSession *)session
{
self.session=session;
[session setDataReceiveHandler:self withContext:nil];
[picker dismiss];
}
- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
{
self.pic.image=[UIImage imageWithData:data];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)selectPic:(id)sender {
UIImagePickerController *pickerVC=[[UIImagePickerController alloc] init];
pickerVC.delegate=self;
[self presentViewController:pickerVC animated:YES completion:nil];
}
- (void)imagePickerController:(nonnull UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info
{
UIImage *img=info[UIImagePickerControllerOriginalImage];
self.pic.image=img;
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(nonnull UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)sendPic:(id)sender {
UIImage *img=self.pic.image;
NSData *data=UIImagePNGRepresentation(img);
[self.session sendDataToAllPeers:data withDataMode:GKSendDataUnreliable error:nil];
}
@end