USB-программирование на iPhone

все, что я хочу сделать, это отправить / получить данные через порт USB. С официальным SDK это невозможно - кроме MFi.

Какие еще способы проводной связи с другими устройствами возможны и вы бы предложили?

Спасибо заранее!

GD


person user741330    schedule 06.05.2011    source источник


Ответы (2)


Членство в MFI не требуется для разработчиков программного обеспечения, оно необходимо только для разработчиков оборудования. И какой USB-порт вы имеете в виду? Вы имеете в виду 32-контактный разъем iPhone? Вы всегда можете отправить данные на аппаратное устройство с помощью Bluetooth.

обновление 1 –

Прежде всего, извините, код может показаться сложным, я вставляю это из моего текущего проекта. Оставьте комментарий, если вы хотите образец проекта.

сначала вам нужно зарегистрироваться для получения уведомлений в виду загрузки-

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];

Затем вы должны найти прилагаемые аксессуары -

     _accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];

Затем убедитесь, что это правильный аксессуар, который вы ищете -

for(EAAccessory *obj in _accessoryList)
    {
        if ([[obj protocolStrings] containsObject:@"com.bluebamboo.p25i"])//if find the accessory(p25) record it
        {
            [accessoryLabel setText:@"P25mi connected"]; // yup this is correct accessory!
            [obj release];
            break;
        }
    }

Затем откройте сеанс -

//if accessory not null
if(accessory)
{
    session = [[EASession alloc] initWithAccessory:accessory forProtocol:@"com.bluebamboo.p25i"];//initial session that pair with protocol string
    [[session outputStream] setDelegate:self];//set delegate class for output stream 
    [[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; //set outputstream loop
    [[session outputStream] open]; //open session
    [[session inputStream] setDelegate:self];
    [[session inputStream] open];
    [[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];


}

Затем будет вызван делегат потока —

//this is a stream listener function that would actived by system while steam has any event
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{   



    switch(streamEvent)
    {
        case NSStreamEventOpenCompleted:
            if(theStream==[session outputStream])//to identify which stream has been opend
            {
                [self addLabel:@"outputNSStream open;"];
            }
            else
            {
                [self addLabel:@"inputNSStream open:"];
            }


            break;
        case NSStreamEventHasBytesAvailable:
            //if system has stream data comes in
            [self addLabel:@"receiving Data;"];

            uint8_t buf2[100];//create a buffer
            unsigned int len = 0;
            //read buffer commands return actuall length of return data
            len = [[session inputStream] read:buf2 maxLength:100];

            if (len>0 )
            {
                if (buf2[4]==0x03&&buf2[5]==0x00)//if two bytes are 0x03 and 0x00, that means print success 
                {
                    //display success message
                    alertMessage = [[UIAlertView alloc] initWithTitle:@"SUCCESS:" message:@"P25i have printed Text successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alertMessage show];
                    [alertMessage release];

                    [self addLabel:@"received success"]; 
                }

            }


            [self enableButton];
            //operation finished then close all streams and session
            [[session outputStream] close];
            [[session outputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [[session outputStream] setDelegate:nil];
            [[session inputStream] close];
            [[session inputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [[session inputStream] setDelegate:nil];
            [session release];
            session = nil;
            //[self connectSession];
            //switcher2=TRUE;

            break;
        case NSStreamEventHasSpaceAvailable:

            [self addLabel:@" NSStreamEventHasSpaceAvailable"];
            if (switcher2)//we send loop mode so application would keep sending data to p25, the switcher2 identify the data has send to P25m
            {


                         //[self addLabel:@"buffer is selected"];
                 int contentLength=[printContent.text length];
                 unsigned char buffer[contentLength+7];
                 buffer[0] = 0X55; 
                         buffer[1]=0x66; 
                         buffer[2]=0x77;  
                         buffer[3]=0x88; 
                         buffer[4]=0x44;//print command
                for (int i=5;i<contentLength+5;i++)//add print content
                {
               buffer[i] =[printContent.text characterAtIndex:i-5];
                  }
               buffer[contentLength+5]=0x0A;
               buffer[contentLength+6]=0x0A;
              [[session outputStream] write:(const uint8_t *)buffer maxLength:contentLength+7];//send print package



                switcher2 =FALSE;
            }



            break;
        case NSStreamEventErrorOccurred:
            alertMessage = [[UIAlertView alloc] initWithTitle:@"ERROR:" message:@"NSSTream Error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertMessage show];
            [alertMessage release];

            [self enableButton];
            [self addLabel:@"NSSTream error"];
            break;
        default:

            break;
    }
}
person Saurabh    schedule 06.05.2011
comment
спасибо за ответ - да, я имею в виду 32-контактный разъем iphone и хочу отправлять и получать данные через это соединение. все беспроводные возможности исключены. - person user741330; 06.05.2011
comment
Мой вопрос заключается в том, как я могу записывать данные и читать входящие потоки данных с 32-контактного разъема iphone. - person user741330; 06.05.2011
comment
Будет ли это работать для любых USB-устройств? Даже если не МФО устройство? - person douglasd3; 20.12.2013
comment
Я попробовал это и получил использование необъявленного идентификатора «EAAccessoryDidConnectNotification», я делаю что-то не так или? - person SomeNorwegianGuy; 18.03.2014
comment
Привет, Саураб. Спасибо за фрагмент кода. Не могли бы вы опубликовать пример проекта, как вы предложили в своем посте? Это было бы очень признательно. - person Alex; 03.04.2014
comment
Вы можете прочитать официальную документацию Apple по EASession и использованию внешнего оборудования на iOS: developer.apple.com/library/ios/documentation/ExternalAccessory/ - person ekscrypto; 11.02.2015

посетите http://redpark.com

они продают USB-кабель и iOS SDK для чтения/записи данных на устройство, подключенное через USB.

я успешно использовал его для подключения iPad к различному оборудованию.

person Jerry Walton    schedule 22.10.2011
comment
Вы когда-нибудь получали одобрение приложения в App Store с включенной функциональностью? - person elsurudo; 21.08.2013
comment
Вы уверены, что redpark.com продает USB-кабели? - person CAMOBAP; 30.08.2014