简体   繁体   中英

How to parse a multiline response from ASIHTTPRequest and load data into a UITableView?

I am trying to build a simple chat module in my iOS application. Right now, the application can send messages, which are handled by a PHP file and saved onto a database.

When trying to retrieve messages from the DB to display, the server returns a response of the most 10 recent messages in the following format

msgid|userid|timestamp|message

Note that these values are separated by a | character.

So a sample response from my server would be as follows

12|123|2013-03-02 09:15:16|Hey. How are you?
13|12|2013-03-02 09:17:31|Hey Matt. I'm good!
14|123|2013-03-02 09:18:02|That's great!

I need to load this response into TableViewCells, but I'm not sure how to go about parsing the response and saving the data locally.

I am newbie to iOS dev and I'd appreciate the help.

Thanks!

If there is a newline character after each message maybe you could use the NSString method:

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

So:

NSArray *tableViewCellDataArray = [responseString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

If your response is in the format NSData, you can get an NSString by using:

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

As for storing the data, you can store it in an NSArray property, or if you want persistent storage, investigate Core Data or NSUserDefaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM