iOS - 网络语线程(OC)

1. 检测网络状态

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    //获得网络检测结果

    BOOL canConnectNetwork = [self isExistenceNetwork];

    NSLog(@"Can connect network? --- %d",canConnectNetwork);

}

 //检测网络状态

-(BOOL)isExistenceNetwork {

    BOOL isExistenceNetwork;

    //测试网络是否可以连接苹果官网.对于使用内购的朋友,可以用来检测是否可以连接苹果官网.

    Reachability *r = [Reachability reachabilityWithHostName:@"http://www.apple.com"];

    

    //对网络的连接状态进行遍历

    switch ([r currentReachabilityStatus]) {

        case NotReachable:

            isExistenceNetwork = FALSE;         //表示网络不可用的状态

            break;

        case ReachableViaWWAN:

            isExistenceNetwork = TRUE;          //表示当前网络通过2G或3G连接

        case ReachableViaWiFi:

            isExistenceNetwork = TRUE;          //表示当前网络通过WiFi连接

        default:

            break;

    }

    return isExistenceNetwork;

}

2. 同步Get方式的网络请求

    //建立一个网址对象,指定请求数据的网址

    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];

    //通过网址,创建网络请求对象,Argument1:请求访问路径 Argument2:缓存协议 Argument3:网络请求超时

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //使用网络连接对象,实现网络通信,网络连接对象创建成功后,就创建一个网络连接对象

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

    //将返回的数据,转成字符串

    NSString *str = [[NSString alloc] initWithData:received encoding:NSUTF8StringEncoding];

    NSLog(@"%@",str);

3. 异步Get方式的网络请求

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    //建立一个网址对象,指定请求数据的网址,本节将调用Facebook的公用应用程序接口,获得某个用户的信息.

    NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/Apple-Inc"];

    //通过网址创建网络请求对象,Argument1:请求访问路径,Arguments:缓存协议 Arguments: 网络请求超时时间.

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //使用网络请求对象实现网络通信,网络请求对象创建成功后,就创建了一个网络连接.

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];  

}

//添加一个代理方法,当接受到网络反馈时,执行这个方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response {

    self.receiveData = [NSMutableData data];

}

//添加一个代理方法,当接受到网络数据时,执行这个方法

-(void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data {

    self.receiveData = data;

}

............

4. 同步Post方式的网络请求

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    //建立一个网址对象,指定请求数据的网址

    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];

    

    //再通过网址创建网络请求对象.Argument1:请求访问路径 Argument2:缓存协议 Argument3:网络请求超时时间

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    

    //设置网络通信方式为post,默认为GET.

    [request setHTTPMethod:@"POST"];

    //设置网络请求的参数

    NSString *str = @"type=focus-c";

    //将请求参数,转换为二进制数据

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    //使用网络连接对象实现网络的通信,网络连接对象创建成功后,就创建了一个连接

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

    //将返回的数据转成字符串

    NSString *str1 = [[NSString alloc] initWithData:received encoding:NSUTF8StringEncoding];

    NSLog(@"%@",str1);

}

5. 异步Get、Post方式的网络请求

6. 下载并保存网络图片

 

7. PerformSelector消息处理方法

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    IOSApp *app = [[IOSApp alloc] init];

    //@selector()可以理解成取类方法的编号,它的行为基本可以等同C语言的中函数指针.它的结果是一个SEL类型.

    SEL method = @selector(printInformation);

    //首先判断对象是否存在,以某个名称命名的方法

    if ([app respondsToSelector:method]) {

        

        [app performSelector:method];

    }

    //然后调用对象的制定方法,这种方法的调用方式,是由运行时系统,负责去找对应的方法,在编译时候不做任何校验.

    SEL method2 = @selector(buyApp:);

    //执行带有参数的方法,传递相关的参数

    if ([app respondsToSelector:method2]) {

        [app performSelector:method2 withObject:(@"Photoshop Interactive Turorials")];

    }

    //在执行某个方法时,可以增加延迟执行的功能

    [app performSelector:method2 withObject:(@"Photoshop Interactive Turorials") afterDelay:2];

}

8. 使用谷歌地图

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    [self openMaps];

}

 

//打开谷歌地图

