你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> [iOS]NSURLConnection的一個小例子

[iOS]NSURLConnection的一個小例子

編輯:IOS開發綜合

直接上代碼了。。。


在iOS7之後可以使用NSURLSession,但是考慮到兼顧iOS6還是使用NSURLConnection。



@interface ViewController() 
@property (nonatomic,strong) NSMutableData *receivedData;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                            timeoutInterval:10.0];

    NSURLConnection *theConncetion=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConncetion) {
        _receivedData = [NSMutableData data];
    }

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_receivedData appendData:data];
    NSLog(@"Downloading...");
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Finished");
}

@end

也可以直接用Block發個異步請求:

    [NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"Finished");
    }];


  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved