Make a function to connect in objective c
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开发者_JAVA百科 would i do this and how would i call it ?
Thanks
Mason
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.
精彩评论