在iOS中通过蓝牙在两个设备之间传输NSString

Dis*_*ant 5 iphone bluetooth file-transfer nsstring ios

我想NSString通过蓝牙在两个iOS设备之间转移.任何人都可以帮助如何NSString通过蓝牙传输?我搜索了具体的答案和示例代码,但找不到它.请指导我.

提前致谢.!!

Lyn*_*ott 14

我将更广泛地评论如何使用MCSession这种简单的情况,因为当我第一次熟悉自己时MCSession,我很惊讶于如何利用简单MCSession而没有添加额外的一层的信息很少MCBrowserViewController.

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

在.m中,在viewDidLoad期间或您希望开始之前的任何其他时间MCSession,初始化您的MCPeerID:

devicePeerId = [[MCPeerID alloc] initWithDisplayName:DISPLAY_NAME];
Run Code Online (Sandbox Code Playgroud)

然后用它MCPeerID来初始化MCSession:

session = [[MCSession alloc] initWithPeer:devicePeerId securityIdentity:nil encryptionPreference:MCEncryptionNone];
session.delegate = self;
Run Code Online (Sandbox Code Playgroud)

现在,为了避免使用MCBrowserViewController,你必须自己创建MCNearbyServiceAdvertiser允许你的设备宣传会话,MCNearbyServiceBrowser允许你的设备找到会话,或者你甚至可以在同一台设备上同时启动以允许同时进行广告和浏览:

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;
Run Code Online (Sandbox Code Playgroud)

接下来,如果您已将设备设置为广告客户,则需要实施这些MCNearbyServiceAdvertiserDelegate方法.

要从浏览对等方发送邀请:

- (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);

}
Run Code Online (Sandbox Code Playgroud)

如果设备由于某种原因尚未开始投放,则会收到错误消息:

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

同样,如果您将设备设置为浏览器,则需要实现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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

[session sendData:[@"text" dataUsingEncoding:NSUTF8StringEncoding] toPeers:[NSArray arrayWithObject:peerID] withMode:MCSessionSendDataReliable error:&error];
Run Code Online (Sandbox Code Playgroud)

一旦用户与他的同伴联系,就立即传输数据.但是这行可以用来在代码中的其他地方发送数据,例如:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

最后,启动/停止广告的广告客户和/或浏览器,你可以打电话[_serviceAdvertiser start/stopAdvertisingPeer],[_nearbyServiceBrowser start/stopBrowsingForPeers]:

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

- (void)stop {
    [serviceAdvertiser stopAdvertisingPeer];
    [nearbyServiceBrowser stopBrowsingForPeers];
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法,但这些是基础知识.尽快写出来,所以任何人都应该随意修改!


Sat*_*zad 1

查看苹果开发者论坛BTLE Transfer源代码

我希望这将帮助您使用蓝牙将字符串或任何数据从一台设备传输到另一台设备。