异步请求

//

//  ViewController.m

//  3、异步请求

//

//  Created by yongma00 on 15/12/10.

//  Copyright © 2015 yongma. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()

- (IBAction)btnPressed:(id)sender;

@property (weak, nonatomic) IBOutlet UILabel *label;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (IBAction)btnPressed:(id)sender {

    //1、生成请求的url

    NSString *str=@"http://192.168.0.100:8080/MJServer/login";

    NSURL *url=[NSURL URLWithString:str];

    NSData *postData=[@"username=123&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

    //2、根据请求生成对应的Request

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:postData];

    //3、连接(异步)

    NSOperationQueue *queue=[[NSOperationQueue alloc]init];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

//        NSLog(@"%@",[NSThread currentThread]);

        //不是主线程,所以需要回到主线程跟新UI

        NSString *text=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

//        [self.label performSelectorOnMainThread:@selector(setText:) withObject:text waitUntilDone:YES];

        

        

//        [[NSOperationQueue mainQueue]addOperationWithBlock:^{

//            self.label.text=text;

//        }];

        

        

        dispatch_async(dispatch_get_main_queue(), ^{

            self.label.text=text;

        });

    }];

}


/*

 回到主线程

 1 [self.label performSelectorOnMainThread:@selector(setText:) withObject:text waitUntilDone:YES];

 2 [[NSOperationQueue mainQueue]addOperationWithBlock:^{

     self.label.text=text;

     }];

 3 dispatch_async(dispatch_get_main_queue(), ^{

     self.label.text=text;

     });

 */


@end


猜你喜欢

转载自blog.csdn.net/u012222212/article/details/50297639