实现IPHONE或PAD与PC端WIFI传输文件

xiaoxiao2021-02-28  8

1 需要导入框架:   QuartzCore.framework  SystemConfiguration.framework  libicucore.dylib //GameKit.framework蓝牙传输需要导入 2 .h文件引入头文件 #import "HTTPServer.h" #import <QuartzCore/QuartzCore.h> #import <GameKit/GameKit.h> #import <SystemConfiguration/CaptiveNetwork.h> 3 遵守WebFileResourceDelegate//GKPeerPickerControllerDelegate,GKSessionDelegate协议 4 创建需要的对象    HTTPServer *myServer;                     //GKSession  *session;蓝牙链接,通过这个对象2个设备传输数据                     //GKPeerPickerController *myPicker; 5  创建socketServer     myServer = [[HTTPServer alloc] init];     [myServer setType:@"_http._tcp."];     [myServer setPort:8080];     [myServer setName:@"CocoaWebResource"];     [myServer setupBuiltInDocroot];     myServer.fileResourceDelegate = self; 6 开启移动端服务 - (IBAction)toggleService:(id)sender {         NSError *error;     if ([(UISwitch*)sender isOn])     {                 BOOL serverIsRunning = [httpServer start:&error];         if(!serverIsRunning)         {             NSLog(@"Error starting HTTP Server: %@", error);         }         [urlLabel setText:[NSString stringWithFormat:@"http://%@:%d", [myServer hostName], [httpServer port]]];         NSLog(@"httpWifiName------->%@",[myServer wifiName]);         [wifiNameLabel setText:[myServer wifiName]];             }     else     {         [myServer stop];         [urlLabel setText:@""];     } }    7 实现代理方法 - (NSInteger)numberOfFiles {     return [fileList count]; } // the file name by the index - (NSString*)fileNameAtIndex:(NSInteger)index {     return [fileList objectAtIndex:index]; } // provide full file path by given file name - (NSString*)filePathForFileName:(NSString*)filename {     //NSString* docDir = [NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()];     NSString *docDir;     NSString *type = [filename pathExtension];     if ([type isEqualToString:@"pdf"]) {         docDir = PDF_PATH;     }     else if ([type isEqualToString:@"doc"]||[type isEqualToString:@"docx"])     {         docDir = DOC_PATH;             }     else if ([type isEqualToString:@"png"]||[type isEqualToString:@"jpg"])     {         docDir = IMAGES_PATH;             }     else{         docDir =OTHERS_PATH;     }    // NSString *docDir = DOCUMENTS_PATH;     return [NSString stringWithFormat:@"%@/%@", docDir, filename]; } // handle newly uploaded file. After uploading, the file is stored in // the temparory directory, you need to implement this method to move // it to proper location and update the file list. - (void)newFileDidUpload:(NSString*)name inTempPath:(NSString*)tmpPath {     if (name == nil || tmpPath == nil)         return;     //NSString* docDir = [NSString stringWithFormat:@"%@/Documents", NSHomeDirectory()]; //    NSString *docDir = DOCUMENTS_PATH;     NSString *docDir;     NSString *type = [name pathExtension];     if ([type isEqualToString:@"pdf"]) {         docDir = PDF_PATH;     }     else if ([type isEqualToString:@"doc"]||[type isEqualToString:@"docx"])     {         docDir = DOC_PATH;             }     else if ([type isEqualToString:@"png"]||[type isEqualToString:@"jpg"])     {         docDir = IMAGES_PATH;             }     else{         docDir =OTHERS_PATH;     }     NSString *path = [NSString stringWithFormat:@"%@/%@", docDir, name];     NSLog(@"newFileDidUpLoad----name---->%@",path);     NSFileManager *fm = [NSFileManager defaultManager];     NSError *error;     if (![fm moveItemAtPath:tmpPath toPath:path error:&error])     {         NSLog(@"can not move %@ to %@ because: %@", tmpPath, path, error );     }         [self loadFileList];     } // implement this method to delete requested file and update the file list - (void)fileShouldDelete:(NSString*)fileName {     NSString *path = [self filePathForFileName:fileName];     NSFileManager *fm = [NSFileManager defaultManager];     NSError *error;     if(![fm removeItemAtPath:path error:&error])     {         NSLog(@"%@ can not be removed because:%@", path, error);     }     [self loadFileList]; } #pragma -----buletooth----- //=================================蓝牙相关方法========================================== -(void)connectionButtonTapped {     // allocate and setup the peer picker controller     bpicker = [[GKPeerPickerController alloc] init];     bpicker.delegate = self;     bpicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;     [bpicker show];     } -(GKSession *)peerPickerController:(GKPeerPickerController *)picker sessionForConnectionType:(GKPeerPickerConnectionType)type {     currentSession = [[GKSession alloc] initWithSessionID:@"FR" displayName:nil sessionMode:GKSessionModePeer];     currentSession.delegate = self;         return currentSession; } //方法功能:判断数据传输状态 -(void)session:(GKSession*)session peer:(NSString*)peerID didChangeState:(GKPeerConnectionState)state {     switch (state) {         case GKPeerStateConnected:             [currentSession setDataReceiveHandler :self withContext:nil];         //    [connectionButton setEnabled:NO];             //[DisconnectButton setEnabled:YES];             NSLog(@"连接");             break;         case GKPeerStateDisconnected:         //    [connectionButton setEnabled:YES];             //[DisconnectButton setEnabled:NO];             NSLog(@"连接断开");             //[currentSession release];             currentSession=nil;             break;     } } - (void)peerPickerController:(GKPeerPickerController *)picker didConnectToPeer:(NSString *)peerID {     printf("连接成功!\n"); } - (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker {     printf("连接尝试被取消 \n"); } //方法功能:接受数据 -(void)receiveData:(NSData*)data fromPeer:(NSString*)peer inSession:(GKSession*)session context:(void*)context {     // Read the bytes in data and perform an application-specific action, then free the NSData object         //[self animationShow];     NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];         NSDictionary *ndata = [aStr objectFromJSONString];         NSLog(@"接受数据: %@", ndata);         NSString *bankStr = [ndata objectForKey:bank];     NSString *numberStr = [ndata objectForKey:cnumber];         NSString *atr = [ndata objectForKey:money];     NSLog(@"bankStr===%@\n number====%@\n atr====%@",bankStr,numberStr,atr);                 } //方法功能:断开链接 //- (IBAction) DisconnectButtonTapped:(id) sender{ //    //    [self.currentSession disconnectFromAllPeers]; //    currentSession=nil; //    [connectionButton setEnabled:YES]; //    //[DisconnectButton setEnabled:NO]; //    //} //方法功能:发送一个数据包 -(void)mySendDataToPeers:(NSMutableData*)data {     NSLog(@"发送一个数据包");     if (currentSession) {         [currentSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];     } } //方法功能:连接失败 -(void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString*)peerID toSession:(GKSession *)session{     currentSession=session;     session.delegate=self;     [session setDataReceiveHandler:self withContext:nil];     picker.delegate=nil;     [picker dismiss];     }
转载请注明原文地址: https://www.6miu.com/read-450163.html

最新回复(0)