user523234
user523234

Reputation: 14834

Initializing NSString 's length limit

In the code below, I am looking for a way to limit the length of connected string. Let's say I only want to retrieve the first 100 characters. But I do not want to do the processing connected after retrieving. Is there a way to initialize NSString with certain length?

NSError* error = nil;
NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.somesite.com"] encoding:NSASCIIStringEncoding error:&error];

Upvotes: 1

Views: 357

Answers (2)

Caleb
Caleb

Reputation: 125007

You're going to have to retrieve the data yourself instead of using NSString's convenience method to do it. If you use, say, NSURLConnection or ASIHTTPRequest you can close the connection when you've received as much data as you want.

Upvotes: 2

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73628

You could use NSString methods to retrieve the first 100 characters but you would have wasted bandwidth anyway to get all the data. So why download all when you want only 100 chars.

So to get only a slice of the data coming off the server, you need count the data stream that the url response gives. For this you could use NSURLConnection -

- (void)viewDidLoad {
    [super viewDidLoad];

    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://someurl.com/data.json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if([responseData length] <= 100)
        [responseData appendData:data];
    else //break connection
        [self connectionDidFinishLoading:connection];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
}

So you need to put your logic in didReceiveData. For here, you want only 100 chars, so break-off the connection after that number is reached.

Upvotes: 2

Related Questions