I’m using NSURLConnection to pull data from a webpage. I’m looking to find a specific line of text to display in a basic app. I’ve converted my NSData to an NSString. The program successfully locates the string I’m looking for:
@"Most recent instantaneous value:
However, I need to actually pull and store the string that follows “instantaneous value: myString “
I’m noob, so I’m stuck. Here’s my code:
- (void)viewWillAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://waterdata.usgs.gov/ga/nwis/uv?cb_72036=on&cb_00062=on&format=gif_default&period=1&site_no=02334400"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
// Connect
label.text = @"Connecting...";
myData = [[NSMutableData alloc] init];
} else {
// Error
}
}
- (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data
{
[myData appendData:data];
}
-(void)connectionDidFinishLoading: (NSURLConnection *)connection {
response = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
label.text = response;
NSString *string1 = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
if ([string1 rangeOfString:@"Most recent instantaneous value: "].location == NSNotFound){
NSLog(@"Not found");
} else
{
NSLog(@"Found");
}
connection = nil;
}
This depends no the format of what follows. You can easily use a regular expression to extract this value if it has a delimiter. For example, let’s say it looks like this:
…Most recent instantaneous value: 74219MoredataBlahBLahBlah
This would be extracted using the regular expression “Most recent instantaneous value: ([0-9]+)”
However, if it is something like this
…Most recent instantaneous value: MyValueMoredataBlahBLahBlah
Then you are pretty much out of luck unless it is the same size each time
If it is like this
……Most recent instantaneous value: MyValue MoredataBlahBLahBlah
Then you can get it like this “…Most recent instantaneous value: ([A-Z,a-z]+ )” (note the space at the end inside the parenthesis).
Could you perhaps tell a bit more about the format of your value?
EDIT:
Since you know the length of your string, just do as shown above and when you get here:
Continue with this:
NSString *cutString = [restOfString substringToIndex:8];