简体   繁体   中英

Send and receive key/value pair using gcdasyncsocket over wifi

I've made an iOS app that receives RSSI values from a BLE Beacon and sends (using GCDAsynSocket) it to a connected MacBook over wifi. My next app on the MacBook receives the RSSI values and saves (using NSOutpuStream class) it in .txt format. Now, I need to send RSSI values from eight different BLE beacons and their respective MAC address in key/value pairs. I tried to solve it using NSKeyedArchiver to encode NSDictionary into NSData.

NSData *data = [NSKeyedArchiver archivedDataWithRootObject: NSDictionaryContaningKeyValuePair];

And on the receiver's end (MacBook), I used NSUnarchiver to decode. I am unable to extract the NSDictionary containing key/value (MAC address/RSSI values) pair and store it to the .txt file. Moreover, since NSoutputStrteam write method takes nonnull const uint8_t value, how can I write the Key/value pair in the .txt file? I use Objective-C and Xcode (7.0).

Thank you.

Got the solution. NSDictionary can be sent using NSJSONSerialization class. At transmitter's end (iOS):

NSDictionary* dictInfo = [NSDictionary dictionaryWithObjectsAndKeys:self.txtInfo.text,@"data", nil];
NSData* dataDict = [NSJSONSerialization dataWithJSONObject:dictInfo options:NSJSONWritingPrettyPrinted error:nil];
[self.socket writeData:dataDict withTimeout:-1.0f tag:0];

At receiver's end (MacBook):

 if ([self getSelectedSocket]== sock) {
    [_dataBuffer appendData:data];
    if ([sock socketAvailableBytes] == 0) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_dataBuffer options:NSJSONReadingMutableLeaves error:nil];
        DLog("Dictionary Info: %@", dict);
        NSString* strInfo =  (NSString*)[dict objectForKey:@"data"];
        [_dataBuffer setLength:0];
        self.txtLogs.stringValue= strInfo;

For further information please visit https://github.com/boobalaninfo/Bonjour-iOS-MAC-Apps .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM