objective-c – Mac到蓝牙设备文件传输,简单的例子?

objective-c – Mac到蓝牙设备文件传输,简单的例子?,第1张

概述我花了两天谷歌搜索和阅读蓝牙编程指南,同时尝试拼凑一个小型Mac应用程序,它将从一个drop文件夹中检索图像,并通过蓝牙将任何新文件发送到预定的设备.似乎没有很多好的例子可供使用. 我正处于能够产生蓝牙服务浏览器并选择设备及其OBEX服务,建立服务和创建连接的地步,但之后不再发生任何事情.谁能指点我/向我展示一个可行的简单例子? 附带AppDelegate源代码.谢谢阅读! #import "A 我花了两天谷歌搜索和阅读蓝牙编程指南,同时尝试拼凑一个小型Mac应用程序,它将从一个drop文件夹中检索图像,并通过蓝牙将任何新文件发送到预定的设备.似乎没有很多好的例子可供使用.

我正处于能够产生蓝牙服务浏览器并选择设备及其OBEX服务,建立服务和创建连接的地步,但之后不再发生任何事情.谁能指点我/向我展示一个可行的简单例子?

附带AppDelegate源代码.谢谢阅读!

#import "AppDelegate.h"@implementation AppDelegate- (voID)applicationDIDFinishLaunching:(NSNotification *)aNotification {    IOBluetoothServicebrowserController *browser = [IOBluetoothServicebrowserController servicebrowserController:0];    [browser runModal];    //IOBluetoothSDPServiceRecord    IOBluetoothSDPServiceRecord *result = [[browser getResults] objectAtIndex:0];    [self describe:result];    if ([[result.device.name substringToIndex:8] isEqualToString:@"PolaroID"]) {        printer = result.device;        serviceRecord = result;        [self testPrint];    }    else {        NSLog(@"%@ is not a valID device",result.device.name);    }}- (voID) testPrint {     currentfilePath = @"/Users/oyvind/Desktop/_DSC8797.jpg";    [self sendfile:currentfilePath];}- (voID) sendfile:(Nsstring *)filePath {    IOBluetoothOBEXSession *obexSession = [[IOBluetoothOBEXSession alloc] initWithSDPServiceRecord:serviceRecord];    if( obexSession != nil )    {        NSLog(@"OBEX Session Established");        OBEXfileTransferServices *fst = [OBEXfileTransferServices withOBEXSession:obexSession];        OBEXDelegate *obxd = [[OBEXDelegate alloc] init];        [obxd setfile:filePath];        [fst setDelegate:obxd];        OBEXError cnctResult = [fst connectToObjectPushService];        if( cnctResult != kIOReturnSuccess ) {            NSLog(@"Error creating connection");            return;        }        else {            NSLog(@"OBEX Session Created. Sending file: %@",filePath);            [fst sendfile:filePath];            [printer openConnection];        }    }    else {        NSLog(@"Error creating OBEX session");        NSLog(@"Error sending file");    }}@end
解决方法 好;这里最终成为功能的核心部分.我制作的应用程序是PolaroID即时打印机的一种打印服务器,它只接受Object Push上的图像.

首先,确保监视文件夹存在.

/*    Looks for a directory named PolaroIDWatchFolder in the user's desktop directory    and creates it if it does not exist. */- (voID) ensureWatchedFolderExists {    NSfileManager *fileManager = [NSfileManager defaultManager];    NSURL *url = [NSURL URLWithString:@"PolaroIDWatchFolder" relativeToURL:[[fileManager URLsForDirectory:NSDesktopDirectory inDomains:NSUserDomainMask] objectAtIndex:0]];    BOol isDir;    if ([fileManager fileExistsAtPath:[url path] isDirectory:&isDir] && isDir) {        [self log:[Nsstring stringWithFormat:@"Watched folder exists at %@",[url absoluteURL]]];        watchFolderPath = url;    }    else {        NSError *theError = nil;        if (![fileManager createDirectoryAtURL:url withIntermediateDirectorIEs:NO attributes:nil error:&theError]) {            [self log:[Nsstring stringWithFormat:@"Watched folder Could not be created at %@",[url absoluteURL]]];        }        else {            watchFolderPath = url;            [self log:[Nsstring stringWithFormat:@"Watched folder created at %@",[url absoluteURL]]];        }    }}

然后扫描可用的打印机:

/*    Loops through all paired Bluetooth devices and retrIEves OBEX Object Push service records    for each device who's name starts with "PolaroID". */- (voID) findPairedDevices {    NSArray *pairedDevices = [IOBluetoothDevice pairedDevices];    devicesTested = [NSMutableArray arrayWithCapacity:0];    for (IOBluetoothDevice *device in pairedDevices)    {        if ([self deviceQualifIEsForAddOrRenew:device.name])        {            BluetoothPushDevice *pushDevice = [[BluetoothPushDevice new] initWithDevice:device];            if (pushDevice != nil)            {                [availableDevices addobject:pushDevice];                [pushDevice testConnection];                            }        }    }}

最后一个函数调用是BluetoothPushDevice的内置方法来测试连接.这是响应的委托处理程序:

- (voID) deviceStatusHandler: (NSNotification *)notification {    BluetoothPushDevice *device = [notification object];    Nsstring *status = [[notification userInfo] objectForKey:@"message"];    if ([devicesTested count] < [availableDevices count] && ![devicesTested containsObject:device.name]) {        [devicesTested addobject:device.name];    }}

在服务器启动时,此方法将响应计时器滴答或手动扫描运行:

- (voID) checkWatchedFolder {    NSError *error = nil;    NSArray *propertIEs = [NSArray arrayWithObjects: NSURLLocalizednameKey,NSURLCreationDateKey,NSURLLocalizedTypeDescriptionKey,nil];    NSArray *files = [[NSfileManager defaultManager]                      contentsOfDirectoryAtURL:watchFolderPath                      includingPropertIEsForKeys:propertIEs                      options:(NSDirectoryEnumerationSkipsHIDdenfiles)                      error:&error];    if (files == nil) {        [self log:@"Error reading watched folder"];        return;    }    if ([files count] > 0) {        int newfileCount = 0;        for (NSURL *url in files) {            if (![filesInTransit containsObject:[url path]]) {                NSLog(@"New file: %@",[url lastPathComponent]);                [self sendfile:[url path]];                newfileCount++;            }        }    }}

找到新文件后,首先需要找到一个不忙于收到打印文件的设备:

/* Loops through all discovered device service records and returns the a new OBEX session for the first it finds that is not connected (meaning it is not currently in use,connections are ad-hoc per print). */- (BluetoothPushDevice*) getIDleDevice {    for (BluetoothPushDevice *device in availableDevices) {        if ([device.status isEqualToString:kBluetoothDeviceStatusReady]) {            return device;        }    }    return nil;}

然后使用此方法发送文件:

- (voID) sendfile:(Nsstring *)filePath {    BluetoothPushDevice *device = [self getIDleDevice];        if( device != nil ) {        NSLog(@"%@ is available",device.name);        if ([device sendfile:filePath]) {            [self log:[Nsstring stringWithFormat:@"Sending file: %@",filePath]];            [filesInTransit addobject:filePath];        }        else {            [self log:[Nsstring stringWithFormat:@"Error sending file: %@",filePath]];        }    }    else {        NSLog(@"No IDle devices");    }}

传输完成后,将调用此委托方法:

/*    Responds to BluetoothPushDevice's TransferComplete notification */- (voID) transferStatusHandler: (NSNotification *) notification {    Nsstring *status = [[notification userInfo] objectForKey:@"message"];    Nsstring *file = ((BluetoothPushDevice*)[notification object]).file;    if ([status isEqualToString:kBluetoothTransferStatusComplete]) {        if ([filesInTransit containsObject:file]) {            NSfileManager *fileManager = [NSfileManager defaultManager];            NSError *error = nil;            [fileManager removeItemAtPath:file error:&error];            if (error != nil) {                [self log:[Nsstring stringWithFormat:@"**ERROR** file %@ Could not be deleted (%@)",file,error.description]];            }            [self log:[Nsstring stringWithFormat:@"file deleted: %@",file]];            [filesInTransit removeObject:file];        }        else {            [self log:[Nsstring stringWithFormat:@"**ERROR** filesInTransit array does not contain file %@",file]];        }    }    [self updateDeviceStatusdisplay];}

我希望这可以帮助别人!

总结

以上是内存溢出为你收集整理的objective-c – Mac到蓝牙设备文件传输,简单的例子?全部内容,希望文章能够帮你解决objective-c – Mac到蓝牙设备文件传输,简单的例子?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/999072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存