CocoaPods 使用 AFNetworking,SDWebImage

这篇博客详细介绍了如何在Xcode项目中通过CocoaPods来集成AFNetworking和SDWebImage这两个流行框架的步骤。首先,通过终端进入项目目录并创建Podfile,然后搜索并添加所需的框架。接着,使用`pod install --no-repo-update`安装框架,并在Xcode中打开`.xcworkspace`文件进行项目开发。在代码中调用AFNetworking进行网络请求和SDWebImage实现图片加载。最后,别忘了在`info.plist`中配置ATS以解决安全问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 进入终端,cd 切换至项目文件夹下,执行 ls 指令能够看到 .xcodeproj 文件

2. 旧文件就删除旧的 Pods 目录和锁文件

rm -rf Pods Podfile.lock

3. 创建默认的 Podfile 文件

pod init

4. 搜索 AFNetworking,SDWebImage 框架,得到框架详情(或者直接上 github 上找)

pod search AFNetworking
pod search SDWebImage

5. 使用 Xcode 打开 Podfile 文件,添加框架,保存并关闭

# Uncomment the next line to define a global platform for your project
# 最低支持的 iOS 版本
# platform :ios, '9.0'

target '测试Pod' do
  # Comment the next line if you don't want to use dynamic frameworks
  # use_frameworks!
  pod 'AFNetworking'
  pod 'SDWebImage'
  # Pods for 测试Pod
end

6. 安装框架,不更新本地索引,速度快

pod install --no-repo-update

7. 之后升级,添加,删除框架 (供参考)

pod update

8. 第一次使用安装框架(供参考)

pod install

9. 打开项目,点击项目中的带白色图标的 .xcworkspace 文件

10. 调用 AFNetworking,SDWebImage 库(库以下载到项目并且编译通过)

#import "ViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
@interface ViewController ()
@property(nonatomic,weak)UIImageView *imageView;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,20, 300, 200)];
    [self.view addSubview:iv];
    self.imageView = iv;
    NSURL *uil = [NSURL URLWithString:@"https://i0.hdslb.com/bfs/article/ec2f90c04aec710ac655db94fd22c103ef47b7c4.jpg@942w_668h_progressive.webp"];
    [self.imageView sd_setImageWithURL:uil];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置反序列化数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    
    [manager GET:@"http://www.weather.com.cn/data/sk/101010100.html" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
@end

11. 最后 info.plist 文件中,得加上 ATS 设置,否则报错

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanyang Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值