NSURLRequest 簡單的網絡請求

fb24 9年前發布 | 1K 次閱讀 Objective-C IOS

NSURLRequest 簡單的網絡請求

- (void)viewDidLoad
{
    [super viewDidLoad];

NSURL* url = [NSURL URLWithString:@"http://img21.mtime.cn/mg/2012/03/25/112544.76654880.jpg"];
_imageData = [[NSMutableData alloc] init];

//進度條
_pv = [[UIProgressView alloc] initWithFrame:CGRectMake(50, 50, 220, 20)];
[self.view addSubview:_pv];
[_pv release];


//創建一個請求

//NSURLRequest request = [NSURLRequest requestWithURL:url]; NSURLRequest request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30]; //發送請求 [NSURLConnection connectionWithRequest:request delegate:self]; }

//接收響應頭

  • (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response{ NSLog(@"接收到響應頭"); [_imageData setLength:0]; //拿到響應體長度 NSHTTPURLResponse res = (NSHTTPURLResponse)response; _length = [[res.allHeaderFields objectForKey:@"Content-Length"] floatValue]; NSLog(@"length:%f",_length); //是否 開啟 網絡開關 狀態欄的 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; }

//接收響應體,下載數據 / 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 /

  • (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data{ NSLog(@"接收響應體"); //把每次下載的數據添加到一起 [_imageData appendData:data];

    //刷新進度條 [_pv setProgress:_imageData.length / _length animated:YES]; }

//成功

  • (void)connectionDidFinishLoading:(NSURLConnection )connection{ NSLog(@"成功"); UIImage image = [UIImage imageWithData:_imageData]; self.view.backgroundColor = [UIColor colorWithPatternImage:image];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }

//失敗

  • (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{ NSLog(@"失敗"); [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; }</pre>
 本文由用戶 fb24 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!