理解iOS7的Multipeer Connectivity框架

例子可跑

http://www.oschina.net/translate/intro-multipeer-connectivity-framework-ios-programming?lang=chs&page=1#

git
https://github.com/kakegawa-atsushi/MultipeerConnectivitySample


//
// FirstViewController.m
// MCDemo
//
//

#import "FirstViewController.h"
#import "AppDelegate.h"

@interface FirstViewController ()

@property (nonatomic, strong) AppDelegate *appDelegate;

-(void)sendMyMessage;
-(void)didReceiveDataWithNotification:(NSNotification *)notification;

@end

@implementation FirstViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

_txtMessage.delegate = self;

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveDataWithNotification:)
name:@"MCDidReceiveDataNotification"
object:nil];
}

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


#pragma mark - UITextField Delegate method implementation

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[self sendMyMessage];
return YES;
}


#pragma mark - IBAction method implementation

- (IBAction)sendMessage:(id)sender {
[self sendMyMessage];
}

- (IBAction)cancelMessage:(id)sender {
[_txtMessage resignFirstResponder];
}


#pragma mark - Private method implementation

-(void)sendMyMessage{
NSData *dataToSend = [_txtMessage.text dataUsingEncoding:NSUTF8StringEncoding];
NSArray *allPeers = _appDelegate.mcManager.session.connectedPeers;
NSError *error;

[_appDelegate.mcManager.session sendData:dataToSend
toPeers:allPeers
withMode:MCSessionSendDataReliable
error:&error];

if (error) {
NSLog(@"%@", [error localizedDescription]);
}

[_tvChat setText:[_tvChat.text stringByAppendingString:[NSString stringWithFormat:@"I wrote:\n%@\n\n", _txtMessage.text]]];
[_txtMessage setText:@""];
[_txtMessage resignFirstResponder];
}


-(void)didReceiveDataWithNotification:(NSNotification *)notification{
MCPeerID *peerID = [[notification userInfo] objectForKey:@"peerID"];
NSString *peerDisplayName = peerID.displayName;

NSData *receivedData = [[notification userInfo] objectForKey:@"data"];
NSString *receivedText = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

[_tvChat performSelectorOnMainThread:@selector(setText:) withObject:[_tvChat.text stringByAppendingString:[NSString stringWithFormat:@"%@ wrote:\n%@\n\n", peerDisplayName, receivedText]] waitUntilDone:NO];
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值