How to separate data received? using asyncsocket

纵饮孤独 提交于 2020-01-24 01:37:06

问题


I am trying to make a app that can connect to a device and ask for a query. To be able to have the a reply, I need to send an NSString command first. I have it in a loop with NSTimer.

I normally have like this in Interface Builder

Read: SIDDA1999AP

then after some time changed to

Read: @REL10345

and so on until the last string send @"H\r\n" then back to the first one.

Part of my code base in Asyncsocket

- (void)viewDidLoad
{
    [super  viewDidLoad];

    // Read Data as loaded
    NSTimer *t;
    t = [NSTimer scheduledTimerWithTimeInterval: 0.5
                                         target: self
                                       selector:@selector(onTick:)
                                       userInfo: nil repeats:YES];

}

-(void)onTick:(NSTimer *)timer {
    sendStr = 
    @"S\r"
    @"@\r\n"
    @"P\r\n"
   @"H\r\n"
    ;

    NSData *sendData = [sendStr dataUsingEncoding:NSUTF8StringEncoding];
    [asyncSocket writeData:sendData withTimeout:-1.0 tag:0];
    [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];


}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{

    DDLogVerbose(@"socket:didReadData:withTag:");
    NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
componentsSeparatedByString:@"L"]objectAtIndex:6];

    [self debugPrint2:[NSString stringWithFormat:@"Read:  \n%@",response]];

    [response release];
    [asyncSocket readDataWithTimeout:-1 tag:0];

}

debugPrint2 where I display my text.

I want to extract string from debugPrint and display it individually. Because its in a loop data would be dynamic. I also need to extract a substring (shorten from SIDDA1999AP to 1999). In other words, remove the prefix and suffix.

My xib would have like

Data1: 1999
Data2: 10345
....

Here's an image of my application in progress:

I hope somebody could help.

来源:https://stackoverflow.com/questions/8243469/how-to-separate-data-received-using-asyncsocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!