【學習版】AFNetWorking之GET,POST,上傳圖片,下載文件進度監(jiān)測

1.GET

- (void)testgetDemo {

NSString *path = @"http://m.weather.com.cn/data/101010100.html";

//2.下載管理類對象

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//3.默認傳輸?shù)臄?shù)據(jù)類型

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//4.默認傳輸數(shù)據(jù)的樣式

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

//5執(zhí)行下載

/*

第一個參數(shù):請求數(shù)據(jù)的地址

第二個參數(shù):附加信息(可以為空)

第三個參數(shù):執(zhí)行成功后的操作

第四個參數(shù):執(zhí)行失敗后的操作

*/

[manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

?????????? //第一個請求類,默認的參數(shù)

????????? //第二個:請求獲得數(shù)據(jù)

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

NSLog(@"%@",str);

//解析

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

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

}];

}

2.POST

#pragma mark - post請求

- (void)testPost {

NSString *path = @"http://baidu.com";

//下載管理類

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//默認傳輸數(shù)據(jù)的類型

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//傳輸數(shù)據(jù)的樣式

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

//post請求

[manager POST:path parameters:@{@"user":@"fangbingbing",@"password":@"123456"} success:^(AFHTTPRequestOperation *operation, id responseObject) {

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

NSLog(@"%@",str);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

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

}];

}

3.POST上傳圖片到服務(wù)器

#pragma mark - post上傳頭像

- (void)postImageToSever {

//獲取地址

NSString *path = @"http://10.0.178.12/iOS_PHP/upload.php";? ? //下載管理類的對象? ? AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];? ? //默認傳輸?shù)臄?shù)據(jù)類型是二進制

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//第三個參數(shù):進行上傳數(shù)據(jù)的保存操作

[manager POST:path parameters:nil constructingBodyWithBlock:^(idformData) {

//找到要上傳的圖片

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"menu_bg_01-hd.jpg" ofType:nil];

/*

第一個參數(shù):將要上傳的數(shù)據(jù)的原始路徑

第二個參數(shù):要上傳的路徑的key

第三個參數(shù):上傳后文件的別名

第四個參數(shù):原始圖片的格式

*/

[formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"file" fileName:@"2345.png" mimeType:@"image.jpg" error:nil];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {

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

NSLog(@"%@",str);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

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

}];

}

4.下載數(shù)據(jù)進度監(jiān)測

#pragma mark - 下載數(shù)據(jù)

- (void)downLoadData {

_progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];

_progressView.frame = CGRectMake(10, 100, 300, 10);

_progressView.backgroundColor = [UIColor redColor];

[self.view addSubview:_progressView];

//1.獲取地址

NSString *path = @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip";

//2.專門進行下載的管理類

AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];? ? //默認傳輸?shù)臄?shù)據(jù)類型是二進制

sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];

//模式是下載模式

NSProgress *downloadProgress = nil;

/*? ?? 第一個參數(shù):將要下載文件的路徑? ?? 第二個參數(shù):下載進度? ?? 第三個參數(shù):(block):處理下載后文件保存的操作? ?? 第四個參數(shù)(block):下載完成的操作? ?? */

NSURLSessionDownloadTask *task = [sessionManager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]] progress:&downloadProgress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

//沙盒的Documents路徑

NSString *downLoadPath = [NSString stringWithFormat:@"%@/Documents/downLoadData.zip",NSHomeDirectory()];

/**? ? ? ?? 區(qū)分:fileURLWithPath:與urlWithString:? ? ? ?? 前者用于網(wǎng)絡(luò)(AFNetWorking),后者用于(NSURLConnection等系統(tǒng)的數(shù)據(jù)請求類)? ? ? ?? */

//返回下載后保存文件的路徑

return [NSURL fileURLWithPath:downLoadPath];

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {? ? ? ? NSLog(@"filePah:%@",filePath);? ? } ];

//開始下載? ? [task resume];

//利用kvo監(jiān)聽下載進度

//利用kvo? 通過將當前類的對象設(shè)置成觀察者(監(jiān)聽者),讓當前類觀察downloadProgress里面的fractionCompleted屬性的變化

//NSKeyValueObservingOptionNew:標記值的變化,這個是新值? ? //NSKeyValueObservingOptionOld:舊值

[downloadProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

? }

#pragma mark - //kvo觀察者觸發(fā)的方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context {

NSLog(@"keypath:%@,object:%@,change:%@",keyPath,object,change);

//獲取 進度變化

float chanagefl = [[object valueForKeyPath:keyPath] floatValue];

//

_progressView.progress = chanagefl; //開始不能體現(xiàn)變化,是因為下載的過程是異步的,不能實時的獲取值的變化.所以利用多線程的知識解決問題

[[NSOperationQueue mainQueue] addOperationWithBlock:^{

_progressView.progress = chanagefl;

}];

}

作者:流浪在簡書

鏈接:http://www.itdecent.cn/p/320743ac8df0

來源:簡書

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容