AFNetworking是一个流行的iOS网络封装库,包括了常用的HTTP协议的使用接口,用起来很方便。被国内外很多大型APP应用。
1.安装
1)
https://github.com/AFNetworking/AFNetworking 下载下来并解压
2)以group方式,AFNetwork下面的文件都加入到工程中
3)在需要引用的地方#import “AFNetworking.h"
2.例子
1)GET一个json数据
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
[manager GET:@"http://XXXXX" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
/*
完整例子:
[manager GET:@"
http://XXX" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
NSDictionary *a=responseObject;
NSLog(@"%@",[a valueForKey:@"version"]);
NSString *remoteVersion=[a valueForKey:@"version"];
NSString *url=[a valueForKey:@"url"];
NSString *target=[a valueForKey:@"target"];
NSString *localVersion=[self getCurrentVersion];
if (remoteVersion!=nil){
if ([remoteVersion compare:localVersion]!=NSOrderedSame){
NSLog(@"Need to download!");
[self downloadFile:url toFile:target];
}
[self writeVersion:remoteVersion];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
*/
2)下载文件
-(void) downloadFile:(NSString *)fileURL toFile:(NSString*)toFile{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:fileURL];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
}