What is Multipeer Connectivity?
In IOS7, a new framework--multipeer Connectivity (multipoint connection) is introduced. With the Multipeer connectivity framework, even when there is no connection to WiFi (Wi-Fi) or mobile network (XG), the proximity of Apple devices (Imac/ipad/iphone) can be based on Bluetooth and WiFi (peer WiFi) technology for discovery and connectivity for near field communication.
The Multipeer connectivity expansion function is very similar to the use of AirDrop transfer files, which can be viewed as compensation that airdrop cannot use directly, at the expense of its own implementation.
This demo mainly uses 4 kinds of classes:
MCBrowserViewController
: Mcbrowserviewcontroller inherits from Uiviewcontroller and provides a basic UI application framework.
MCAdvertiserAssistant
, Mcadvertiserassistant is the management assistant for Advertiser encapsulation, which mainly deals with broadcast information.
MCSession
: A socket similar to a TCP link. When you create Mcsession, you specify your own Mcpeerid, similar to bind.
MCPeerID
: Similar to sockaddr, used to identify both ends of a connection endpoint, usually a nickname or device name.
1, simple to establish an interface, mainly connected and sent 2 UIButton.
Create_button.png
2. The Multipeer Connectivity Framework initializes these 4 classes.
#pragma mark-wifi sharing methods-(void) setupmultipeer { // setup peer ID Self.mypeerid = [[Mcpeerid alloc] Initwithdisplayname:[uidevice currentdevice].name]; // setup session self.mysession = [[Mcsession alloc] InitWithPeer:self.myPeerID]; self.mysession.delegate = self; // setup browserviewcontroller SELF.BROWSERVC = [[Mcbrowserviewcontroller alloc] initwithservicetype:@ "chat" session:self.mySession]; self.browservc.delegate = self; // setup Advertiser Self.advertiser = [[Mcadvertiserassistant alloc] initwithservicetype:@ "chat" Discoveryinfo:nil session:self.mySession]; [Self.advertiser start]; } -(void) SHOWBROWSERVC { [self PresentViewController:self.browserVC animated:yes completion:nil];} -(void) DISMISSBROWSERVC { [SELF.BROWSERVC Dismissviewcontrolleranimated:yes completion:^ (void) { [self invokealertmethod:@ "connection succeeded" body:@ "Both device connected successfully." Delegate:nil]; }]; } -(void) stopwifisharing: (BOOL) isclear { if (isclear && self.mysession! = nil) { & nbsp [self.mysession disconnect]; [self.mysession Setdelegate:nil]; self.mysession = nil;  SELF.BROWSERVC = nil; }}
3. MCBrowserViewController
Agent Method
#pragma marks MCBrowserViewControllerDelegate// 点击完成-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController { [self dismissBrowserVC]; [marrReceiveData removeAllObjects]; }// 点击取消-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController { [self dismissBrowserVC]; }
4. MCSession
Agent Method
Primarily deals with files or information transmitted by the sender
Received data from remote peer-(void) session: (Mcsession *) session Didreceivedata: (NSData *) data frompeer: (Mcpeerid *) Peerid { nslog (@ "Data receiveddddd:%lu", (unsigned long) data.length); if (data.length > 0) { if (Data.length < 2) { noofdatasend++ &NB Sp nslog (@ "Noofdatasend:%zd", noofdatasend); nslog (@ "Array count:%zd", Marrfiledata.count); if (Noofdatasend < ([Marrfiledata Count])) { &NBSP ; [self.mysession senddata:[marrfiledata Objectatindex:noofdatasend] Topeers:[self.mysession Connectedpeers] Withmode:mcsessionsenddatareliable Error:nil]; }else { [self.mysession senddata:[@ "File Transfer Done" datausingencoding:nSutf8stringencoding] topeers:[self.mysession connectedpeers] withmode:mcsessionsenddatareliable Error:nil]; } } else { if ([[[[NSString Alloc] initwithdata:data encoding:nsutf8stringencoding] isequaltostring:@ "File Transfer Done"]) { [self appendfiledata]; }else { [self.mysession senddata:[@ "1" datausingencoding:nsutf8stringencoding] topeers:[self.mysession connectedpeers] WithMode: Mcsessionsenddatareliable Error:nil]; [Marrreceivedata Addobject:data]; { } }}//Received a byte stream from Remote peer-(void) session: (Mcsession *) session Didreceivestream: (Nsinputstream *) stream withname: (NSString *) Streamname frompeer: (Mcpeerid *) Peerid { nslog (@ "did receive stream");} Start receiving a resource from remote peer-(void) session: (Mcsession *) session Didstartreceivingresourcewithname: ( NSString *) resourcename frompeer: (Mcpeerid *) Peerid withprogress: (nsprogress *) Progress { nslog (@ "Start Receiving "); }//finished receiving a resource from remote peer and saved the content in a temporary location-the app is responsible For moving the file to a permanent location within its sandbox-(void) session: (Mcsession *) session Didfinishreceivingresou Rcewithname: (NSString *) resourcename frompeer: (Mcpeerid *) Peerid Aturl: (Nsurl *) localurl witherror: (NSError *) Error {& nbsp nslog (@ "finish receiving resource"); } -(void) session: (Mcsession *) session Peer: (Mcpeerid *) Peerid didchangestate: (mcsessionstate) state { nslog (@ "Change state:%zd", state); }
5, Send pictures (this demo is simply to do a send and receive pictures of the demo, this framework can be implemented more than that simple function.) )
-(void) SendData { [marrfiledata removeallobjects]; nsdata *senddata = Uiimagepngrepresentation ([UIImage imagenamed:@ "Test2.png"]); nsuinteger length = [senddata length]; nsuinteger chunkSize = 100 * 1024; nsuinteger offset = 0; do { nsuinteger thischunksize = length-offset > chunkSize? chunksize:lengt H-offset; nsdata* chunk = [NSData datawithbytesnocopy: (char *) [senddata bytes] + offset &NB Sp , &NB Sp length:thischunksize &NBS ------ P freeWhenDone:NO]; nslog (@ "Chunk length:%lu", (unsigned long) chunk.length); [marrfiledATA Addobject:[nsdata Datawithdata:chunk]; offset + = thischunksize; } while (offset < length); noofdata = [Marrfiledata count]; Noofdatasend = 0; if ([marrfiledata Count] > 0) { [self.mysession senddata:[marrfiledata objecta Tindex:noofdatasend] topeers:[self.mysession connectedpeers] withmode:mcsessionsenddatareliable Error:nil]; } -(void) appendfiledata { nsmutabledata *filedata = [Nsmutabledata data]; for (int i = 0; i < [Marrreceivedata count]; i++) { [FileData appenddata:[marrreceivedata O BJECTATINDEX:I]]; [filedata writetofile:[nsstring stringwithformat:@ "%@/image.png", [nshomedirectory () stringbyappendingpathcomponent:@ "Documents"] atomically:yes]; uiimagewritetosavedphotosalbum ([UIImage Imagewithdata:filedata], self, @selector (imagE:didfinishsavingwitherror:contextinfo:), nil); } -(void) Image: (UIImage *) image didfinishsavingwitherror: (nserror *) error ContextInfo: (void *) ContextInfo { if (!error) { [self invokealertmethod:@ "send success" body:@ "Picture saved to Mobile album" Delegate:nil]; nbsp }}
You can download the full demo:https://github.com/janztam/wifisharedemo on GitHub.
WiFi transfer using the Multipeer connectivity framework-B