程式的實現需要藉助幾個對象: NSURLRequest:建立了一個請求,可以指定緩存策略、超時時間。和NSURLRequest對應的還有一個NSMutableURLRequest,如果請求定義為NSMutableURLRequest則可以指定請求方法(GET或POST)等信息。 NSURLConne ...
程式的實現需要藉助幾個對象:
NSURLRequest:建立了一個請求,可以指定緩存策略、超時時間。和NSURLRequest對應的還有一個NSMutableURLRequest,如果請求定義為NSMutableURLRequest則可以指定請求方法(GET或POST)等信息。
NSURLConnection:用於發送請求,可以指定請求和代理。當前調用NSURLConnection的start方法後開始發送非同步請求。
當然了這種方法比較原始。。。
//
// ViewController.m
// xiazai
//
// Copyright © 2016年 asamu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
{
NSMutableData *_data;//響應數據
UITextField *_textField;
UIButton *_button;
UIProgressView *_progressView;
UILabel *_label;
long long _totalLength;
NSDictionary *_musicDic;
}
@end
@implementation ViewController
#pragma mark -- UI方法
- (void)viewDidLoad {
[super viewDidLoad];
[self analysisJson];
[self layoutUI];
}
#pragma mark -- 私有方法
#pragma mark 解析 JSON
-(void)analysisJson{
NSError *error;
NSString *str = @"http://douban.fm/j/mine/playlist?channel=3";
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *musicDic = [[NSDictionary alloc]init];
//遍歷字典 取出 key - @"song"
for (musicDic in dic[@"song"]) {
_musicDic = musicDic;
}
}
#pragma mark 界面佈局
-(void)layoutUI{
//地址欄
_textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 25)];
//加圓角和邊框
_textField.layer.cornerRadius = 3.0f;
_textField.layer.borderWidth = 0.5f;
_textField.textColor = [UIColor redColor];
/*
解析的 JOSN 中的 歌曲名加上 .mp3 的尾碼
這個名字就是存儲在沙盒中的名字,所以要加 .mp3
由於名稱不一樣,所以不會覆蓋
*/
NSString *musicName = [_musicDic[@"title"] stringByAppendingString:@".mp3"];
_textField.text = musicName;
[_textField sizeToFit];
[self.view addSubview:_textField];
//進度條
_progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 25)];
[self.view addSubview:_progressView];
//狀態顯示
_label = [[UILabel alloc]initWithFrame:CGRectMake(10, 130, 300, 25)];
_label.textColor = [UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
[self.view addSubview:_label];
//下載按鈕
_button = [[UIButton alloc]initWithFrame:CGRectMake(10, 500, 300, 25)];
[_button setTitle:@"下載" forState:UIControlStateNormal];
[_button setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
[_button addTarget:self action:@selector(sendRequest) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
}
#pragma mark -- 更新進度
-(void)updateProgress{
if (_data.length == _totalLength) {
_label.text = @"Finish downloaded";
}else{
_label.text = @"downing...";
[_progressView setProgress:(float)_data.length/_totalLength];
}
}
#pragma mark -- 發送請求
-(void)sendRequest{
NSLog(@"begin");
NSString *urlStr = [NSString stringWithFormat:_musicDic[@"url"],_textField.text];
//解碼
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// 創建 URL 鏈接
NSURL *url = [NSURL URLWithString:urlStr];
//創建請求
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
//創建連接
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//啟動連接
[connection start];
}
#pragma mark -- 連接代理方法
#pragma mark 開始響應
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"receive response");
_data = [[NSMutableData alloc]init];
_progressView.progress = 0;
//通過響應頭中的 Content-Length 取得整個響應的長度
NSHTTPURLResponse *httpRespose = (NSHTTPURLResponse *)response;
NSDictionary *httpResponseHeaderFields = [httpRespose allHeaderFields];
_totalLength = [[httpResponseHeaderFields objectForKey:@"Content-Length"]longLongValue];
}
#pragma mark 接收響應數據,(根據響應內容的大小此方法會被重覆調用)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"Receive data");
//連續接收數據
[_data appendData:data];
//更新進度
[self updateProgress];
}
#pragma mark 接收數據完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"loading finish");
//數據接收完保存文集(註意蘋果官方要求:下載數據只能保存在緩存目錄)
NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
savePath = [savePath stringByAppendingPathComponent:_textField.text];
[_data writeToFile:savePath atomically:YES];
NSLog(@"path:%@",savePath);
}
#pragma mark 請求失敗
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"connection error,error detail is:%@",error.localizedDescription);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
參考 KenshinCui,估計大神的 url 沒用了,所以我換了個音樂的 url,可以用。初學者,若有錯誤,敬請指出,不甚感激。