-(IBAction)openMaps{

    

    //定义个字符串,作为谷歌地图的当前地理位置

    NSString *addressText = @"Beijing";

    

    //请求的网址路径中,如果包含中文的话,会出现请求不成功的情况,这时需要将中文参数转为美国标准信息交换代码.

    addressText = [addressText stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

    

    //定义一个完整的网址路径

    NSString *urlText = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@",addressText];

    NSLog(@"urlText================ %@",urlText);

    //获取应用程序的单例对象,然后调用对象的打开网址方法,打开指定路径的网址.

//    [[UIApplication sharedApplication] openURL:urlText];

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlText]

}

 

9. 发送邮件

10. NSRLoop延迟动作

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    CGRect rect = CGRectMake(100, 100, 100, 30);

    UILabel *label = [[UILabel alloc] initWithFrame:rect];

    [label setText:@"Waitting..."];

    [label setTag:1];

    [self.view addSubview:label];

    //设置延迟1秒钟后,执行设定的方法.

    [self performSelector:@selector(threadEvent) withObject:nil afterDelay:1.0f];

}

 -(void)threadEvent {

    //设置延迟2秒钟后,执行设定的方法.

    [self performSelector:@selector(workInBackground) withObject:nil afterDelay:2.0f];

    _stillLoading = true;

    //是方法一直停留在本行,直到布尔值为假时,才跳转到下面的代码,以此实现线程的阻塞.

    while (_stillLoading) {

        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]         ;

    }

    //延迟2秒钟后,隐藏文字标签

    [[self.view viewWithTag:1] setHidden:YES];

}

-(void)workInBackground {

    //标志线程运行状态

    NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>");

    _stillLoading = false;

}

11. NSThread暂停动作

12. 使用多线程下载网络图片

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    //创建一个包含图片网络路径的字符串.

    NSString *url = @"http://images.apple.com/v/creativity-apps/a/images/icon_mac_garageband_2x.jpg";

    

    //使用分离新线程选择器方法,创建一个线程,用来执行下载图片的方法.

    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];

    

    

    

    

}

-(void)downloadImage:(NSString *)url {

    //初始化加载状态和可变二进制数据对象.

    _isLoaded = NO;

    _bufferData = [NSMutableData data];

    //清除网络返回的缓存

    [[NSURLCache sharedURLCache] removeAllCachedResponses];

    //建立网络请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

    //建立网络请求的连接

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (connection != nil) {

        while (!_isLoaded) {

            //使方法一直停留在本行,直到布尔变量为假时,才跳到下面的代码,以此实现现成的阻塞

            NSLog(@"Downloading........");

            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

        }

    }

    //跟新界面在主线程中,避免异常

    //This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        

        //将请求返回的数据,转换为UIImage对象.

        UIImage *img = [UIImage imageWithData:_bufferData];

        UIImageView *imgview = [[UIImageView alloc] initWithImage:img];

        //设置图像视图的中心点坐标

        [imgview setCenter:CGPointMake(150, 200)];

        [self.view addSubview:imgview];

    }];

    //清除网络请求对象与网络连接对象

    request = nil;

    connection = nil;

}

//添加代理方法,处理网络连接缓存事件,这里选择不缓存

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {

    return nil;

}

//添加一个代理方法,处理网络连接故障事件

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    

    [self performSelectorOnMainThread:@selector(httpConnectEndWitnError) withObject:self waitUntilDone:NO];

    [_bufferData setLength:0];

    

}

 

//添加一个代理方法,处理接受网络数据事件。将返回的数据存入可变二进制数据对象.

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    

    [_bufferData appendData:data];

}

 

//添加一个代理方法,处理网络联结结束事件

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

    

    [self performSelectorOnMainThread:@selector(httpConnectedEnd) withObject:nil waitUntilDone:NO];

    //修改状态为真,退出线程阻塞.

    self.isLoaded = YES;

}

//处理网络结束事件

-(void)httpConnectedEnd {

    

    NSLog(@"httpConnetend");

}

//处理网络故障事件

-(void)httpConnectEndWitnError {

    NSLog(@"httpConnectEndWithError");

}

 

备注:如果你是iOS兴趣者或开发者,有兴趣的话可获得更多参考,以供学习交流。

       内容知识点全面,释意详尽。有自写Code源码(免费+付费)。

学习交流联系方式:

邮箱:1983457078@qq.com

微信号:PureWind_jlk

 

转载于:https://www.cnblogs.com/share-iOS/p/6080721.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值