通过蓝牙在iOS中两个设备之间传输的NSString [英] Transfer NSString between two devices via bluetooth in iOS

查看:345
本文介绍了通过蓝牙在iOS中两个设备之间传输的NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想两个iOS设备之间传输的NSString ,通过蓝牙。任何人都可以帮怎么办转移的NSString 通过蓝牙?我搜索了具体的答案和样品code,但找不到它。请指引我。

I want to transfer NSString between two iOS device, via bluetooth. Can anybody please help how to do transfer NSString via bluetooth? I searched for specific answer and for sample code, but couldn't find it. Please guide me.

先谢谢了!!

推荐答案

我要评论更广泛你如何使用 MCSession 对于这种简单的情况下因为当我第一次用 MCSession 熟悉自己,我怎么是可如何利用一个简单的 MCSession 无需增加额外的层的 MCBrowserViewController

I'm going to comment more extensively on how you can use MCSession for this sort of simple case since when I was first familiarizing myself with MCSession, I was amazed at how little information was available on how to utilize a simple MCSession without adding the extra layer of an MCBrowserViewController.

在您的.H,添加以下代表: MCSessionDelegate MCNearbyServiceAdvertiserDelegate MCNearbyServiceBrowserDelegate 。同时声明类实例变量 MCPeerID * devicePeerID MCSession *会话 MCNearbyServiceAdvertiser * serviceAdvertiser MCNearbyServiceBrowser * nearbyServiceBrowser

In your .h, add the following delegates: MCSessionDelegate, MCNearbyServiceAdvertiserDelegate, and MCNearbyServiceBrowserDelegate. Also declare class instance variables for MCPeerID *devicePeerID, MCSession *session, MCNearbyServiceAdvertiser *serviceAdvertiser, and MCNearbyServiceBrowser *nearbyServiceBrowser.

在您的m,viewDidLoad中或要启动之前的任何时候你的 MCSession ,初始化 MCPeerID

In your .m, during viewDidLoad or any other time before you wish to start your MCSession, initialize your MCPeerID:

devicePeerId = [[MCPeerID alloc] initWithDisplayName:DISPLAY_NAME];

然后使用 MCPeerID 来初始化 MCSession

session = [[MCSession alloc] initWithPeer:devicePeerId securityIdentity:nil encryptionPreference:MCEncryptionNone];
session.delegate = self;

现在,为了避免使用 MCBrowserViewController ,你必须初始化自己的 MCNearbyServiceAdvertiser ,让您的设备做广告的会话, MCNearbyServiceBrowser ,让您的设备找到一个会话,或者你甚至可以初始化都是相同的设备,以便同时广告和浏览的:

Now, in order to avoid using the MCBrowserViewController, you have to init your own MCNearbyServiceAdvertiser to allow your device to advertise a session, MCNearbyServiceBrowser to allow your device to find a session, or you can even init BOTH on the same device to allow for simultaneous advertising and browsing:

serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:myDevicePeerId discoveryInfo:nil serviceType:SERVICE_TYPE];
serviceAdvertiser.delegate = self;
// (I've set discoveryInfo to nil here, but it can also contain an NSDictionary of data to pass along to browsers who find this advertiser via the browser:foundPeer:withDiscoveryInfo method)

nearbyServiceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:myDevicePeerId serviceType:SERVICE_TYPE];
nearbyServiceBrowser.delegate = self;

接下来,如果你设置该设备作为广告客户,则需要落实 MCNearbyServiceAdvertiserDelegate 方法。

要从浏览同行现场邀请:

To field invitations from browsing peers:

- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {

    NSLog(@"invitation received");

    if (want_to_accept_invitation)
        invitationHandler(YES, session);
    else
        invitationHandler(NO, session);

}

要收到一个错误,如果该设备还没有开始出于某种原因,广告:

To receive an error if the device has yet to start advertising for some reason:

- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didNotStartAdvertisingPeer:(NSError *)error {
    NSLog(@"Did not start advertising error: %@", error);
}

同样的,如果你设置该设备作为一个浏览器,你需要实现 MCNearbyServiceBrowserDelegate 方法:

// Peer found
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {

    NSLog(@"Session Manager found peer: %@", peerID);

    if (want_to_connect)
        [serviceBrowser invitePeer:peerID toSession:session withContext:nil timeout:CONNECTION_TIMEOUT];

} 

// Peer lost, ex. out of range
- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID {
    NSLog(@"Session Manager lost peer: %@", peerID);

}

- (void)browser:(MCNearbyServiceBrowser *)browser didNotStartBrowsingForPeers:(NSError *)error {
    NSLog(@"Did not start browsing for peers: %@", error);
}

然后,你需要在 MCSessionDelegate 方法来帮助改变通知连接状态的用户和方便的发送和接收数据的:

Then you need the MCSessionDelegate Methods to help notify the user of changing connection states and facilitate the sending and receiving of data:

- (void)session:(MCSession *)session didReceiveCertificate:(NSArray *)certificate fromPeer:(MCPeerID *)peerID certificateHandler:(void (^)(BOOL accept))certificateHandler {
    NSLog(@"Did receive certificate");
    certificateHandler(true);
}

// To detect changes in the state of your connections with your peers….
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state {

    switch (state) {
        case MCSessionStateConnected: {

            NSLog(@"Connected to %@", peerID);

            //  If you'd like to send your text string as soon as you're connected...
            NSError *error;
            [session sendData:[@"text" dataUsingEncoding:NSUTF8StringEncoding] toPeers:[NSArray arrayWithObject:peerID] withMode:MCSessionSendDataReliable error:&error];

            break;
        } case MCSessionStateConnecting: {
            NSLog(@"Connecting to %@", peerID);

            break;
        } case MCSessionStateNotConnected: {
            break;
        }
    }
}


- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID {
    NSLog(@"Did receive data.");

    /// Receive the string here.
    NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}

请注意,要发送的数据,我用:

Note that to send the data, I've used:

[session sendData:[@"text" dataUsingEncoding:NSUTF8StringEncoding] toPeers:[NSArray arrayWithObject:peerID] withMode:MCSessionSendDataReliable error:&error];

尽快发送的数据作为用户与他的同辈相连。但是,这条线可用于在code别处发送数据,例如:

to transmit the data as soon as the user's connected with his peers. But this line can be used to send data elsewhere in the code, ex:

- (void)sendMessageToAllPeers:(NSString *)message {
    [session sendData:[message dataUsingEncoding:NSUTF8StringEncoding] toPeers:session.connectedPeers withMode:MCSessionSendDataReliable error:&error];
}

- (void)sendMessage:(NSString *)message toPeerIDs:(NSArray *)peerIDs {
    [session sendData:[message dataUsingEncoding:NSUTF8StringEncoding] toPeers:peerIDs withMode:MCSessionSendDataReliable error:&error];
}

最后,启动/停止广告的广告客户和/或浏览器,你可以叫 [_ serviceAdvertiser启动/ stopAdvertisingPeer] [_ nearbyServiceBrowser启动/ stopBrowsingForPeers]

- (void)start {
    [serviceAdvertiser startAdvertisingPeer];
    [nearbyServiceBrowser startBrowsingForPeers];
}

- (void)stop {
    [serviceAdvertiser stopAdvertisingPeer];
    [nearbyServiceBrowser stopBrowsingForPeers];
}

有其他的方法,但这些是基本知识。写到这了相当快的,所以任何人都应该随意修改!

There are other methods, but these are the basics. Wrote this out fairly quickly though, so anyone should feel free to amend!

这篇关于通过蓝牙在iOS中两个设备之间传输的NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