AFNetworking 是 iOS/macOS 最流行的網絡庫,封裝 NSURLSession 提供鏈式調用、自動序列化、圖片緩存等功能。本文覆蓋 CocoaPods/手動接入、基礎請求、圖片加載、進階配置全流程。
pod 'AFNetworking', '~> 4.0'
AFNetworking/AFNetworking.h、AFNetworking/AFURLSessionManager.h 等核心文件Security.framework、MobileCoreServices.framework、SystemConfiguration.framework#import "AFNetworking.h"
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
// GET 請求示例
NSString *urlStr = @"https://api.example.com/data";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
NSURLSessionDataTask *task = [manager dataTaskWithRequest:request
completionHandler:^(NSURLResponse * _Nonnull response,
id _Nullable responseObject,
NSError * _Nullable error) {
if (error) {
NSLog(@"請求失敗: %@", error);
return;
}
// responseObject 已自動反序列化為 NSDictionary/NSArray
NSDictionary *result = (NSDictionary *)responseObject;
NSLog(@"成功: %@", result);
}];
[task resume];
#import "UIImageView+AFNetworking.h"
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 150, 200, 200)];
NSURL *imageURL = [NSURL URLWithString:@"https://example.com/image.jpg"];
// 佔位圖、漸變動畫、緩存策略一行搞定
[imageView setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:@"placeholder"]
options:SDWebImageRefreshCached
progress:nil
completion:nil];
[self.view addSubview:imageView];
manager.securityPolicy.pinningMode = AFSSLPinningModePublicKey;AFHTTPResponseSerializer 處理非標準格式。AFURLRequestSerialization / AFHTTPResponseSerialization 協議統一添加 Token、日誌、錯誤碼映射。NSAppTransportSecurity 允許 HTTP 或指定域名例外。dispatch_async(dispatch_get_main_queue(), ^{...})。AFURLSessionManager 的 downloadTaskWithRequest / uploadTaskWithRequest 並監聽進度。