THIS CONTENT DOWNLOAD SHORTLY

Objective

The main objective of this post is to describe how to share file between two apple devices using WiFi.

 

In following demo I have described how to connect two devices using WiFi and then share large size image file by dividing it in data chunks and save shared file in camera roll of other device.

Note

To connect devices and share file application must be installed in both devices. Turn Off Bluetooth while WiFi sharing, as it will interfere WiFi.

 

Step 1 Create Xcode Project

Create new XCode project name it as FileShareDemo. It contains one UIViewController Main.storyboard file.

 

Step 2 Design UI

Add two UIButton in UIVIewController and set title Connect and Share respectively in both UIButton.

 

Step 3 Add Framework

Add MultipeerConnectivity framework in your project. Also add .png file which you want to share.

 

Step 4 Implement delegate & make variables

In ViewController.h file you have to import MultipeerConnectivity framework, set delegate and declare property as below.

#import <UIKit/UIKit.h>
#import <MultipeerConnectivity/MultipeerConnectivity.h>
 
@interface ViewController : UIViewController <MCBrowserViewControllerDelegate, MCSessionDelegate>
{
__block BOOL _isSendData;
NSMutableArray *marrFileData, *marrReceiveData;
int noOfdata, noOfDataSend;
}
 
@property (nonatomic, strong) MCBrowserViewController *browserVC;
@property (nonatomic, strong) MCAdvertiserAssistant *advertiser;
@property (nonatomic, strong) MCSession *mySession;
@property (nonatomic, strong) MCPeerID *myPeerID;
 
@end
 

Step 5 Initialized Array

Initialize both NSMutableArray object in viewDidLoad() method.

- (void)viewDidLoad
{
[super viewDidLoad];
marrFileData = [[NSMutableArray alloc] init];
marrReceiveData = [[NSMutableArray alloc] init];
}
 

Step 6 Code in setUpMultipeer

Initialize MCSession object, MCBrowserViewController object, and MCPeerID object in setUpMultipeer() method.

-(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];
}

Also implement below methods in your ViewController.m file.

-(void)showBrowserVC
{
[self presentViewController:self.browserVC animated:YES completion:nil];
}
 
-(void)dismissBrowserVC
{
[self.browserVC dismissViewControllerAnimated:YES completion:nil];
}
 
-(void)stopWifiSharing:(BOOL)isClear
{
if(isClear && self.mySession != nil){
[self.mySession disconnect];
 
[self.mySession setDelegate:nil];
 
self.mySession = nil;
 
self.browserVC = nil;
}
}
 

Step 7 Code in IBAction method

Call setUpMultipeer and showBrowserVC methods from connect button action method.

-(IBAction)btnConnectClicked:(id)sender
{
if (!self.mySession) {
[self setUpMultipeer];
}
[self showBrowserVC];
}
 

Step 8 MCBrowserViewControllerDelegate methods

Implement MCBrowserViewControllerDelegate methods.

#pragma marks MCBrowserViewControllerDelegate
// Notifies the delegate, when the user taps the done button
-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController
{
[self dismissBrowserVC];
[marrReceiveData removeAllObjects];
}
 
// Notifies delegate that the user taps the cancel button.
-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController
{
[self dismissBrowserVC];
}
 

Step 9 Code for sendData

Now in sendData method divide your image in data chunks and call sendData:toPeers:withMode:error method of MCSession object and pass data chunk in it to connected peer.

-(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 : length - offset;
NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[sendData bytes] + offset
length:thisChunkSize
freeWhenDone:NO];
NSLog(@"chunk length : %lu",(unsigned long)chunk.length);
 
[marrFileData addObject:[NSData dataWithData:chunk]];
offset += thisChunkSize;
// do something with chunk
} while (offset < length);
 
noOfdata = [marrFileData count];
noOfDataSend = 0;
 
if ([marrFileData count] > 0) {
[self.mySession sendData:[marrFileData objectAtIndex:noOfDataSend] toPeers:[self.mySession connectedPeers] withMode:MCSessionSendDataReliable error:nil];
}
}
 

Step 10 call sendData form IBAction

Call sendData method from send button action method.

- (IBAction)btnSendClicked:(id)sender
{
[self sendData];
}
 

Step 11 appendFileData method

Add appendFileData method to append all chunks and save file on receiver device and display alert message after image saved successfully in camera roll.

-(void)appendFileData
{
NSMutableData *fileData = [NSMutableData data];
 
for (int i = 0; i < [marrReceiveData count]; i++) {
[fileData appendData:[marrReceiveData objectAtIndex: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:@"Successfully Sent" Body:@"Image shared successfully and saved in Cameraroll." Delegate:nil];
}
}
 
- (void)invokeAlertMethod:(NSString *)strTitle Body:(NSString *)strBody Delegate:(id)delegate
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle
message:strBody
delegate:delegate
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
alert = nil;
}
 

Step 12 MCSessionDelegate methods

Add MCSessionDelegate methods.

#pragma marks MCSessionDelegate
- (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++;
NSLog(@"noofdatasend : %d",noOfDataSend);
NSLog(@"array count : %d",marrFileData.count);
if (noOfDataSend < ([marrFileData count])) {
[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];
}
}
}
}
 
- (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID
{
NSLog(@"did receive stream");
}
 
- (void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{
NSLog(@"start receiving");
}
 
- (void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error
{
NSLog(@"finish receiving resource");
}
 
-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
NSLog(@"change state : %d",state);
}

If you have got any query related to File Sharing using wifi in iOS then comment them below.

Got an Idea of iPhone App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best iPhone App Development Company in India.

I am iOS developer with an aspiration of learning new technology and creating a bright future in Information Technology.

face mask Belial The Demon Headgear Pocket Staff Magic