理解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