Search code examples
iosfileparsingnsdata

Parsing NSData with file content


I am retriving some file from the web containing data in a specific format which I would like to parse. However I know only how to get the file from the web:

dispatch_async(server_queue, ^{
    NSData* data = [NSData dataWithContentsOfURL:
                    kURL];
    [self performSelectorOnMainThread:@selector(parseData:)
                           withObject:data waitUntilDone:YES];
});

In the parse method I would like to tokenize each line of the file but I am not sure how to extract the lines from the NSData object.

-(void)parseData:(NSData *)responseData {
    //tokenize each line of responseData
}

Any suggestion?


Solution

  • NSData is not in a format where you can go through to parse it. Just convert it to a NSString like this:

    -(void)parseData:(NSData *)responseData
    {
        NSString *stringFromData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSArray *eachLineOfString = [stringFromData componentsSeparatedByString:@"\n"];
        for (NSString *line in eachLineOfString) {
            // DO SOMETHING WITH THIS LINE
        }
    }