iOS中的WiFi与硬件通信
生活随笔
收集整理的這篇文章主要介紹了
iOS中的WiFi与硬件通信
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
WiFi通信是指手機通過WiFi與外部設備建立連接,并與外部設備進行交互、通信。手機與外部設備的WiFi通信通常是使用Socket來實現(xiàn)的,在這里先介紹一個第三方Socket庫(CocoaAsyncSocket)來實現(xiàn)WiFi通信。
CocoaAsyncSocket支持TCP和UDP,其中:
AsyncSocket類是支持TCP的;
AsyncUdpSocket類是支持UDP的。
本文是建立在硬件通過UDP廣播包廣播自身信息,手機與硬件之間通過TCP連接傳輸數(shù)據(jù)。
WiFi連接的建立
首先,通過手動連接手機WiFi至外部設備,此時可以獲取到外部WiFi的一些信息:
#import <UIKit/UIKit.h>@interface ViewController : UIViewControllertypedef void (^udpSocketBlock)(NSDictionary* dic,NSError* err);// block用于硬件返回信息的回調 @property (nonatomic,copy) udpSocketBlock udpSocketBlock; - (void)sendUdpBoardcast:(udpSocketBlock)block; @end #import "ViewController.h" #import <AsyncSocket.h> #import <AsyncUdpSocket.h> @interface ViewController ()<AsyncSocketDelegate,AsyncUdpSocketDelegate> @property (nonatomic,strong) AsyncUdpSocket *udpSocket; @property (nonatomic,strong) AsyncSocket *socket; @end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad]; }- (void)sendUdpBoardcast:(udpSocketBlock)block{self.udpSocketBlock = block;if(!_udpSocket)_udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];NSData *data = [NSData data];// 此處data是根據(jù)硬件要求傳參數(shù)UInt16 port = 34343;// 此處具體指需詢問硬件工程師[self.udpSocket enableBroadcast:YES error:NULL];[_udpSocket sendData:data toHost:@"255.255.255.255" port:port withTimeout:-1 tag:0];// 因為不知道具體的ip地址,所以host采用受限廣播地址 } - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port{ // data 接收到的外部設備返回的數(shù)據(jù)id result = [self unpackageMessage:data]; // 對數(shù)據(jù)進行處理,此處調用的 - (id)unpackageMessage:(NSData *)data ;是根據(jù)與硬件方面協(xié)商的數(shù)據(jù)格式進行的數(shù)據(jù)處理if ([[result valueForJSONKey:@"typeid"] isEqualToString:@"xxxx"]) {self.udpSocketBlock([result valueForJSONKey:@"data"],nil);} // 判斷的到的數(shù)據(jù)是否為我們需要的數(shù)據(jù)return YES; // 發(fā)現(xiàn)設備后,則關閉發(fā)現(xiàn)通道return NO; // 不關閉發(fā)現(xiàn)通道,一直處于發(fā)現(xiàn)狀態(tài) } #pragma mark - udpSocket -(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag{}通過調用該方法,可以得到外部設備返還的WiFi信息:
[self sendUdpBoardcast:^(NSDictionary *dic, NSError *err) {// dic為硬件返回的參數(shù) }];獲取硬件參數(shù)之后,需要確認手機是否已于硬件連接,直接調用方法
- (BOOL)isConnected;若未連接,則需建立手機和硬件之間的socket連接:
- (BOOL)connectToHost:(NSString*)hostname onPort:(UInt16)port error:(NSError **)errPtr; // hostname、port均為硬件返回的數(shù)據(jù)的寫入和讀取
CocoaAsyncSocket提供了寫入數(shù)據(jù)和讀取數(shù)據(jù)的方法:
// 數(shù)據(jù)的寫入 - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag; // 數(shù)據(jù)的讀取 - (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag;數(shù)據(jù)寫入具體格式需要根據(jù)硬件要求來決定,這里提供幾種常用的數(shù)據(jù)類型轉換方法以供參考:
- 十六進制字符串轉NSData -(NSData *)converHexStrToData:(NSString *)hexString {NSMutableData *data = [[NSMutableData alloc] init];unsigned char whole_byte;char byte_chars[3] = {'\0','\0','\0'};if (hexString.length%2) {//防止丟失半個bytehexString = [@"0" stringByAppendingString:hexString];}int i;for (i = 0; i < [hexString length]/2; i++) {byte_chars[0] = [hexString characterAtIndex:i * 2];byte_chars[1] = [hexString characterAtIndex:i * 2 + 1];whole_byte = strtol(byte_chars, NULL, 16);[data appendBytes:&whole_byte length:1];}return data; }
- NSData轉十六進制字符串 -(NSString *) converDataToHexString:(NSData *)data {if (data == nil) {return nil;}NSMutableString* hexString = [NSMutableString string];const unsigned char *p = [data bytes];for (int i=0; i < [data length]; i++) {[hexString appendFormat:@"%02x", *p++];}return hexString; }
- 十六進制字符串轉普通字符串 -(NSString *)stringFromHexString:(NSString *)hexString {char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);bzero(myBuffer, [hexString length] / 2 + 1);for (int i = 0; i < [hexString length] - 1; i += 2) {unsigned int anInt;NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];[scanner scanHexInt:&anInt];myBuffer[i / 2] = (char)anInt;}NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];return unicodeString; }
總結
以上是生活随笔為你收集整理的iOS中的WiFi与硬件通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SQL -- 多表查询
- 下一篇: iOS开发--地图与定位