与服务器交互

准备URL

 NSString *urlStr = self.textField.text;

根据URL来准备一个请求对象

 NSURL *url = [NSURL URLWithString:urlStr];

发送请求

 NSURLRequest *request = [NSURLRequest requestWithURL:url];

同步//主线程会阻塞(在服务器没返回数据之前,界面会卡死不动)

NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    

    if (!receivedData &&error) {

        NSLog(@"%@",error.userInfo);

        return;

    }

    NSLog(@"收到%d个字节的数据",receivedData.length);

使用UIwebview将网络商获取的数据(一个网页)显示出来

[self.webview loadData:receivedData
                  MIMEType:@"text/html"
                 textEncodingName:@"utf-8"
                   baseURL:nil];
View Code

 或

[self.webview loadRequest:request];
View Code

 异步请求

 //发送异步请求无返回值,利用回调的Block 当数据返回时再处理
   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"在线程%@中处理服务器返回的数据",[NSThread currentThread]);
        NSLog(@"接收到的数据%d",data.length);
        
   }];
View Code

 异步请求  用委托来处理数据

<NSURLConnectionDataDelegate>(遵守协议)

  //startImmediately : yes 对象创建的同时发请求,如果是NO 只创建对象,不发送请求
  NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
    [conn start];//默认异步

//服务器收到请求后应答返回时调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
 NSLog(@"服务器开始响应");

}

//服务器接收数据的调用 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSLog(@"接收到服务器端来的数据%d",data.length); NSString *Data =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",Data); }

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

 
原文地址:https://www.cnblogs.com/appshan/p/4566432.html