HTTP 请求GET操作

在Objective-C中执行HTTP请求的选项可能有点吓人。对我来说,一个很好的解决方案是使用NSMutableURLRequest

下面是具体代码:

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:[NSURL URLWithString:url]];

    NSError *error = nil;
    NSHTTPURLResponse *responseCode = nil;

    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

    if([responseCode statusCode] != 200){
        NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
        return nil;
    }

    return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]; 

 

上面的NSURLConnection方法已经被废弃了,如果想要启用新的方式,可以用下面的方式

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)changeTextLabel: (NSString *) tt {
    _textJoke.text = tt;
}
- (IBAction)btnClick:(id)sender {
    NSURL *myUrl = [NSURL URLWithString:@"https://www.baidu.com"];
    NSMutableURLRequest *httpRequest = [[NSMutableURLRequest alloc] init];
    [httpRequest setHTTPMethod:@"GET"];
    [httpRequest setURL:myUrl];
    
    NSURLSessionDataTask *sessTask =  [[NSURLSession sharedSession]  dataTaskWithRequest:httpRequest
                                                                       completionHandler: ^(NSData  *httpRespData,
                                                                                            NSURLResponse *resp,
                                                                                            NSError *error) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)resp;
        if (httpResp.statusCode != 200) {
            NSLog(@"Error get %@, status code: %li", myUrl,
                  httpResp.statusCode);
        }
        NSString *outStr = [[NSString alloc] initWithData:httpRespData encoding:NSUTF8StringEncoding];
        NSString *finalStr =  [NSString stringWithFormat:@"%@ %@",  @"Hello world", outStr];
        [self performSelectorOnMainThread:@selector(changeTextLabel:) withObject:finalStr waitUntilDone:true];
    }];
    [sessTask resume];
    
    NSLog(@"btn clicked");
}


@end

  注意上面的task是异步的,所以我们用了performSelectorOnMainThread方法,执行一个异步调用。

还有一个更好用的异步调用

dispatch_async(dispatch_get_main_queue(), ^{
   // do work here to Usually to update the User Interface
  //在main queue队列,也就是main 线程,更新用户UI
});

具体代码改为

dispatch_async(dispatch_get_main_queue(), ^(void) {
            [self changeTextLabel:finalStr];
        });

两个都可以,但是具体用哪一个,还是可以考虑一下前辈们的说法:

如果您在主线程dispatch _ async 块中启动一个模型对话框窗口,在 OS 10.9中,通过鼠标滚轮滚动将无法工作(假设 b/c 只能在默认运行循环模式下工作)。此外,未捕获的异常将总是终止程序,这在生产代码中是不好的(唯一的出路是在您编写的每个 dispatch _ async block 中嵌套一个 try-catch)。由于这些原因,我们更喜欢 performSelectorOnMainThread。我们创建了一个 dispatch _ async _ main 变体,它在内部调用 performSelectorOnMainThread,因此我们可以继续使用漂亮的块语法。

分类: 默认 标签: 发布于: 2021-12-01 14:07:15, 更新于: 2021-12-01 16:00:26