views:

30

answers:

1

This is my code:

    NSError *error;
NSURLResponse *response;
NSData *dataReply;
NSString *stringReply;

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: URLGOESHERE]];
[request setHTTPMethod: @"GET"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];

I want to put that in a function soo that i can call it from all my other buttons but i can set the

URLWithString: URLGOESHERE]];

how would i do this and how would i call it ?

Thanks

Mason

+1  A: 

See the explanation below for why this is a bad idea.

- (NSString *)sendRequestWithURLString:(NSString *)urlString {
    NSError *error;
    NSURLResponse *response;
    NSData *dataReply;
    NSString *stringReply;

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlString]];
    [request setHTTPMethod: @"GET"];
    dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
    return [stringReply autorelease];
}

Then

NSString *response = [self sendRequestWithURLString:@"....."];

So, take note, if you call this from a button, it will block the main thread until it finishes, which is bad. You need to look into asynchronous requests, or at the very least use dispatch_async.

jtbandes
asynchronous ? how would i do that ?
NSURLConnection has asynchronous methods.
jtbandes