开发者

Make a function to connect in objective c

开发者 https://www.devze.com 2023-01-08 13:45 出处:网络
This is my code: NSError *error; NSURLResponse *response; NSData *dataReply; NSString *stringReply; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: URLGOES

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消