Merge remote-tracking branch 'origin/main'

# Conflicts:
#	duix-android/dh_aigc_android/README_en.md
This commit is contained in:
jingtonghuai
2025-07-17 17:13:55 +08:00
39 changed files with 292 additions and 10398 deletions

View File

@@ -26,19 +26,20 @@ Duix-Mobile 支持一键跨平台部署Android/iOS上手门槛低
## 🥳 有什么优势?
- **仿真数字人体验**:自然呈现面部表情、语调和情绪共鸣,打造「像人一样」的 AI 对话。
- **极致响应速度**:对话延迟低于 1.5 秒(持续优化中),带来毫秒级的畅快互动体验
- **支持流式音频**:边合成、边说话,支持中途打断、抢话,让数字人不仅会说话,而且更像「人」
- **极致响应速度**:数字人响应延迟低于 120ms测试设备为骁龙® 8 Gen 2 SoC带来毫秒级流畅互动体验。
- **成本友好,随处部署**:轻量化运行,资源占用极低,轻松适配手机、平板、智能屏等终端。
- **无惧弱网环境**:核心处理本地完成,对网络依赖极低,尤其适合金融、政务、法律等高稳定性场景。
- **全行业适配**:模块化设计,支持快速定制,轻松打造各行业专属数字人解决方案。
## 📑 开发文档
- Android 开发者:[DUIX-Mobile SDK for Android](https://github.com/GuijiAI/duix.ai/blob/main/duix-android/dh_aigc_android/README.md)
- iOS 开发者:[DUIX-Mobile SDK for iOS](https://github.com/GuijiAI/duix.ai/blob/main/duix-ios/GJLocalDigitalDemo/GJLocalDigitalSDK.md)
- Android 开发者:[DUIX-Mobile SDK for Android](./duix-android/dh_aigc_android/README.md)
- iOS 开发者:[DUIX-Mobile SDK for iOS](./duix-ios/GJLocalDigitalDemo/GJLocalDigitalSDK.md)
## 💚 体验 DEMO
## 💚 实际部署案例
- Android[APK 下载](https://github.com/duixcom/Duix.mobile/blob/main/duix-android/test-release.apk)
- 前往哔哩哔哩查看:[《程序员与奶奶的虚拟重逢》](https://www.bilibili.com/video/BV1QSgczPESS)
## ✨ 公用数字人下载
@@ -126,9 +127,7 @@ Duix-Mobile 支持一键跨平台部署Android/iOS上手门槛低
<details>
<summary>是否支持流式音频?</summary>
流式音频目前还处于开发阶段;
如需你当前阶段需要,请联系上方的企业微信。
支持,流式音频已于 2025 年 7 月 17 日版本更新中上线。
</details>
@@ -141,5 +140,5 @@ Duix-Mobile 支持一键跨平台部署Android/iOS上手门槛低
## 💡 版本计划
- [ ] 流式音频能力,预计时间:2025 年 7 月 30 日前
- [x] 流式音频能力2025 年 7 月 16 日上线
- [ ] 算法响应优化预计时间2025 年 8 月 30 日前

View File

@@ -2,9 +2,9 @@
https://github.com/user-attachments/assets/cee993d6-f6ab-40d8-a52b-ae9e8064247b
# ❇️❇️❇️ Duix-Mobile — The Best Real-time Interactive Digital Human Solution for Mobile Devices
# 🚀🚀🚀 Duix-Mobile — The Best Real-time Interactive Digital Human Solution for Mobile Devices
**(Supporting Android/iOS/Pad/Large Screens, etc.)**
**📱 Cross-platform support: iOS / Android / Tablet / Automotive / VR / IoT / Large Screen Interaction, etc.**
## 😎 What is Duix-Mobile?
@@ -16,29 +16,30 @@ Duix-Mobile supports one-click cross-platform deployment (Android/iOS), has a lo
Start building your own interactive digital human now and significantly boost your product performance!
## 🤩 What are the Application Scenarios?
## 🤩 Application Scenarios
- Duix-Mobile supports various practical application scenarios across Android/iOS/Pad/large screen devices;
- Significantly enhance your product performance and boost your revenue levels.
![](./res/example.png)
## 🥳 What are the Advantages?
## 🥳 Advantages
- **Realistic Digital Human Experience**: Natural presentation of facial expressions, tone, and emotional resonance, creating "human-like" AI conversations.
- **Ultimate Response Speed**: Conversation latency under 1.5 seconds (continuously optimizing), delivering millisecond-level smooth interaction experience.
- **Streaming Audio Support**: Synthesize and speak simultaneously, supports interruption and barge-in, making digital humans not only talk but also behave more "human-like".
- **Ultimate Response Speed**: Conversation latency under 120ms (tested on Snapdragon® 8 Gen 2 SoC), delivering millisecond-level smooth interaction experience.
- **Cost-Friendly, Deploy Anywhere**: Lightweight operation, extremely low resource consumption, easily adaptable to phones, tablets, smart screens, and other terminals.
- **Resilient in Weak Network Environments**: Core processing completed locally, minimal network dependency, especially suitable for scenarios requiring high stability like finance, government, and legal sectors.
- **Comprehensive Industry Adaptation**: Modular design, supports rapid customization, easily create industry-specific digital human solutions.
## 📑 Development Documentation
- For Android Developers: [DUIX-Mobile SDK for Android](https://github.com/GuijiAI/duix.ai/blob/main/duix-android/dh_aigc_android/README_en.md)
- For iOS Developers: [DUIX-Mobile SDK for iOS](https://github.com/GuijiAI/duix.ai/blob/main/duix-ios/GJLocalDigitalDemo/GJLocalDigitalSDK_en.md)
- For Android Developers: [DUIX-Mobile SDK for Android](./duix-android/dh_aigc_android/README_en.md)
- For iOS Developers: [DUIX-Mobile SDK for iOS](./duix-ios/GJLocalDigitalDemo/GJLocalDigitalSDK_en.md)
## 💚 Experience DEMO
## 💚 Real Deployment Case
- Android: [APK Download](https://github.com/duixcom/Duix.mobile/blob/main/duix-android/test-release.apk)
- Watch on Bilibili: ["Programmer's Virtual Reunion with Grandma"](https://www.bilibili.com/video/BV1QSgczPESS)
## ✨ Public Digital Human Downloads
@@ -126,9 +127,7 @@ Usually, recording a 15-second to 2-minute video is sufficient to complete the c
<details>
<summary>Is streaming audio supported?</summary>
Streaming audio is currently under development.
If you need this feature at the current stage, please contact the enterprise WeChat above.
Yes, streaming audio was released in the July 17, 2025 update.
</details>
@@ -141,5 +140,5 @@ Yes, we provide documentation for voice start and end callbacks.
## 💡 Version Roadmap
- [ ] Streaming audio capability, expected by: July 30, 2025
- [ ] Algorithm response optimization, expected by: August 30, 2025
- [x] Streaming audio capability, completed by July 16, 2025
- [ ] Algorithm response optimization, expected by August 30, 2025

View File

@@ -1,4 +1,6 @@
# 硅基数字人SDK [[English]] (./README_en.md)
# 硅基数字人SDK
简体中文 | [English](./README_en.md)
## 一、产品介绍

View File

@@ -54,7 +54,7 @@
self.view.backgroundColor=[UIColor whiteColor];
UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 150,self.view.frame.size.width-40,44)];
titleLabel.text=@"Github地址可能下载失败您可以考虑使用代理或者将文件存到自己的存储服务";
titleLabel.text=@"Github地址可能下载失败您可以考虑将文件存到自己的存储服务";
titleLabel.textColor=[UIColor blackColor];
titleLabel.textAlignment=NSTextAlignmentLeft;
titleLabel.numberOfLines=0;

View File

@@ -1,5 +1,7 @@
## 硅基本地版DUIX-PRO SDK使⽤⽂档 (1.2.0)
简体中文 | [English](./GJLocalDigitalSDK_en.md)
### 物料准备
 GJLocalDigitalSDK.framework  (-Embed & Sign)
 
@@ -17,8 +19,7 @@
if(result==1)
{
// NSString *bgpath =[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],@"bg2.jpg"];
// [[GJLDigitalManager manager] toChangeBBGWithPath:bgpath];
[[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg) {
if(isSuccess)
{
@@ -28,12 +29,10 @@
[[GJLDigitalManager manager] toStartRuning];
[weakSelf initASR];
[[GJLASRManager manager] toOpenAsr];
});
//
}
else
@@ -46,13 +45,12 @@
```
## 调用流程
```
1. 启动服务前需要准备好授权的appId,appKey以及同步数字人需要的基础配置和模型文件。
2. 使用授权接口授权
3. 初始化数字人渲染服务。
4. 调用toStart函数开始渲染数字人
5. 调用toSpeakWithPath函数驱动数字人播报。
6. 调用cancelAudioPlay函数可以主动停止播报。
7. 调用toStop结束并释放数字人渲染
1. 启动服务前需要准备好同步数字人需要的基础配置和模型文件。
2. 初始化数字人渲染服务
3. 调用toStart函数开始渲染数字人
4. 调用toWavPcmData函数驱动数字人播报。
5. 调用stopPlaying函数可以主动停止播报。
6. 调用toStop结束并释放数字人渲染
```
### SDK回调
@@ -190,9 +188,7 @@
```
/*
*pcm
*size
* 参考demo里面GJLPCMManager类里toSpeakWithPath 转换成pcm的代码
*audioData播放音频流 参考demo里面GJLPCMManager类里toSpeakWithPath 转换成pcm的代码
*/
-(void)toWavPcmData:(NSData*)audioData;
```
@@ -293,78 +289,7 @@
-(void)toPause;
```
## 语音识别
### 初始化录音和ASR
```
/*
*初始化录音和ASR
*/
-(void)initASR;
```
### 开始识别
```
/*
*开始识别
*/
-(void)toOpenAsr;
```
### 停止识别
```
/*
*停止识别
*/
-(void)toCloseAsr;
```
### 语音识别回调
```
@property (nonatomic, copy) void (^asrBlock)(NSString * asrText,BOOL isFinish);
/*
*data 录音返回 单声道 1 采样率 16000
*/
@property (nonatomic, copy) void (^recordDataBlock)(NSData * data);
/*
*音量回调
*/
@property (nonatomic, copy) void (^rmsBlock)(float rms);
@property (nonatomic, copy) void (^errBlock)(NSError *err);
/*
* 服务端开始推送音频流
*/
@property (nonatomic, copy) void (^startPushBlock)(void);
/*
*data 服务端返回音频流 单声道 1 采样率 16000
*/
@property (nonatomic, copy) void (^pushDataBlock)(NSData * data);
/*
*服务端停止推送音频流
*/
@property (nonatomic, copy) void (^stopPushBlock)(void);
/*
*大模型返回文字
*/
@property (nonatomic, copy) void (^speakTextBlock)(NSString * speakText);
/*
*返回动作标记
*/
@property (nonatomic, copy) void (^motionBlock)(NSString * motionText);
```
## 版本记录

View File

@@ -23,6 +23,7 @@
A0B1C4332B29BECA009E0716 /* GJLGCDTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = A0B1C4312B29BECA009E0716 /* GJLGCDTimer.m */; };
A0B1C4342B29BECA009E0716 /* GJLGCDTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = A0B1C4322B29BECA009E0716 /* GJLGCDTimer.h */; };
A0BA7FA22E26439B00C8EAED /* GJLDecry.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A0BA7FA12E26439B00C8EAED /* GJLDecry.framework */; };
A0BA7FBC2E28B2D900C8EAED /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A0BA7FBB2E28B2D900C8EAED /* AudioToolbox.framework */; };
A0BB09242B3ACCA000BF0CC1 /* GJLGlobalFunc.m in Sources */ = {isa = PBXBuildFile; fileRef = A0BB09222B3ACCA000BF0CC1 /* GJLGlobalFunc.m */; };
A0BB09252B3ACCA000BF0CC1 /* GJLGlobalFunc.h in Headers */ = {isa = PBXBuildFile; fileRef = A0BB09232B3ACCA000BF0CC1 /* GJLGlobalFunc.h */; };
A0C35E712DE6002500FA89D5 /* lightweightsemaphore.h in Headers */ = {isa = PBXBuildFile; fileRef = A0C35E452DE6002500FA89D5 /* lightweightsemaphore.h */; };
@@ -74,39 +75,12 @@
A0C35EA32DE6BA7600FA89D5 /* gjsimp.h in Headers */ = {isa = PBXBuildFile; fileRef = A0C35EA22DE6BA7600FA89D5 /* gjsimp.h */; };
A0D81D742B298FBB002F98C1 /* DIMetalView.mm in Sources */ = {isa = PBXBuildFile; fileRef = A0D81D722B298FBB002F98C1 /* DIMetalView.mm */; };
A0D81D752B298FBB002F98C1 /* DIMetalView.h in Headers */ = {isa = PBXBuildFile; fileRef = A0D81D732B298FBB002F98C1 /* DIMetalView.h */; };
A0E72AAC2DD42D00006F0809 /* SRWebSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AA82DD42D00006F0809 /* SRWebSocket.m */; };
A0E72AAD2DD42D00006F0809 /* WebSocketManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AAA2DD42D00006F0809 /* WebSocketManager.m */; };
A0E72AAE2DD42D00006F0809 /* SRWebSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AA72DD42D00006F0809 /* SRWebSocket.h */; };
A0E72AAF2DD42D00006F0809 /* SocketRocket.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AA62DD42D00006F0809 /* SocketRocket.h */; };
A0E72AB02DD42D00006F0809 /* WebSocketManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AA92DD42D00006F0809 /* WebSocketManager.h */; };
A0E72AB62DD42D42006F0809 /* GJLHttpClient.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AB32DD42D42006F0809 /* GJLHttpClient.h */; };
A0E72AB72DD42D42006F0809 /* GJHttpManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AB12DD42D42006F0809 /* GJHttpManager.h */; };
A0E72AB82DD42D42006F0809 /* GJLHttpClient.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AB42DD42D42006F0809 /* GJLHttpClient.m */; };
A0E72AB92DD42D42006F0809 /* GJHttpManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AB22DD42D42006F0809 /* GJHttpManager.m */; };
A0E72AC92DD42D48006F0809 /* GJLAFCompatibilityMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AC72DD42D48006F0809 /* GJLAFCompatibilityMacros.h */; };
A0E72ACA2DD42D48006F0809 /* GJLAFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72ABC2DD42D48006F0809 /* GJLAFURLSessionManager.h */; };
A0E72ACB2DD42D48006F0809 /* GJLAFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72ABB2DD42D48006F0809 /* GJLAFNetworkReachabilityManager.h */; };
A0E72ACC2DD42D48006F0809 /* GJLAFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72ABF2DD42D48006F0809 /* GJLAFHTTPSessionManager.h */; };
A0E72ACD2DD42D48006F0809 /* GJLAFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72ABA2DD42D48006F0809 /* GJLAFSecurityPolicy.h */; };
A0E72ACE2DD42D48006F0809 /* GJLAFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AC42DD42D48006F0809 /* GJLAFNetworking.h */; };
A0E72ACF2DD42D48006F0809 /* GJLAFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AC22DD42D48006F0809 /* GJLAFURLRequestSerialization.h */; };
A0E72AD02DD42D48006F0809 /* GJLAFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72ABD2DD42D48006F0809 /* GJLAFURLResponseSerialization.h */; };
A0E72AD12DD42D48006F0809 /* GJLAFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AC02DD42D48006F0809 /* GJLAFHTTPSessionManager.m */; };
A0E72AD22DD42D48006F0809 /* GJLAFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AC62DD42D48006F0809 /* GJLAFSecurityPolicy.m */; };
A0E72AD32DD42D48006F0809 /* GJLAFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AC32DD42D48006F0809 /* GJLAFURLRequestSerialization.m */; };
A0E72AD42DD42D48006F0809 /* GJLAFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AC12DD42D48006F0809 /* GJLAFURLSessionManager.m */; };
A0E72AD52DD42D48006F0809 /* GJLAFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AC52DD42D48006F0809 /* GJLAFNetworkReachabilityManager.m */; };
A0E72AD62DD42D48006F0809 /* GJLAFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72ABE2DD42D48006F0809 /* GJLAFURLResponseSerialization.m */; };
A0E72ADA2DD42DF1006F0809 /* GJLASRCofigModel.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AD82DD42DF1006F0809 /* GJLASRCofigModel.m */; };
A0E72ADB2DD42DF1006F0809 /* GJLASRCofigModel.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AD72DD42DF1006F0809 /* GJLASRCofigModel.h */; };
A0E72AE22DD4373A006F0809 /* BZQWebRTC.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AE02DD4373A006F0809 /* BZQWebRTC.h */; };
A0E72AE32DD4373A006F0809 /* BZQWebRTC.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AE12DD4373A006F0809 /* BZQWebRTC.m */; };
A0E72AE62DD4375D006F0809 /* gjl_noise_suppression.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72AE52DD4375D006F0809 /* gjl_noise_suppression.h */; };
A0E72AE72DD4375D006F0809 /* gjl_noise_suppression.c in Sources */ = {isa = PBXBuildFile; fileRef = A0E72AE42DD4375D006F0809 /* gjl_noise_suppression.c */; };
A0E72B4D2DD5E114006F0809 /* GJLDigitalConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72B4B2DD5E114006F0809 /* GJLDigitalConfig.h */; settings = {ATTRIBUTES = (Public, ); }; };
A0E72B4E2DD5E114006F0809 /* GJLDigitalConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72B4C2DD5E114006F0809 /* GJLDigitalConfig.m */; };
A0E72B572DD5EBAC006F0809 /* JWTGenerator.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E72B562DD5EBAC006F0809 /* JWTGenerator.m */; };
A0E72B582DD5EBAC006F0809 /* JWTGenerator.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E72B552DD5EBAC006F0809 /* JWTGenerator.h */; };
A0E8C97E2B29CD5A0089DEE7 /* GJLOpenUDID.m in Sources */ = {isa = PBXBuildFile; fileRef = A0E8C97C2B29CD5A0089DEE7 /* GJLOpenUDID.m */; };
A0E8C97F2B29CD5A0089DEE7 /* GJLOpenUDID.h in Headers */ = {isa = PBXBuildFile; fileRef = A0E8C97D2B29CD5A0089DEE7 /* GJLOpenUDID.h */; };
A0FC3D882B282DC40069EA0E /* GJLocalDigitalSDK.h in Headers */ = {isa = PBXBuildFile; fileRef = A0FC3D852B282DC40069EA0E /* GJLocalDigitalSDK.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -151,6 +125,7 @@
A0B1C4312B29BECA009E0716 /* GJLGCDTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GJLGCDTimer.m; sourceTree = "<group>"; };
A0B1C4322B29BECA009E0716 /* GJLGCDTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GJLGCDTimer.h; sourceTree = "<group>"; };
A0BA7FA12E26439B00C8EAED /* GJLDecry.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = GJLDecry.framework; sourceTree = "<group>"; };
A0BA7FBB2E28B2D900C8EAED /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; };
A0BB09202B3ACBB600BF0CC1 /* GJLocalDigitalSDK.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLocalDigitalSDK.pch; sourceTree = "<group>"; };
A0BB09222B3ACCA000BF0CC1 /* GJLGlobalFunc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GJLGlobalFunc.m; sourceTree = "<group>"; };
A0BB09232B3ACCA000BF0CC1 /* GJLGlobalFunc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GJLGlobalFunc.h; sourceTree = "<group>"; };
@@ -203,39 +178,12 @@
A0C35EA22DE6BA7600FA89D5 /* gjsimp.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = gjsimp.h; sourceTree = "<group>"; };
A0D81D722B298FBB002F98C1 /* DIMetalView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = DIMetalView.mm; sourceTree = "<group>"; };
A0D81D732B298FBB002F98C1 /* DIMetalView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DIMetalView.h; sourceTree = "<group>"; };
A0E72AA62DD42D00006F0809 /* SocketRocket.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SocketRocket.h; sourceTree = "<group>"; };
A0E72AA72DD42D00006F0809 /* SRWebSocket.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SRWebSocket.h; sourceTree = "<group>"; };
A0E72AA82DD42D00006F0809 /* SRWebSocket.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SRWebSocket.m; sourceTree = "<group>"; };
A0E72AA92DD42D00006F0809 /* WebSocketManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WebSocketManager.h; sourceTree = "<group>"; };
A0E72AAA2DD42D00006F0809 /* WebSocketManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = WebSocketManager.m; sourceTree = "<group>"; };
A0E72AB12DD42D42006F0809 /* GJHttpManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJHttpManager.h; sourceTree = "<group>"; };
A0E72AB22DD42D42006F0809 /* GJHttpManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJHttpManager.m; sourceTree = "<group>"; };
A0E72AB32DD42D42006F0809 /* GJLHttpClient.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLHttpClient.h; sourceTree = "<group>"; };
A0E72AB42DD42D42006F0809 /* GJLHttpClient.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLHttpClient.m; sourceTree = "<group>"; };
A0E72ABA2DD42D48006F0809 /* GJLAFSecurityPolicy.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFSecurityPolicy.h; sourceTree = "<group>"; };
A0E72ABB2DD42D48006F0809 /* GJLAFNetworkReachabilityManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFNetworkReachabilityManager.h; sourceTree = "<group>"; };
A0E72ABC2DD42D48006F0809 /* GJLAFURLSessionManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFURLSessionManager.h; sourceTree = "<group>"; };
A0E72ABD2DD42D48006F0809 /* GJLAFURLResponseSerialization.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFURLResponseSerialization.h; sourceTree = "<group>"; };
A0E72ABE2DD42D48006F0809 /* GJLAFURLResponseSerialization.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFURLResponseSerialization.m; sourceTree = "<group>"; };
A0E72ABF2DD42D48006F0809 /* GJLAFHTTPSessionManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFHTTPSessionManager.h; sourceTree = "<group>"; };
A0E72AC02DD42D48006F0809 /* GJLAFHTTPSessionManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFHTTPSessionManager.m; sourceTree = "<group>"; };
A0E72AC12DD42D48006F0809 /* GJLAFURLSessionManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFURLSessionManager.m; sourceTree = "<group>"; };
A0E72AC22DD42D48006F0809 /* GJLAFURLRequestSerialization.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFURLRequestSerialization.h; sourceTree = "<group>"; };
A0E72AC32DD42D48006F0809 /* GJLAFURLRequestSerialization.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFURLRequestSerialization.m; sourceTree = "<group>"; };
A0E72AC42DD42D48006F0809 /* GJLAFNetworking.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFNetworking.h; sourceTree = "<group>"; };
A0E72AC52DD42D48006F0809 /* GJLAFNetworkReachabilityManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFNetworkReachabilityManager.m; sourceTree = "<group>"; };
A0E72AC62DD42D48006F0809 /* GJLAFSecurityPolicy.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLAFSecurityPolicy.m; sourceTree = "<group>"; };
A0E72AC72DD42D48006F0809 /* GJLAFCompatibilityMacros.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLAFCompatibilityMacros.h; sourceTree = "<group>"; };
A0E72AD72DD42DF1006F0809 /* GJLASRCofigModel.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLASRCofigModel.h; sourceTree = "<group>"; };
A0E72AD82DD42DF1006F0809 /* GJLASRCofigModel.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLASRCofigModel.m; sourceTree = "<group>"; };
A0E72AE02DD4373A006F0809 /* BZQWebRTC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BZQWebRTC.h; sourceTree = "<group>"; };
A0E72AE12DD4373A006F0809 /* BZQWebRTC.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BZQWebRTC.m; sourceTree = "<group>"; };
A0E72AE42DD4375D006F0809 /* gjl_noise_suppression.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = gjl_noise_suppression.c; sourceTree = "<group>"; };
A0E72AE52DD4375D006F0809 /* gjl_noise_suppression.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = gjl_noise_suppression.h; sourceTree = "<group>"; };
A0E72B4B2DD5E114006F0809 /* GJLDigitalConfig.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GJLDigitalConfig.h; sourceTree = "<group>"; };
A0E72B4C2DD5E114006F0809 /* GJLDigitalConfig.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GJLDigitalConfig.m; sourceTree = "<group>"; };
A0E72B552DD5EBAC006F0809 /* JWTGenerator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = JWTGenerator.h; sourceTree = "<group>"; };
A0E72B562DD5EBAC006F0809 /* JWTGenerator.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = JWTGenerator.m; sourceTree = "<group>"; };
A0E8C97C2B29CD5A0089DEE7 /* GJLOpenUDID.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GJLOpenUDID.m; sourceTree = "<group>"; };
A0E8C97D2B29CD5A0089DEE7 /* GJLOpenUDID.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GJLOpenUDID.h; sourceTree = "<group>"; };
A0FC3D822B282DC40069EA0E /* GJLocalDigitalSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GJLocalDigitalSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -271,6 +219,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A0BA7FBC2E28B2D900C8EAED /* AudioToolbox.framework in Frameworks */,
A066FDA52B289CBC007A3C68 /* Metal.framework in Frameworks */,
A066FDA42B289C7D007A3C68 /* CoreGraphics.framework in Frameworks */,
A066FD9F2B2897EF007A3C68 /* QuartzCore.framework in Frameworks */,
@@ -438,68 +387,6 @@
path = include;
sourceTree = "<group>";
};
A0E72AAB2DD42D00006F0809 /* SocketRocket */ = {
isa = PBXGroup;
children = (
A0E72AA62DD42D00006F0809 /* SocketRocket.h */,
A0E72AA72DD42D00006F0809 /* SRWebSocket.h */,
A0E72AA82DD42D00006F0809 /* SRWebSocket.m */,
A0E72AA92DD42D00006F0809 /* WebSocketManager.h */,
A0E72AAA2DD42D00006F0809 /* WebSocketManager.m */,
);
path = SocketRocket;
sourceTree = "<group>";
};
A0E72AB52DD42D42006F0809 /* HttpClient */ = {
isa = PBXGroup;
children = (
A0E72AB12DD42D42006F0809 /* GJHttpManager.h */,
A0E72AB22DD42D42006F0809 /* GJHttpManager.m */,
A0E72AB32DD42D42006F0809 /* GJLHttpClient.h */,
A0E72AB42DD42D42006F0809 /* GJLHttpClient.m */,
);
path = HttpClient;
sourceTree = "<group>";
};
A0E72AC82DD42D48006F0809 /* AFNetworking4.0.1 */ = {
isa = PBXGroup;
children = (
A0E72ABA2DD42D48006F0809 /* GJLAFSecurityPolicy.h */,
A0E72ABB2DD42D48006F0809 /* GJLAFNetworkReachabilityManager.h */,
A0E72ABC2DD42D48006F0809 /* GJLAFURLSessionManager.h */,
A0E72ABD2DD42D48006F0809 /* GJLAFURLResponseSerialization.h */,
A0E72ABE2DD42D48006F0809 /* GJLAFURLResponseSerialization.m */,
A0E72ABF2DD42D48006F0809 /* GJLAFHTTPSessionManager.h */,
A0E72AC02DD42D48006F0809 /* GJLAFHTTPSessionManager.m */,
A0E72AC12DD42D48006F0809 /* GJLAFURLSessionManager.m */,
A0E72AC22DD42D48006F0809 /* GJLAFURLRequestSerialization.h */,
A0E72AC32DD42D48006F0809 /* GJLAFURLRequestSerialization.m */,
A0E72AC42DD42D48006F0809 /* GJLAFNetworking.h */,
A0E72AC52DD42D48006F0809 /* GJLAFNetworkReachabilityManager.m */,
A0E72AC62DD42D48006F0809 /* GJLAFSecurityPolicy.m */,
A0E72AC72DD42D48006F0809 /* GJLAFCompatibilityMacros.h */,
);
path = AFNetworking4.0.1;
sourceTree = "<group>";
};
A0E72AD92DD42DF1006F0809 /* GJLASRConfig */ = {
isa = PBXGroup;
children = (
A0E72AD72DD42DF1006F0809 /* GJLASRCofigModel.h */,
A0E72AD82DD42DF1006F0809 /* GJLASRCofigModel.m */,
);
path = GJLASRConfig;
sourceTree = "<group>";
};
A0E72B542DD5EB9B006F0809 /* JWTGenerator */ = {
isa = PBXGroup;
children = (
A0E72B552DD5EBAC006F0809 /* JWTGenerator.h */,
A0E72B562DD5EBAC006F0809 /* JWTGenerator.m */,
);
path = JWTGenerator;
sourceTree = "<group>";
};
A0E8C97B2B29CD5A0089DEE7 /* OpenUDID-master */ = {
isa = PBXGroup;
children = (
@@ -529,11 +416,6 @@
A0FC3D842B282DC40069EA0E /* GJLocalDigitalSDK */ = {
isa = PBXGroup;
children = (
A0E72B542DD5EB9B006F0809 /* JWTGenerator */,
A0E72AD92DD42DF1006F0809 /* GJLASRConfig */,
A0E72AC82DD42D48006F0809 /* AFNetworking4.0.1 */,
A0E72AB52DD42D42006F0809 /* HttpClient */,
A0E72AAB2DD42D00006F0809 /* SocketRocket */,
A05E10052DCC8C170057BEC4 /* AudioCapture */,
A05E0FF92DCC8BD00057BEC4 /* GJLAudioPlayer */,
A0B027122DCB5F9000C4824C /* duixsdka */,
@@ -618,6 +500,7 @@
A0FC3E992B2840BC0069EA0E /* Frameworks */ = {
isa = PBXGroup;
children = (
A0BA7FBB2E28B2D900C8EAED /* AudioToolbox.framework */,
A066FDA62B289E0C007A3C68 /* CoreVideo.framework */,
A066FDA22B289C0D007A3C68 /* Metal.framework */,
A066FDA02B2897F7007A3C68 /* Foundation.framework */,
@@ -686,8 +569,6 @@
A0C35E8E2DE6002500FA89D5 /* dhwenet.h in Headers */,
A0C35E8F2DE6002500FA89D5 /* atomicops.h in Headers */,
A0C35E902DE6002500FA89D5 /* dh_mem.h in Headers */,
A0E72AB62DD42D42006F0809 /* GJLHttpClient.h in Headers */,
A0E72AB72DD42D42006F0809 /* GJHttpManager.h in Headers */,
A0D81D752B298FBB002F98C1 /* DIMetalView.h in Headers */,
A0FC3E502B283DD80069EA0E /* jconfig.h in Headers */,
A0FC3E972B283E7E0069EA0E /* DigitalHumanDriven.h in Headers */,
@@ -696,21 +577,8 @@
A0E8C97F2B29CD5A0089DEE7 /* GJLOpenUDID.h in Headers */,
A0FC3E512B283DD80069EA0E /* jmorecfg.h in Headers */,
A05E0FFA2DCC8BD00057BEC4 /* GJLAudioPlayer.h in Headers */,
A0E72B582DD5EBAC006F0809 /* JWTGenerator.h in Headers */,
A0E72AE62DD4375D006F0809 /* gjl_noise_suppression.h in Headers */,
A0E72AE22DD4373A006F0809 /* BZQWebRTC.h in Headers */,
A0E72AC92DD42D48006F0809 /* GJLAFCompatibilityMacros.h in Headers */,
A0E72ACA2DD42D48006F0809 /* GJLAFURLSessionManager.h in Headers */,
A0E72ACB2DD42D48006F0809 /* GJLAFNetworkReachabilityManager.h in Headers */,
A0E72ACC2DD42D48006F0809 /* GJLAFHTTPSessionManager.h in Headers */,
A0E72ACD2DD42D48006F0809 /* GJLAFSecurityPolicy.h in Headers */,
A0E72ACE2DD42D48006F0809 /* GJLAFNetworking.h in Headers */,
A0E72ACF2DD42D48006F0809 /* GJLAFURLRequestSerialization.h in Headers */,
A0E72ADB2DD42DF1006F0809 /* GJLASRCofigModel.h in Headers */,
A0E72AD02DD42D48006F0809 /* GJLAFURLResponseSerialization.h in Headers */,
A0E72AAE2DD42D00006F0809 /* SRWebSocket.h in Headers */,
A0E72AAF2DD42D00006F0809 /* SocketRocket.h in Headers */,
A0E72AB02DD42D00006F0809 /* WebSocketManager.h in Headers */,
A0A336A22B31499800C07A38 /* DigitalConfigModel.h in Headers */,
A05E10062DCC8C170057BEC4 /* GJLKFAudioCapture.h in Headers */,
A05E10072DCC8C170057BEC4 /* GJLKFAudioConfig.h in Headers */,
@@ -793,13 +661,6 @@
A0B1C4332B29BECA009E0716 /* GJLGCDTimer.m in Sources */,
A05E10082DCC8C170057BEC4 /* GJLKFAudioCapture.mm in Sources */,
A0E72AE32DD4373A006F0809 /* BZQWebRTC.m in Sources */,
A0E72B572DD5EBAC006F0809 /* JWTGenerator.m in Sources */,
A0E72AB82DD42D42006F0809 /* GJLHttpClient.m in Sources */,
A0E72ADA2DD42DF1006F0809 /* GJLASRCofigModel.m in Sources */,
A0E72AB92DD42D42006F0809 /* GJHttpManager.m in Sources */,
A0E72AD12DD42D48006F0809 /* GJLAFHTTPSessionManager.m in Sources */,
A0E72AD22DD42D48006F0809 /* GJLAFSecurityPolicy.m in Sources */,
A0E72AD32DD42D48006F0809 /* GJLAFURLRequestSerialization.m in Sources */,
A0E72AE72DD4375D006F0809 /* gjl_noise_suppression.c in Sources */,
A0C35E912DE6002500FA89D5 /* dhwenet.cpp in Sources */,
A0C35E922DE6002500FA89D5 /* iir_filter.cpp in Sources */,
@@ -817,9 +678,6 @@
A0C35E9F2DE6002500FA89D5 /* dh_data.cpp in Sources */,
A0C35EA02DE6002500FA89D5 /* jmat.cpp in Sources */,
A0C35EA12DE6002500FA89D5 /* malpha.cpp in Sources */,
A0E72AD42DD42D48006F0809 /* GJLAFURLSessionManager.m in Sources */,
A0E72AD52DD42D48006F0809 /* GJLAFNetworkReachabilityManager.m in Sources */,
A0E72AD62DD42D48006F0809 /* GJLAFURLResponseSerialization.m in Sources */,
A0E72B4E2DD5E114006F0809 /* GJLDigitalConfig.m in Sources */,
A05E10092DCC8C170057BEC4 /* GJLKFAudioConfig.m in Sources */,
A05E0FFB2DCC8BD00057BEC4 /* GJLAudioPlayer.mm in Sources */,
@@ -829,8 +687,6 @@
A0E8C97E2B29CD5A0089DEE7 /* GJLOpenUDID.m in Sources */,
A0FC3EA92B2855430069EA0E /* shaders.metal in Sources */,
A0A336A32B31499800C07A38 /* DigitalConfigModel.m in Sources */,
A0E72AAC2DD42D00006F0809 /* SRWebSocket.m in Sources */,
A0E72AAD2DD42D00006F0809 /* WebSocketManager.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};

View File

@@ -1,49 +0,0 @@
// AFCompatibilityMacros.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef AFCompatibilityMacros_h
#define AFCompatibilityMacros_h
#ifdef API_AVAILABLE
#define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__)
#else
#define AF_API_AVAILABLE(...)
#endif // API_AVAILABLE
#ifdef API_UNAVAILABLE
#define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__)
#else
#define AF_API_UNAVAILABLE(...)
#endif // API_UNAVAILABLE
#if __has_warning("-Wunguarded-availability-new")
#define AF_CAN_USE_AT_AVAILABLE 1
#else
#define AF_CAN_USE_AT_AVAILABLE 0
#endif
#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000))
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0
#else
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1
#endif
#endif /* AFCompatibilityMacros_h */

View File

@@ -1,285 +0,0 @@
// AFHTTPSessionManager.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import <TargetConditionals.h>
#import "GJLAFURLSessionManager.h"
/**
`AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
## Subclassing Notes
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
## Methods to Override
To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`.
## Serialization
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
## URL Construction Using Relative Paths
For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
*/
NS_ASSUME_NONNULL_BEGIN
@interface GJLAFHTTPSessionManager : GJLAFURLSessionManager <NSSecureCoding, NSCopying>
/**
The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
*/
@property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
/**
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
@warning `requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) GJLAFHTTPRequestSerializer <GJLAFURLRequestSerialization> * requestSerializer;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) GJLAFHTTPResponseSerializer <GJLAFURLResponseSerialization> * responseSerializer;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception.
*/
@property (nonatomic, strong) GJLAFSecurityPolicy *securityPolicy;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns an `AFHTTPSessionManager` object.
*/
+ (instancetype)manager;
/**
Initializes an `AFHTTPSessionManager` object with the specified base URL.
@param url The base URL for the HTTP client.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(nullable NSURL *)url;
/**
Initializes an `AFHTTPSessionManager` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client.
@param configuration The configuration used to create the managed session.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(nullable NSURL *)url
sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates and runs an `NSURLSessionDataTask` with a `GET` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
/**
Creates an `NSURLSessionDataTask` with a custom `HTTPMethod` request.
@param method The HTTPMethod string used to create the request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param headers The headers appended to the default headers for this request.
@param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:
*/
- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,357 +0,0 @@
// AFHTTPSessionManager.m
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "GJLAFHTTPSessionManager.h"
#import "GJLAFURLRequestSerialization.h"
#import "GJLAFURLResponseSerialization.h"
#import <Availability.h>
#import <TargetConditionals.h>
#import <Security/Security.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#endif
@interface GJLAFHTTPSessionManager ()
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end
@implementation GJLAFHTTPSessionManager
@dynamic responseSerializer;
+ (instancetype)manager {
return [[[self class] alloc] initWithBaseURL:nil];
}
- (instancetype)init {
return [self initWithBaseURL:nil];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
return [self initWithBaseURL:url sessionConfiguration:nil];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
return [self initWithBaseURL:nil sessionConfiguration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
self = [super initWithSessionConfiguration:configuration];
if (!self) {
return nil;
}
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
url = [url URLByAppendingPathComponent:@""];
}
self.baseURL = url;
self.requestSerializer = [GJLAFHTTPRequestSerializer serializer];
self.responseSerializer = [GJLAFJSONResponseSerializer serializer];
return self;
}
#pragma mark -
- (void)setRequestSerializer:(GJLAFHTTPRequestSerializer <GJLAFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(GJLAFHTTPResponseSerializer <GJLAFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[super setResponseSerializer:responseSerializer];
}
@dynamic securityPolicy;
- (void)setSecurityPolicy:(GJLAFSecurityPolicy *)securityPolicy {
if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
NSString *pinningMode = @"Unknown Pinning Mode";
switch (securityPolicy.SSLPinningMode) {
case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
}
NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
@throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
}
[super setSecurityPolicy:securityPolicy];
}
#pragma mark -
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
headers:headers
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
if (success) {
success(task);
}
} failure:failure];
[dataTask resume];
return dataTask;
}
- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
for (NSString *headerField in headers.keyEnumerator) {
[request setValue:headers[headerField] forHTTPHeaderField:headerField];
}
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(task, error);
}
} else {
if (success) {
success(task, responseObject);
}
}
}];
[task resume];
return task;
}
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary<NSString *,NSString *> *)headers
success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(nullable id)parameters
headers:(nullable NSDictionary <NSString *, NSString *> *)headers
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
for (NSString *headerField in headers.keyEnumerator) {
[request setValue:headers[headerField] forHTTPHeaderField:headerField];
}
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request
uploadProgress:uploadProgress
downloadProgress:downloadProgress
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
if (!configuration) {
NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
if (configurationIdentifier) {
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
}
}
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[GJLAFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[GJLAFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
GJLAFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[GJLAFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
if (decodedPolicy) {
self.securityPolicy = decodedPolicy;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
} else {
[coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
}
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
[coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
return HTTPClient;
}
@end

View File

@@ -1,216 +0,0 @@
// AFNetworkReachabilityManager.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
};
NS_ASSUME_NONNULL_BEGIN
/**
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
*/
@interface GJLAFNetworkReachabilityManager : NSObject
/**
The current network reachability status.
*/
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
/**
Whether or not the network is currently reachable.
*/
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
/**
Whether or not the network is currently reachable via WWAN.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
/**
Whether or not the network is currently reachable via WiFi.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
///---------------------
/// @name Initialization
///---------------------
/**
Returns the shared network reachability manager.
*/
+ (instancetype)sharedManager;
/**
Creates and returns a network reachability manager with the default socket address.
@return An initialized network reachability manager, actively monitoring the default socket address.
*/
+ (instancetype)manager;
/**
Creates and returns a network reachability manager for the specified domain.
@param domain The domain used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified domain.
*/
+ (instancetype)managerForDomain:(NSString *)domain;
/**
Creates and returns a network reachability manager for the socket address.
@param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified socket address.
*/
+ (instancetype)managerForAddress:(const void *)address;
/**
Initializes an instance of a network reachability manager from the specified reachability object.
@param reachability The reachability object to monitor.
@return An initialized network reachability manager, actively monitoring the specified reachability.
*/
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
/**
* Unavailable initializer
*/
+ (instancetype)new NS_UNAVAILABLE;
/**
* Unavailable initializer
*/
- (instancetype)init NS_UNAVAILABLE;
///--------------------------------------------------
/// @name Starting & Stopping Reachability Monitoring
///--------------------------------------------------
/**
Starts monitoring for changes in network reachability status.
*/
- (void)startMonitoring;
/**
Stops monitoring for changes in network reachability status.
*/
- (void)stopMonitoring;
///-------------------------------------------------
/// @name Getting Localized Reachability Description
///-------------------------------------------------
/**
Returns a localized string representation of the current network reachability status.
*/
- (NSString *)localizedNetworkReachabilityStatusString;
///---------------------------------------------------
/// @name Setting Network Reachability Change Callback
///---------------------------------------------------
/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
*/
- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
@end
///----------------
/// @name Constants
///----------------
/**
## Network Reachability
The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
enum {
AFNetworkReachabilityStatusUnknown,
AFNetworkReachabilityStatusNotReachable,
AFNetworkReachabilityStatusReachableViaWWAN,
AFNetworkReachabilityStatusReachableViaWiFi,
}
`AFNetworkReachabilityStatusUnknown`
The `baseURL` host reachability is not known.
`AFNetworkReachabilityStatusNotReachable`
The `baseURL` host cannot be reached.
`AFNetworkReachabilityStatusReachableViaWWAN`
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
`AFNetworkReachabilityStatusReachableViaWiFi`
The `baseURL` host can be reached via a Wi-Fi connection.
### Keys for Notification UserInfo Dictionary
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
`AFNetworkingReachabilityNotificationStatusItem`
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
*/
///--------------------
/// @name Notifications
///--------------------
/**
Posted when network reachability changes.
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
///--------------------
/// @name Functions
///--------------------
/**
Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
*/
FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
NS_ASSUME_NONNULL_END
#endif

View File

@@ -1,269 +0,0 @@
// AFNetworkReachabilityManager.m
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "GJLAFNetworkReachabilityManager.h"
#if !TARGET_OS_WATCH
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
typedef GJLAFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status);
NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
case AFNetworkReachabilityStatusReachableViaWWAN:
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
case AFNetworkReachabilityStatusReachableViaWiFi:
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
case AFNetworkReachabilityStatusUnknown:
default:
return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
}
}
static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
if (isNetworkReachable == NO) {
status = AFNetworkReachabilityStatusNotReachable;
}
#if TARGET_OS_IPHONE
else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
status = AFNetworkReachabilityStatusReachableViaWWAN;
}
#endif
else {
status = AFNetworkReachabilityStatusReachableViaWiFi;
}
return status;
}
/**
* Queue a status change notification for the main thread.
*
* This is done to ensure that the notifications are received in the same order
* as they are sent. If notifications are sent directly, it is possible that
* a queued notification (for an earlier status condition) is processed after
* the later update, resulting in the listener being left in the wrong state.
*/
static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) {
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
dispatch_async(dispatch_get_main_queue(), ^{
GJLAFNetworkReachabilityManager *manager = nil;
if (block) {
manager = block(status);
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
[notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo];
});
}
static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info);
}
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
return Block_copy(info);
}
static void AFNetworkReachabilityReleaseCallback(const void *info) {
if (info) {
Block_release(info);
}
}
@interface GJLAFNetworkReachabilityManager ()
@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
@end
@implementation GJLAFNetworkReachabilityManager
+ (instancetype)sharedManager {
static GJLAFNetworkReachabilityManager *_sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedManager = [self manager];
});
return _sharedManager;
}
+ (instancetype)managerForDomain:(NSString *)domain {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
GJLAFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
CFRelease(reachability);
return manager;
}
+ (instancetype)managerForAddress:(const void *)address {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
GJLAFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
CFRelease(reachability);
return manager;
}
+ (instancetype)manager
{
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
struct sockaddr_in6 address;
bzero(&address, sizeof(address));
address.sin6_len = sizeof(address);
address.sin6_family = AF_INET6;
#else
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_len = sizeof(address);
address.sin_family = AF_INET;
#endif
return [self managerForAddress:&address];
}
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
self = [super init];
if (!self) {
return nil;
}
_networkReachability = CFRetain(reachability);
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
return self;
}
- (instancetype)init
{
@throw [NSException exceptionWithName:NSGenericException
reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
userInfo:nil];
return nil;
}
- (void)dealloc {
[self stopMonitoring];
if (_networkReachability != NULL) {
CFRelease(_networkReachability);
}
}
#pragma mark -
- (BOOL)isReachable {
return [self isReachableViaWWAN] || [self isReachableViaWiFi];
}
- (BOOL)isReachableViaWWAN {
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
}
- (BOOL)isReachableViaWiFi {
return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
}
#pragma mark -
- (void)startMonitoring {
[self stopMonitoring];
if (!self.networkReachability) {
return;
}
__weak __typeof(self)weakSelf = self;
AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.networkReachabilityStatus = status;
if (strongSelf.networkReachabilityStatusBlock) {
strongSelf.networkReachabilityStatusBlock(status);
}
return strongSelf;
};
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
AFPostReachabilityStatusChange(flags, callback);
}
});
}
- (void)stopMonitoring {
if (!self.networkReachability) {
return;
}
SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
}
#pragma mark -
- (NSString *)localizedNetworkReachabilityStatusString {
return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
}
#pragma mark -
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
self.networkReachabilityStatusBlock = block;
}
#pragma mark - NSKeyValueObserving
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
return [NSSet setWithObject:@"networkReachabilityStatus"];
}
return [super keyPathsForValuesAffectingValueForKey:key];
}
@end
#endif

View File

@@ -1,41 +0,0 @@
// AFNetworking.h
//
// Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#import <TargetConditionals.h>
#ifndef _AFNETWORKING_
#define _AFNETWORKING_
#import "GJLAFURLRequestSerialization.h"
#import "GJLAFURLResponseSerialization.h"
#import "GJLAFSecurityPolicy.h"
#if !TARGET_OS_WATCH
#import "GJLAFNetworkReachabilityManager.h"
#endif
#import "GJLAFURLSessionManager.h"
#import "GJLAFHTTPSessionManager.h"
#endif /* _AFNETWORKING_ */

View File

@@ -1,161 +0,0 @@
// AFSecurityPolicy.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Security/Security.h>
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
};
/**
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
*/
NS_ASSUME_NONNULL_BEGIN
@interface GJLAFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
/**
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
*/
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/**
The certificates used to evaluate server trust according to the SSL pinning mode.
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
@see policyWithPinningMode:withPinnedCertificates:
*/
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
/**
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowInvalidCertificates;
/**
Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
*/
@property (nonatomic, assign) BOOL validatesDomainName;
///-----------------------------------------
/// @name Getting Certificates from the Bundle
///-----------------------------------------
/**
Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
@return The certificates included in the given bundle.
*/
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
///-----------------------------------------
/// @name Getting Specific Security Policies
///-----------------------------------------
/**
Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
@return The default security policy.
*/
+ (instancetype)defaultPolicy;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a security policy with the specified pinning mode.
Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead.
@param pinningMode The SSL pinning mode.
@return A new security policy.
@see -policyWithPinningMode:withPinnedCertificates:
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
/**
Creates and returns a security policy with the specified pinning mode.
@param pinningMode The SSL pinning mode.
@param pinnedCertificates The certificates to pin against.
@return A new security policy.
@see +certificatesInBundle:
@see -pinnedCertificates
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
///------------------------------
/// @name Evaluating Server Trust
///------------------------------
/**
Whether or not the specified server trust should be accepted, based on the security policy.
This method should be used when responding to an authentication challenge from a server.
@param serverTrust The X.509 certificate trust of the server.
@param domain The domain of serverTrust. If `nil`, the domain will not be validated.
@return Whether or not to trust the server.
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(nullable NSString *)domain;
@end
NS_ASSUME_NONNULL_END
///----------------
/// @name Constants
///----------------
/**
## SSL Pinning Modes
The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
}
`AFSSLPinningModeNone`
Do not used pinned certificates to validate servers.
`AFSSLPinningModePublicKey`
Validate host certificates against public keys of pinned certificates.
`AFSSLPinningModeCertificate`
Validate host certificates against pinned certificates.
*/

View File

@@ -1,341 +0,0 @@
// AFSecurityPolicy.m
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "GJLAFSecurityPolicy.h"
#import <AssertMacros.h>
#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
static NSData * AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
__Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
return (__bridge_transfer NSData *)data;
_out:
if (data) {
CFRelease(data);
}
return nil;
}
#endif
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
#endif
}
static id AFPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil;
SecCertificateRef allowedCertificate;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out);
policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
#pragma clang diagnostic pop
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
if (allowedTrust) {
CFRelease(allowedTrust);
}
if (policy) {
CFRelease(policy);
}
if (allowedCertificate) {
CFRelease(allowedCertificate);
}
return allowedPublicKey;
}
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
BOOL isValid = NO;
SecTrustResultType result;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
#pragma clang diagnostic pop
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
_out:
return isValid;
}
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return [NSArray arrayWithArray:trustChain];
}
static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust;
__Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
SecTrustResultType result;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
#pragma clang diagnostic pop
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
_out:
if (trust) {
CFRelease(trust);
}
if (certificates) {
CFRelease(certificates);
}
continue;
}
CFRelease(policy);
return [NSArray arrayWithArray:trustChain];
}
#pragma mark -
@interface GJLAFSecurityPolicy()
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
@end
@implementation GJLAFSecurityPolicy
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
return [NSSet setWithSet:certificates];
}
+ (instancetype)defaultPolicy {
GJLAFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
return securityPolicy;
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
NSSet <NSData *> *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]];
return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates];
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
GJLAFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = pinningMode;
[securityPolicy setPinnedCertificates:pinnedCertificates];
return securityPolicy;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.validatesDomainName = YES;
return self;
}
- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates;
if (self.pinnedCertificates) {
NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
for (NSData *certificate in self.pinnedCertificates) {
id publicKey = AFPublicKeyForCertificate(certificate);
if (!publicKey) {
continue;
}
[mutablePinnedPublicKeys addObject:publicKey];
}
self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
} else {
self.pinnedPublicKeys = nil;
}
}
#pragma mark -
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
// According to the docs, you should only trust your provided certs for evaluation.
// Pinned certificates are added to the trust. Without pinned certificates,
// there is nothing to evaluate against.
//
// From Apple Docs:
// "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
// Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
return NO;
}
NSMutableArray *policies = [NSMutableArray array];
if (self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
} else {
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
if (self.SSLPinningMode == AFSSLPinningModeNone) {
return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
} else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) {
return NO;
}
switch (self.SSLPinningMode) {
case AFSSLPinningModeCertificate: {
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for (NSData *certificateData in self.pinnedCertificates) {
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
if (!AFServerTrustIsValid(serverTrust)) {
return NO;
}
// obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
return YES;
}
}
return NO;
}
case AFSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0;
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
for (id trustChainPublicKey in publicKeys) {
for (id pinnedPublicKey in self.pinnedPublicKeys) {
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
trustedPublicKeyCount += 1;
}
}
}
return trustedPublicKeyCount > 0;
}
default:
return NO;
}
return NO;
}
#pragma mark - NSKeyValueObserving
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
return [NSSet setWithObject:@"pinnedCertificates"];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
[coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
[coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
[coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
securityPolicy.SSLPinningMode = self.SSLPinningMode;
securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
securityPolicy.validatesDomainName = self.validatesDomainName;
securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
return securityPolicy;
}
@end

View File

@@ -1,479 +0,0 @@
// AFURLRequestSerialization.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#endif
NS_ASSUME_NONNULL_BEGIN
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
@param string The string to be percent-escaped.
@return The percent-escaped string.
*/
FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string);
/**
A helper method to generate encoded url query parameters for appending to the end of a URL.
@param parameters A dictionary of key/values to be encoded.
@return A url encoded query string
*/
FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters);
/**
The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
*/
@protocol GJLAFURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
/**
Returns a request with the specified parameters encoded into a copy of the original request.
@param request The original request.
@param parameters The parameters to be encoded.
@param error The error that occurred while attempting to encode the request parameters.
@return A serialized request.
*/
- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(nullable id)parameters
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
@end
#pragma mark -
/**
*/
typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) {
AFHTTPRequestQueryStringDefaultStyle = 0,
};
@protocol AFMultipartFormData;
/**
`AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior.
*/
@interface GJLAFHTTPRequestSerializer : NSObject <GJLAFURLRequestSerialization>
/**
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
Whether created requests can use the devices cellular radio (if present). `YES` by default.
@see NSMutableURLRequest -setAllowsCellularAccess:
*/
@property (nonatomic, assign) BOOL allowsCellularAccess;
/**
The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
@see NSMutableURLRequest -setCachePolicy:
*/
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
/**
Whether created requests should use the default cookie handling. `YES` by default.
@see NSMutableURLRequest -setHTTPShouldHandleCookies:
*/
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
/**
Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
@see NSMutableURLRequest -setHTTPShouldUsePipelining:
*/
@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
/**
The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
@see NSMutableURLRequest -setNetworkServiceType:
*/
@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
/**
The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
@see NSMutableURLRequest -setTimeoutInterval:
*/
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
///---------------------------------------
/// @name Configuring HTTP Request Headers
///---------------------------------------
/**
Default HTTP header field values to be applied to serialized requests. By default, these include the following:
- `Accept-Language` with the contents of `NSLocale +preferredLanguages`
- `User-Agent` with the contents of various bundle identifiers and OS designations
@discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
*/
@property (readonly, nonatomic, strong) NSDictionary <NSString *, NSString *> *HTTPRequestHeaders;
/**
Creates and returns a serializer with default configuration.
*/
+ (instancetype)serializer;
/**
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
@param field The HTTP header to set a default value for
@param value The value set as default for the specified header, or `nil`
*/
- (void)setValue:(nullable NSString *)value
forHTTPHeaderField:(NSString *)field;
/**
Returns the value for the HTTP headers set in the request serializer.
@param field The HTTP header to retrieve the default value for
@return The value set as default for the specified header, or `nil`
*/
- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
@param username The HTTP basic auth username
@param password The HTTP basic auth password
*/
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
password:(NSString *)password;
/**
Clears any existing value for the "Authorization" HTTP header.
*/
- (void)clearAuthorizationHeader;
///-------------------------------------------------------
/// @name Configuring Query String Parameter Serialization
///-------------------------------------------------------
/**
HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
*/
@property (nonatomic, strong) NSSet <NSString *> *HTTPMethodsEncodingParametersInURI;
/**
Set the method of query string serialization according to one of the pre-defined styles.
@param style The serialization style.
@see AFHTTPRequestQueryStringSerializationStyle
*/
- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style;
/**
Set the a custom method of query string serialization according to the specified block.
@param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
*/
- (void)setQueryStringSerializationWithBlock:(nullable NSString * _Nullable (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
///-------------------------------
/// @name Creating Request Objects
///-------------------------------
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
@param error The error that occurred while constructing the request.
@return An `NSMutableURLRequest` object.
*/
- (nullable NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(nullable id)parameters
error:(NSError * _Nullable __autoreleasing *)error;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
@param error The error that occurred while constructing the request.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(nullable NSDictionary <NSString *, id> *)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
error:(NSError * _Nullable __autoreleasing *)error;
/**
Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
@param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
@param fileURL The file URL to write multipart form contents to.
@param handler A handler block to execute.
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
@see https://github.com/AFNetworking/AFNetworking/issues/1398
*/
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
writingStreamContentsToFile:(NSURL *)fileURL
completionHandler:(nullable void (^)(NSError * _Nullable error))handler;
@end
#pragma mark -
/**
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
*/
@protocol AFMultipartFormData
/**
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended, otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
error:(NSError * _Nullable __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
error:(NSError * _Nullable __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
@param inputStream The input stream to be appended to the form data
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
@param length The length of the specified input stream in bytes.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream
name:(NSString *)name
fileName:(NSString *)fileName
length:(int64_t)length
mimeType:(NSString *)mimeType;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithFileData:(NSData *)data
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType;
/**
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
*/
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name;
/**
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
@param headers The HTTP headers to be appended to the form data.
@param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
*/
- (void)appendPartWithHeaders:(nullable NSDictionary <NSString *, NSString *> *)headers
body:(NSData *)body;
/**
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
@param delay Duration of delay each time a packet is read. By default, no delay is set.
*/
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
delay:(NSTimeInterval)delay;
@end
#pragma mark -
/**
`AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
*/
@interface GJLAFJSONRequestSerializer : GJLAFHTTPRequestSerializer
/**
Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
*/
@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
/**
Creates and returns a JSON serializer with specified reading and writing options.
@param writingOptions The specified JSON writing options.
*/
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
@end
#pragma mark -
/**
`AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
*/
@interface GJLAFPropertyListRequestSerializer : GJLAFHTTPRequestSerializer
/**
The property list format. Possible values are described in "NSPropertyListFormat".
*/
@property (nonatomic, assign) NSPropertyListFormat format;
/**
@warning The `writeOptions` property is currently unused.
*/
@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
/**
Creates and returns a property list serializer with a specified format, read options, and write options.
@param format The property list format.
@param writeOptions The property list write options.
@warning The `writeOptions` property is currently unused.
*/
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
writeOptions:(NSPropertyListWriteOptions)writeOptions;
@end
#pragma mark -
///----------------
/// @name Constants
///----------------
/**
## Error Domains
The following error domain is predefined.
- `NSString * const AFURLRequestSerializationErrorDomain`
### Constants
`AFURLRequestSerializationErrorDomain`
AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
### Constants
`AFNetworkingOperationFailingURLRequestErrorKey`
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
/**
## Throttling Bandwidth for HTTP Request Input Streams
@see -throttleBandwidthWithPacketSize:delay:
### Constants
`kAFUploadStream3GSuggestedPacketSize`
Maximum packet size, in number of bytes. Equal to 16kb.
`kAFUploadStream3GSuggestedDelay`
Duration of delay each time a packet is read. Equal to 0.2 seconds.
*/
FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize;
FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay;
NS_ASSUME_NONNULL_END

View File

@@ -1,313 +0,0 @@
// AFURLResponseSerialization.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
NS_ASSUME_NONNULL_BEGIN
/**
Recursively removes `NSNull` values from a JSON object.
*/
FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions);
/**
The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
*/
@protocol GJLAFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
/**
The response object decoded from the data associated with a specified response.
@param response The response to be processed.
@param data The response data to be decoded.
@param error The error that occurred while attempting to decode the response data.
@return The object decoded from the specified response data.
*/
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
@end
#pragma mark -
/**
`AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
*/
@interface GJLAFHTTPResponseSerializer : NSObject <GJLAFURLResponseSerialization>
- (instancetype)init;
/**
Creates and returns a serializer with default configuration.
*/
+ (instancetype)serializer;
///-----------------------------------------
/// @name Configuring Response Serialization
///-----------------------------------------
/**
The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
/**
The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
*/
@property (nonatomic, copy, nullable) NSSet <NSString *> *acceptableContentTypes;
/**
Validates the specified response and data.
In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
@param response The response to be validated.
@param data The data associated with the response.
@param error The error that occurred while attempting to validate the response.
@return `YES` if the response is valid, otherwise `NO`.
*/
- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error;
@end
#pragma mark -
/**
`AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- `application/json`
- `text/json`
- `text/javascript`
In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details.
*/
@interface GJLAFJSONResponseSerializer : GJLAFHTTPResponseSerializer
- (instancetype)init;
/**
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
*/
@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
/**
Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
*/
@property (nonatomic, assign) BOOL removesKeysWithNullValues;
/**
Creates and returns a JSON serializer with specified reading and writing options.
@param readingOptions The specified JSON reading options.
*/
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
@end
#pragma mark -
/**
`AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
*/
@interface GJLAFXMLParserResponseSerializer : GJLAFHTTPResponseSerializer
@end
#pragma mark -
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
`AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
*/
@interface GJLAFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
- (instancetype)init;
/**
Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default.
*/
@property (nonatomic, assign) NSUInteger options;
/**
Creates and returns an XML document serializer with the specified options.
@param mask The XML document options.
*/
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
@end
#endif
#pragma mark -
/**
`AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
- `application/x-plist`
*/
@interface GJLAFPropertyListResponseSerializer : GJLAFHTTPResponseSerializer
- (instancetype)init;
/**
The property list format. Possible values are described in "NSPropertyListFormat".
*/
@property (nonatomic, assign) NSPropertyListFormat format;
/**
The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
*/
@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
/**
Creates and returns a property list serializer with a specified format, read options, and write options.
@param format The property list format.
@param readOptions The property list reading options.
*/
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
readOptions:(NSPropertyListReadOptions)readOptions;
@end
#pragma mark -
/**
`AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
- `image/tiff`
- `image/jpeg`
- `image/gif`
- `image/png`
- `image/ico`
- `image/x-icon`
- `image/bmp`
- `image/x-bmp`
- `image/x-xbitmap`
- `image/x-win-bitmap`
*/
@interface GJLAFImageResponseSerializer : GJLAFHTTPResponseSerializer
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
/**
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
*/
@property (nonatomic, assign) CGFloat imageScale;
/**
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
*/
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
#endif
@end
#pragma mark -
/**
`AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
*/
@interface GJLAFCompoundResponseSerializer : GJLAFHTTPResponseSerializer
/**
The component response serializers.
*/
@property (readonly, nonatomic, copy) NSArray <id<GJLAFURLResponseSerialization>> *responseSerializers;
/**
Creates and returns a compound serializer comprised of the specified response serializers.
@warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
*/
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray <id<GJLAFURLResponseSerialization>> *)responseSerializers;
@end
///----------------
/// @name Constants
///----------------
/**
## Error Domains
The following error domain is predefined.
- `NSString * const AFURLResponseSerializationErrorDomain`
### Constants
`AFURLResponseSerializationErrorDomain`
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
### Constants
`AFNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
`AFNetworkingOperationFailingURLResponseDataErrorKey`
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
NS_ASSUME_NONNULL_END

View File

@@ -1,836 +0,0 @@
// AFURLResponseSerialization.m
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "GJLAFURLResponseSerialization.h"
#import <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#import <Cocoa/Cocoa.h>
#endif
NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
if (!error) {
return underlyingError;
}
if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
return error;
}
NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
}
static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
if ([error.domain isEqualToString:domain] && error.code == code) {
return YES;
} else if (error.userInfo[NSUnderlyingErrorKey]) {
return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
}
return NO;
}
id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
if (![value isEqual:[NSNull null]]) {
[mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
id value = (NSDictionary *)JSONObject[key];
if (!value || [value isEqual:[NSNull null]]) {
[mutableDictionary removeObjectForKey:key];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
return JSONObject;
}
@implementation GJLAFHTTPResponseSerializer
+ (instancetype)serializer {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
self.acceptableContentTypes = nil;
return self;
}
#pragma mark -
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError * __autoreleasing *)error
{
BOOL responseIsValid = YES;
NSError *validationError = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
!([response MIMEType] == nil && [data length] == 0)) {
if ([data length] > 0 && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
}
responseIsValid = NO;
}
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
responseIsValid = NO;
}
}
if (error && !responseIsValid) {
*error = validationError;
}
return responseIsValid;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
[self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
return data;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
[coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
return serializer;
}
@end
#pragma mark -
@implementation GJLAFJSONResponseSerializer
+ (instancetype)serializer {
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
}
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
GJLAFJSONResponseSerializer *serializer = [[self alloc] init];
serializer.readingOptions = readingOptions;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
return self;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
return nil;
}
}
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
// See https://github.com/rails/rails/issues/1742
BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]];
if (data.length == 0 || isSpace) {
return nil;
}
NSError *serializationError = nil;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
if (!responseObject)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
if (self.removesKeysWithNullValues) {
return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
}
return responseObject;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
[coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFJSONResponseSerializer *serializer = [super copyWithZone:zone];
serializer.readingOptions = self.readingOptions;
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
return serializer;
}
@end
#pragma mark -
@implementation GJLAFXMLParserResponseSerializer
+ (instancetype)serializer {
GJLAFXMLParserResponseSerializer *serializer = [[self alloc] init];
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
return self;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
return nil;
}
}
return [[NSXMLParser alloc] initWithData:data];
}
@end
#pragma mark -
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@implementation GJLAFXMLDocumentResponseSerializer
+ (instancetype)serializer {
return [self serializerWithXMLDocumentOptions:0];
}
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
GJLAFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
serializer.options = mask;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
return self;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
return nil;
}
}
NSError *serializationError = nil;
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
if (!document)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
return document;
}
#pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone];
serializer.options = self.options;
return serializer;
}
@end
#endif
#pragma mark -
@implementation GJLAFPropertyListResponseSerializer
+ (instancetype)serializer {
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
}
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
readOptions:(NSPropertyListReadOptions)readOptions
{
GJLAFPropertyListResponseSerializer *serializer = [[self alloc] init];
serializer.format = format;
serializer.readOptions = readOptions;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
return self;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
return nil;
}
}
if (!data) {
return nil;
}
NSError *serializationError = nil;
id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
if (!responseObject)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
return responseObject;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
[coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFPropertyListResponseSerializer *serializer = [super copyWithZone:zone];
serializer.format = self.format;
serializer.readOptions = self.readOptions;
return serializer;
}
@end
#pragma mark -
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
@interface UIImage (AFNetworkingSafeImageLoading)
+ (UIImage *)af_safeImageWithData:(NSData *)data;
@end
static NSLock* imageLock = nil;
@implementation UIImage (AFNetworkingSafeImageLoading)
+ (UIImage *)af_safeImageWithData:(NSData *)data {
UIImage* image = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageLock = [[NSLock alloc] init];
});
[imageLock lock];
image = [UIImage imageWithData:data];
[imageLock unlock];
return image;
}
@end
static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
UIImage *image = [UIImage af_safeImageWithData:data];
if (image.images) {
return image;
}
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
}
static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
if (!data || [data length] == 0) {
return nil;
}
CGImageRef imageRef = NULL;
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if ([response.MIMEType isEqualToString:@"image/png"]) {
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
if (imageRef) {
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
// CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
CGImageRelease(imageRef);
imageRef = NULL;
}
}
}
CGDataProviderRelease(dataProvider);
UIImage *image = AFImageWithDataAtScale(data, scale);
if (!imageRef) {
if (image.images || !image) {
return image;
}
imageRef = CGImageCreateCopy([image CGImage]);
if (!imageRef) {
return nil;
}
}
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
CGImageRelease(imageRef);
return image;
}
// CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
size_t bytesPerRow = 0;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (colorSpaceModel == kCGColorSpaceModelRGB) {
uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wassign-enum"
if (alpha == kCGImageAlphaNone) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
}
#pragma clang diagnostic pop
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (!context) {
CGImageRelease(imageRef);
return image;
}
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
CGImageRelease(inflatedImageRef);
CGImageRelease(imageRef);
return inflatedImage;
}
#endif
@implementation GJLAFImageResponseSerializer
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
#if TARGET_OS_IOS || TARGET_OS_TV
self.imageScale = [[UIScreen mainScreen] scale];
self.automaticallyInflatesResponseImage = YES;
#elif TARGET_OS_WATCH
self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
self.automaticallyInflatesResponseImage = YES;
#endif
return self;
}
#pragma mark - AFURLResponseSerializer
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
return nil;
}
}
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
if (self.automaticallyInflatesResponseImage) {
return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
} else {
return AFImageWithDataAtScale(data, self.imageScale);
}
#else
// Ensure that the image is set to it's correct pixel width and height
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
[image addRepresentation:bitimage];
return image;
#endif
return nil;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
#if CGFLOAT_IS_DOUBLE
self.imageScale = [imageScale doubleValue];
#else
self.imageScale = [imageScale floatValue];
#endif
self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
#endif
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
[coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
[coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
#endif
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFImageResponseSerializer *serializer = [super copyWithZone:zone];
#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
serializer.imageScale = self.imageScale;
serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
#endif
return serializer;
}
@end
#pragma mark -
@interface GJLAFCompoundResponseSerializer ()
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
@end
@implementation GJLAFCompoundResponseSerializer
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
GJLAFCompoundResponseSerializer *serializer = [[self alloc] init];
serializer.responseSerializers = responseSerializers;
return serializer;
}
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
for (id <GJLAFURLResponseSerialization> serializer in self.responseSerializers) {
if (![serializer isKindOfClass:[GJLAFHTTPResponseSerializer class]]) {
continue;
}
NSError *serializerError = nil;
id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
if (responseObject) {
if (error) {
*error = AFErrorWithUnderlyingError(serializerError, *error);
}
return responseObject;
}
}
return [super responseObjectForResponse:response data:data error:error];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
NSSet *classes = [NSSet setWithArray:@[[NSArray class], [GJLAFHTTPResponseSerializer <GJLAFURLResponseSerialization> class]]];
self.responseSerializers = [decoder decodeObjectOfClasses:classes forKey:NSStringFromSelector(@selector(responseSerializers))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
GJLAFCompoundResponseSerializer *serializer = [super copyWithZone:zone];
serializer.responseSerializers = self.responseSerializers;
return serializer;
}
@end

View File

@@ -1,516 +0,0 @@
// AFURLSessionManager.h
// Copyright (c) 20112016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "GJLAFURLResponseSerialization.h"
#import "GJLAFURLRequestSerialization.h"
#import "GJLAFSecurityPolicy.h"
#import "GJLAFCompatibilityMacros.h"
#if !TARGET_OS_WATCH
#import "GJLAFNetworkReachabilityManager.h"
#endif
/**
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
## Subclassing Notes
This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
## NSURLSession & NSURLSessionTask Delegate Methods
`AFURLSessionManager` implements the following delegate methods:
### `NSURLSessionDelegate`
- `URLSession:didBecomeInvalidWithError:`
- `URLSession:didReceiveChallenge:completionHandler:`
- `URLSessionDidFinishEventsForBackgroundURLSession:`
### `NSURLSessionTaskDelegate`
- `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
- `URLSession:task:didReceiveChallenge:completionHandler:`
- `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
- `URLSession:task:needNewBodyStream:`
- `URLSession:task:didCompleteWithError:`
### `NSURLSessionDataDelegate`
- `URLSession:dataTask:didReceiveResponse:completionHandler:`
- `URLSession:dataTask:didBecomeDownloadTask:`
- `URLSession:dataTask:didReceiveData:`
- `URLSession:dataTask:willCacheResponse:completionHandler:`
### `NSURLSessionDownloadDelegate`
- `URLSession:downloadTask:didFinishDownloadingToURL:`
- `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`
- `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Network Reachability Monitoring
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
## NSCoding Caveats
- Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
## NSCopying Caveats
- `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
- Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
*/
NS_ASSUME_NONNULL_BEGIN
@interface GJLAFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
/**
The managed session.
*/
@property (readonly, nonatomic, strong) NSURLSession *session;
/**
The operation queue on which delegate callbacks are run.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) id <GJLAFURLResponseSerialization> responseSerializer;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
*/
@property (nonatomic, strong) GJLAFSecurityPolicy *securityPolicy;
#if !TARGET_OS_WATCH
///--------------------------------------
/// @name Monitoring Network Reachability
///--------------------------------------
/**
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) GJLAFNetworkReachabilityManager *reachabilityManager;
#endif
///----------------------------
/// @name Getting Session Tasks
///----------------------------
/**
The data, upload, and download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
/**
The data tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
/**
The upload tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
/**
The download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
@param configuration The configuration used to create the managed session.
@return A manager for a newly-created session.
*/
- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
/**
Invalidates the managed session, optionally canceling pending tasks and optionally resets given session.
@param cancelPendingTasks Whether or not to cancel pending tasks.
@param resetSession Whether or not to reset the session of the manager.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession;
///-------------------------
/// @name Running Data Tasks
///-------------------------
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
///---------------------------
/// @name Running Upload Tasks
///---------------------------
/**
Creates an `NSURLSessionUploadTask` with the specified request for a local file.
@param request The HTTP request for the request.
@param fileURL A URL to the local file to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
@see `attemptsToRecreateUploadTasksForBackgroundSessions`
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
@param request The HTTP request for the request.
@param bodyData A data object containing the HTTP body to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(nullable NSData *)bodyData
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified streaming request.
@param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
///-----------------------------
/// @name Running Download Tasks
///-----------------------------
/**
Creates an `NSURLSessionDownloadTask` with the specified request.
@param request The HTTP request for the request.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
@warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionDownloadTask` with the specified resume data.
@param resumeData The data used to resume downloading.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
///---------------------------------
/// @name Getting Progress for Tasks
///---------------------------------
/**
Returns the upload progress of the specified task.
@param task The session task. Must not be `nil`.
@return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
*/
- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
/**
Returns the download progress of the specified task.
@param task The session task. Must not be `nil`.
@return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
*/
- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
///-----------------------------------------
/// @name Setting Session Delegate Callbacks
///-----------------------------------------
/**
Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
@param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
*/
- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
/**
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
@warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `setTaskDidReceiveAuthenticationChallengeBlock:` instead.
@see -securityPolicy
@see -setTaskDidReceiveAuthenticationChallengeBlock:
*/
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
///--------------------------------------
/// @name Setting Task Delegate Callbacks
///--------------------------------------
/**
Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
@param block A block object to be executed when a task requires a new request body stream.
*/
- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
/**
Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
@param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
*/
- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
/**
Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
@param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge.
When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options:
1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials.
2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error.
3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface.
4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`.
If you return anything else from the authentication challenge handler, an exception will be thrown.
For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html).
@see -securityPolicy
*/
- (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler;
/**
Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
/**
Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
*/
- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
/**
Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`.
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task.
*/
#if AF_CAN_INCLUDE_SESSION_TASK_METRICS
- (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
#endif
///-------------------------------------------
/// @name Setting Data Task Delegate Callbacks
///-------------------------------------------
/**
Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
@param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
*/
- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
/**
Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
@param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
*/
- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
/**
Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
*/
- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
/**
Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
@param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
*/
- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
/**
Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
@param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
*/
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos);
///-----------------------------------------------
/// @name Setting Download Task Delegate Callbacks
///-----------------------------------------------
/**
Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
*/
- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
/**
Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
*/
- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
/**
Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
@param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
*/
- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
@end
///--------------------
/// @name Notifications
///--------------------
/**
Posted when a task resumes.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
/**
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
/**
Posted when a task suspends its execution.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
/**
Posted when a session is invalidated.
*/
FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
/**
Posted when a session download task finished moving the temporary download file to a specified destination successfully.
*/
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification;
/**
Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
*/
FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
/**
The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
/**
The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
/**
The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
/**
The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
/**
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
/**
The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics`
*/
FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics;
NS_ASSUME_NONNULL_END

View File

@@ -4,6 +4,9 @@
#import "GJLKFAudioCapture.h"
#import <AVFoundation/AVFoundation.h>
#import <mach/mach_time.h>
#import <zlib.h>
#import <AudioToolbox/AudioToolbox.h>
//#import "BZQWebRTC.h"
#import "GJLGCDTimer.h"
#import "DigitalHumanDriven.h"

View File

@@ -1,26 +0,0 @@
//
// GJLASRCofigModel.h
// GJLocalDigitalSDK
//
// Created by guiji on 2025/2/7.
//
#import <Foundation/Foundation.h>
@interface GJLASRCofigModel : NSObject
/*
*endPoint 默认中文=300 目前只支持中文
*设置语言放在【[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg)]之前生效
*/
@property (nonatomic, assign)NSInteger end_point;
@property (nonatomic, strong)NSString * lan;
@property (nonatomic, strong)NSString * type;
+ (GJLASRCofigModel*)manager;
@end

View File

@@ -1,34 +0,0 @@
//
// GJLASRCofigModel.m
// GJLocalDigitalSDK
//
// Created by guiji on 2025/2/7.
//
#import "GJLASRCofigModel.h"
static GJLASRCofigModel * manager = nil;
@implementation GJLASRCofigModel
+ (GJLASRCofigModel *)manager
{
static dispatch_once_t once;
dispatch_once(&once, ^{
manager = [[GJLASRCofigModel alloc] init];
});
return manager;
}
-(id)init
{
self=[super init];
if(self)
{
// self.sampleRate=16000;
self.end_point=300;
self.lan=@"zh";
self.type=@"ali";
// self.playImageQueue= dispatch_queue_create("com.duixsdk.playImageQueue", DISPATCH_QUEUE_CONCURRENT);
// self.mat_type=0;
}
return self;
}
@end

View File

@@ -10,10 +10,7 @@
#import <AVFoundation/AVFoundation.h>
@interface GJLDigitalManager : NSObject
/*
modeType 0 默认生产 1测试 2开发
*/
@property (nonatomic, assign) NSInteger modeType;
/*
backType 0 背景透明 1 使用背景渲染

View File

@@ -10,10 +10,10 @@
#import "DIMetalView.h"
#import "GJLGCDTimer.h"
#import "GJLAudioPlayer.h"
#import "GJHttpManager.h"
#import <GJLDecry/GJLDecry.h>
#import "JWTGenerator.h"
#define DEBASEPATH @"DecryBasePath"
#define DEDIGITALPATH @"DecryDigitalPath"
@@ -144,39 +144,7 @@ static GJLDigitalManager * manager = nil;
-(NSString*)getLocalSignWithAppId:(NSString *)appId appKey:(NSString *)appKey
{
NSDate *now = [NSDate date];
NSTimeInterval sevenDaysInSeconds = 7 * 24 * 60 * 60;
NSDate *expiresDate = [now dateByAddingTimeInterval:sevenDaysInSeconds];
// 打印appId和appSecret
NSLog(@"appId: %@ appSecret: %@", appId, appKey);
// 创建JWT
// 构建payload
NSDictionary *payload = @{@"appId": appId,
@"iat": @([[NSDate date] timeIntervalSince1970]), // issued at
@"exp": @([expiresDate timeIntervalSince1970]) // expires at
};
// 使用JWT库创建token
NSError *error;
NSString *jwt_str = [JWTGenerator generateJWTWithPayload:payload secretKey:appKey];
//[JWT encodePayload:payload withSecret:appKey algorithm:[[JWTAlgorithmHS256 alloc] init]];
// 编码
// NSMutableCharacterSet *charset = [NSCharacterSet URLQueryAllowedCharacterSet].mutableCopy;
// [charset removeCharactersInString:@"+"]; // 强制编码加号
NSString *appsign =jwt_str;// [jwt_str stringByAddingPercentEncodingWithAllowedCharacters:charset];
if (error) {
NSLog(@"Error encoding JWT: %@", error);
} else {
// 打印token
NSLog(@"appsign: %@", appsign);
}
return appsign;
}
-(NSInteger)initBaseModel:(NSString*)basePath digitalModel:(NSString*)digitalPath showView:(UIView*)showView
{
@@ -1468,11 +1436,7 @@ static GJLDigitalManager * manager = nil;
success(isSuccess);
}];
}
-(void)setModeType:(NSInteger)modeType
{
_modeType=modeType;
[GJHttpManager manager].modeType=modeType;
}
-(void)toWavPcmData:(NSData*)audioData
{

View File

@@ -1,40 +0,0 @@
//
// GJHttpManager.h
// GJLocalDigitalSDK
//
// Created by guiji on 2023/12/14.
//
#import <Foundation/Foundation.h>
@interface GJHttpManager : NSObject
+ (GJHttpManager *)manager;
/*
modeType 0 默认生产 1测试 2开发
*/
@property (nonatomic, assign) NSInteger modeType;
-(NSString*)getBaseUrl;
-(NSString*)getWsUrl;
//授权
+ (void)getApplicationSigWithAppId:(NSString *)appId appKey:(NSString *)appKey block:(void (^) (BOOL isSuccess, NSString *msg, NSString *appsign))block;
//获取数字人资源下载地址
+ (void)getdDigitalUrlWithConversationId:(NSString *)conversationId block:(void (^) (BOOL isSuccess, NSString *msg, NSString *digitalUrl))block;
//检查是否存在可用时长
+ (void)checkDurationWithAppId:(NSString *)appId block:(void (^) (BOOL isSuccess, NSString *msg))block;
//创建会话 chatSessionId app会话id
+ (void)toCreateSession:(NSString *)sig chatSessionId:(NSString*)chatSessionId conversationId:(NSString*)conversationId block:(void (^) (BOOL isSuccess, NSString *msg,NSString *sessionId,id responseObject))block;
//结束会话
+ (void)toEndSession:(NSString *)sig sessionId:(NSString*)sessionId chatSessionId:(NSString*)chatSessionId block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block;
//心跳
+ (void)toHeartBeat:(NSString *)sig sessionId:(NSString*)sessionId chatSessionId:(NSString*)chatSessionId block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block;
//创建tts链接
+ (void)toCreateTTS:(NSString *)content conversationId:(NSString*)conversationId isWav:(BOOL)isWav block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block;
+(void)toReport:(NSMutableArray*)data_arr block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block;
@end

View File

@@ -1,264 +0,0 @@
//
// GJHttpManager.m
// GJLocalDigitalSDK
//
// Created by guiji on 2023/12/14.
//
#import "GJHttpManager.h"
#import "GJLDigitalManager.h"
#import "GJLHttpClient.h"
//#import "SaveAudioModel.h"
#import "GJLASRCofigModel.h"
#define GJNetworkErrorMsg @"网络异常,请稍后尝试"
@implementation GJHttpManager
+ (GJHttpManager *)manager
{
static GJHttpManager * manager = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
manager = [[GJHttpManager alloc] init];
});
return manager;
}
-(NSString*)getBaseUrl
{
NSString *sdkurl = GJSDKBaseUrl;
if (self.modeType == 2) {
sdkurl = GJSDKBaseDevUrl;
} else if (self.modeType == 1) {
sdkurl = GJSDKBaseTestUrl;
}
return sdkurl;
}
-(NSString*)getWsUrl
{
NSString *sdkurl = GJSDKWebSocketUrl;
if (self.modeType == 2) {
sdkurl = GJSDKWebSocketDevUrl;
} else if (self.modeType == 1) {
sdkurl = GJSDKWebSocketTestUrl;
}
return sdkurl;
}
//
+ (void)getApplicationSigWithAppId:(NSString *)appId appKey:(NSString *)appKey block:(void (^) (BOOL isSuccess, NSString *msg, NSString *appsign))block {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:appId forKey:@"appId"];
[dict setValue:appKey forKey:@"appKey"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,GJLGETAPPSIG];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodPost success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
// NSDictionary *data_dic=dic[@"data"];
if (success == 1) {
NSString *data = dic[@"data"]?:@"";
block(YES,message,data);
} else {
block(NO,message,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil);
}];
}
+ (void)getdDigitalUrlWithConversationId:(NSString *)conversationId block:(void (^) (BOOL isSuccess, NSString *msg, NSString *digitalUrl))block {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
[dict setValue:conversationId forKey:@"conversationId"];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,GJGETCONVERSATIONBYID];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodGet success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
NSDictionary *data = dic[@"data"];
NSDictionary *detailDto = data[@"detailDto"];
NSDictionary *localModelInfo = detailDto[@"localModelInfo"];
if ([localModelInfo isKindOfClass:[NSDictionary class]]) {
NSString *modelResourcePath = [GJLGlobalFunc changeType:localModelInfo[@"modelResourcePath"]];
block(YES,message,modelResourcePath);
} else {
block(YES,message,@"");
}
} else {
block(NO,message,@"");
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,@"");
}];
}
//
+ (void)checkDurationWithAppId:(NSString *)appId block:(void (^) (BOOL isSuccess, NSString *msg))block {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// [dict setValue:appId forKey:@"appId"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@?appId=%@",baseUrl,GJCHECKDURATION,appId];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodGet success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
block(YES,message);
} else {
block(NO,message);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg);
}];
}
//
+ (void)toCreateSession:(NSString *)sig chatSessionId:(NSString*)chatSessionId conversationId:(NSString*)conversationId block:(void (^) (BOOL isSuccess, NSString *msg,NSString *sessionId,id responseObject))block
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// [dict setValue:sig forKey:@"sig"];
// [dict setValue:chatSessionId forKey:@"chatSessionId"];
// [dict setValue:conversationId forKey:@"conversationId"];
//
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@?sig=%@&chatSessionId=%@&conversationId=%@",baseUrl,CREATESESSIONV2,sig,chatSessionId,conversationId];
if(conversationId==nil || [conversationId isKindOfClass:[NSNull class]] || ([conversationId isKindOfClass:[NSString class]] && conversationId.length==0 ))
{
url = [NSString stringWithFormat:@"%@%@?sig=%@&chatSessionId=%@",baseUrl,CREATESESSIONV2,sig,chatSessionId];
}
url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodGet_Form success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
NSDictionary *data_dic=dic[@"data"];
if([data_dic isKindOfClass:[NSDictionary class]])
{
NSDictionary *conversationDto=data_dic[@"conversationDto"];
if([conversationDto isKindOfClass:[NSDictionary class]])
{
[GJLASRCofigModel manager].end_point=[[GJLGlobalFunc changeType:conversationDto[@"asrEndPoint"]] integerValue];
if([GJLASRCofigModel manager].end_point==0)
{
[GJLASRCofigModel manager].end_point=300;
}
}
}
if ([data_dic isKindOfClass:[NSDictionary class]])
{
NSString * sessionId=data_dic[@"sessionId"]?:@"";
if (success == 1) {
block(YES,message,sessionId,responseObject);
} else {
block(NO,message,nil,responseObject);
}
}
else
{
block(NO,message,nil,responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil,nil);
}];
}
//
+ (void)toEndSession:(NSString *)sig sessionId:(NSString*)sessionId chatSessionId:(NSString*)chatSessionId block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:sig forKey:@"sig"];
[dict setValue:sessionId forKey:@"sessionId"];
[dict setValue:chatSessionId forKey:@"chatSessionId"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,GJLENDSESSION];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodGet_Form success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
block(YES,message,responseObject);
} else {
block(NO,message,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil);
}];
}
//
+ (void)toHeartBeat:(NSString *)sig sessionId:(NSString*)sessionId chatSessionId:(NSString*)chatSessionId block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:sig forKey:@"sig"];
[dict setValue:sessionId forKey:@"sessionId"];
[dict setValue:chatSessionId forKey:@"chatSessionId"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,GJLHEARTBEAT];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodGet_Form success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
block(YES,message,responseObject);
} else {
block(NO,message,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil);
}];
}
//tts
+ (void)toCreateTTS:(NSString *)content conversationId:(NSString*)conversationId isWav:(BOOL)isWav block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:content forKey:@"content"];
[dict setValue:conversationId forKey:@"conversationId"];
[dict setValue:[NSNumber numberWithBool:isWav] forKey:@"isWav"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,CREATETTS];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodPost success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
block(YES,message,responseObject);
} else {
block(NO,message,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil);
}];
}
+(void)toReport:(NSMutableArray*)data_arr block:(void (^) (BOOL isSuccess, NSString *msg,id responseObject))block
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for(int i=0;i<data_arr.count;i++)
{
// SaveAudioModel * saveAudioModel=data_arr[i];
}
// [dict setValue:[NSNumber numberWithDouble:audio_duration] forKey:@"duration"];
NSString * baseUrl=[[GJHttpManager manager] getBaseUrl];
NSString *url = [NSString stringWithFormat:@"%@%@",baseUrl,CREATETTS];
[[GJLHttpClient manager] requestWithBaseURL:url para:dict headers:nil httpMethod:HttpMethodPost success:^(id responseObject) {
NSDictionary * dic=responseObject;
NSInteger success=[dic[@"success"]?:@"" integerValue];
NSString * message=dic[@"message"]?:@"";
if (success == 1) {
block(YES,message,responseObject);
} else {
block(NO,message,nil);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
block(NO,GJNetworkErrorMsg,nil);
}];
}
@end

View File

@@ -1,51 +0,0 @@
//
// HttpClient.h
// Xici
//
// Created by XICI-Jacob on 10/31/13.
//
//
#import "GJLAFNetworking.h"
typedef enum HttpMethod{
HttpMethodGet,
HttpMethodPost,
HttpMethodPost_Form, // post表单请求
HttpMethodGet_Form, // GET表单请求
}HttpMethod;
@interface GJLHttpClient : NSObject
{
NSString *lastUploadString;
}
@property(nonatomic,strong)NSString* token;
+ (GJLHttpClient *)manager;
- (void)requestWithBaseURL:(NSString *)url
para:(NSDictionary *)parameters
headers:(NSDictionary *)headers
httpMethod:(HttpMethod)httpMethod
success:(void (^)( id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task,NSError *error))failure;
- (NSURLSessionDownloadTask *)downloadWithURL:(NSString *)url
savePathURL:(NSURL *)fileURL
pathExtension:(NSString*)pathExtern
progress:(void (^)(NSProgress *))progress
success:(void (^)(NSURLResponse *response, NSURL *filePath))success
fail:(void (^)(NSError *error))fail;
- (void)requestImageWithURL:(NSString *)url
para:(NSDictionary *)parameters
headers:(NSDictionary *)headers
imageData:(NSData *)imageData
fileName:(NSString *)fileName
success:(void (^)( id responseObject))success
failure:(void (^)(NSURLSessionDataTask * task,NSError *error))failure;
@end

View File

@@ -1,247 +0,0 @@
//
// HttpClient.m
// Xici
//
// Created by XICI-Jacob on 10/31/13.
//
//
#import "GJLHttpClient.h"
#import "GJLOpenUDID.h"
#import <zlib.h>
@implementation GJLHttpClient
+ (GJLHttpClient *)manager {
static dispatch_once_t onceToken;
static GJLHttpClient *_sharedMangaer=nil;
dispatch_once(&onceToken, ^{
if (!_sharedMangaer) {
_sharedMangaer=[[GJLHttpClient alloc]init];
}
});
return _sharedMangaer;
}
- (id)init {
self = [super init];
if(self) {
}
return self;
}
-(void)requestWithBaseURL:(NSString *)url
para:(NSDictionary *)parameters
headers:(NSDictionary *)headers
httpMethod:(HttpMethod)httpMethod
success:(void (^)( id responseObject))success
failure:(void (^)(NSURLSessionDataTask * task,NSError *error))failure
{
GJLAFHTTPSessionManager *manager = [GJLAFHTTPSessionManager manager];
//json
manager.requestSerializer=[GJLAFJSONRequestSerializer serializer];
double time=[[NSDate date] timeIntervalSince1970];
NSString * token =self.token?:@"";
NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString * skipVersion=[[NSUserDefaults standardUserDefaults] valueForKey:@"skipVersion"];
NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
headers=@{@"deviceType":@"1",@"deviceID":[GJLOpenUDID value],@"token":token,@"version":app_Version,@"skipVersion":skipVersion?:@"0",@"packageName":bundleID};
//json
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
if (httpMethod == HttpMethodPost_Form) {
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
httpMethod = HttpMethodPost;
}
else if (httpMethod == HttpMethodGet_Form)
{
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
httpMethod = HttpMethodGet;
}
else
{
manager.requestSerializer=[GJLAFJSONRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"image/jpg",@"audio/mpeg", nil];
}
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval=60.0;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
if (httpMethod == HttpMethodPost) {
[manager POST:url parameters:parameters headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
double time2=[[NSDate date] timeIntervalSince1970];
NSLog(@"\nHttpClient====time:%f\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",time2-time,url,parameters,responseObject);
success(responseObject);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"\nHttpClient==end==error=\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",url,parameters,error);
failure(task,error);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
}];
} else if (httpMethod==HttpMethodGet) {
[manager GET:url parameters:parameters headers:headers progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
double time2=[[NSDate date] timeIntervalSince1970];
NSLog(@"\nHttpClient====time:%f\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",time2-time,url,parameters,responseObject);
success(responseObject);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"\nHttpClient====error=\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",url,parameters,error);
failure(task,error);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
}];
}
}
/////
///// @param url
///// @param parameters
///// @param headers
///// @param imageData data
///// @param fileName
///// @param success
///// @param failure
//- (void)requestImageWithURL:(NSString *)url
// para:(NSDictionary *)parameters
// headers:(NSDictionary *)headers
// imageData:(NSData *)imageData
// fileName:(NSString *)fileName
// success:(void (^)( id responseObject))success
// failure:(void (^)(NSURLSessionDataTask * task,NSError *error))failure {
//
// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// //json
// manager.requestSerializer=[AFJSONRequestSerializer serializer];
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
//// [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"deviceType"];
// [manager.requestSerializer setValue:[OpenUDID value] forHTTPHeaderField:@"deviceID"];
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"image/jpg",@"image/png",@"image/gif",@"video/mp4", nil];
// double time=[[NSDate date] timeIntervalSince1970];
// [manager POST:url parameters:parameters headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg/gif/tiff/mp4/wav/m4a"];
//
// } progress:^(NSProgress * _Nonnull uploadProgress) {
//
// } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// success(responseObject);
// double time2=[[NSDate date] timeIntervalSince1970];
// NSLog(@"\nHttpClient====time:%f\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",time2-time,url,parameters,responseObject);
// } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// NSLog(@"\nHttpClient====error=\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",url,parameters,error);
// failure(task,error);
// }];
//}
- (NSURLSessionDownloadTask *)downloadWithURL:(NSString *)url
savePathURL:(NSURL *)fileURL
pathExtension:(NSString*)pathExtern
progress:(void (^)(NSProgress *))progress
success:(void (^)(NSURLResponse *response, NSURL *filePath))success
fail:(void (^)(NSError *error))fail
{
NSLog(@"url:%@",url);
GJLAFHTTPSessionManager *manager = [self managerWithBaseURL:nil sessionConfiguration:NO];
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"image/jpg",@"image/png",@"audio/wav",@"audio/mpeg", nil];
NSURL *urlpath = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:urlpath];
NSLog(@"fileURL:%@",fileURL.absoluteString) ;
NSURLSessionDownloadTask *downloadtask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
progress(downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSString * filename=[response suggestedFilename];
if (pathExtern!=nil) {
filename= [filename stringByDeletingPathExtension];
filename=[NSString stringWithFormat:@"%@.%@",filename,pathExtern];
}
return [fileURL URLByAppendingPathComponent:filename];
// return fileURL;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (error) {
fail(error);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
} else {
success(response,filePath);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
}
}];
[downloadtask resume];
return downloadtask;
}
- (GJLAFHTTPSessionManager *)managerWithBaseURL:(NSString *)baseURL sessionConfiguration:(BOOL)isconfiguration {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
GJLAFHTTPSessionManager *manager = nil;
NSURL *url = [NSURL URLWithString:baseURL];
if (isconfiguration) {
manager = [[GJLAFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
} else {
manager = [[GJLAFHTTPSessionManager alloc] initWithBaseURL:url];
}
manager.requestSerializer = [GJLAFHTTPRequestSerializer serializer];
manager.responseSerializer = [GJLAFHTTPResponseSerializer serializer];
return manager;
}
///
/// @param url
/// @param parameters
/// @param headers
/// @param imageData data
/// @param fileName
/// @param success
/// @param failure
- (void)requestImageWithURL:(NSString *)url
para:(NSDictionary *)parameters
headers:(NSDictionary *)headers
imageData:(NSData *)imageData
fileName:(NSString *)fileName
success:(void (^)( id responseObject))success
failure:(void (^)(NSURLSessionDataTask * task,NSError *error))failure {
GJLAFHTTPSessionManager *manager = [GJLAFHTTPSessionManager manager];
//json
manager.requestSerializer=[GJLAFJSONRequestSerializer serializer];
manager.responseSerializer = [GJLAFJSONResponseSerializer serializer];
// [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"deviceType"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html",@"image/jpg",@"image/png",@"image/gif",@"video/mp4", nil];
// [manager.requestSerializer setValue:@"multipart/form-data; boundary=32343211" forHTTPHeaderField:@"Content-Type"];
// __weak typeof(self)weakSelf = self;
NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString * skipVersion=[[NSUserDefaults standardUserDefaults] valueForKey:@"skipVersion"];
NSString * token = self.token?:@"";
headers=@{@"deviceType":@"1",@"deviceID":[GJLOpenUDID value],@"token":token,@"version":app_Version,@"skipVersion":skipVersion?:@"0"};
double time=[[NSDate date] timeIntervalSince1970];
[manager POST:url parameters:parameters headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:imageData name:@"imageFile" fileName:fileName mimeType:@"image/jpg/png/jpeg/gif/tiff/mp4/wav/m4a"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
double time2=[[NSDate date] timeIntervalSince1970];
NSLog(@"\nHttpClient====time:%f\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",time2-time,url,parameters,responseObject);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
// if (GYCODE.integerValue == 503) {
// [weakSelf tokenInvalid];
// } else if (GYCODE.integerValue == 1006) {
// //token
// [weakSelf tokenInvalid];
// }
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"\nHttpClient====error=\nurl=%@:\nparameters=\n%@\nresponseObject=\n%@",url,parameters,error);
failure(task,error);
[manager invalidateSessionCancelingTasks:YES resetSession:YES];
}];
}
@end

View File

@@ -1,20 +0,0 @@
//
// JWTGenerator.h
// GJLocalDigitalSDK
//
// Created by guiji on 2025/5/15.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface JWTGenerator : NSObject
+ (NSString *)generateJWTWithPayload:(NSDictionary *)payload
secretKey:(NSString *)secretKey;
@end
NS_ASSUME_NONNULL_END

View File

@@ -1,59 +0,0 @@
//
// JWTGenerator.m
// GJLocalDigitalSDK
//
// Created by guiji on 2025/5/15.
//
#import "JWTGenerator.h"
#import <CommonCrypto/CommonHMAC.h>
@implementation JWTGenerator
+ (NSString *)generateJWTWithPayload:(NSDictionary *)payload
secretKey:(NSString *)secretKey {
// 1. Header
NSDictionary *header = @{
@"alg": @"HS256",
@"typ": @"JWT"
};
// 2. Base64URLHeader
NSData *headerData = [NSJSONSerialization dataWithJSONObject:header options:0 error:nil];
NSString *headerBase64 = [[self base64EncodedStringFromData:headerData] stringByReplacingOccurrencesOfString:@"=" withString:@""];
headerBase64 = [headerBase64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
headerBase64 = [headerBase64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
// 3. Payload
NSMutableDictionary *processedPayload = [payload mutableCopy];
[payload enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSString class]]) {
NSString *encodedValue = [obj stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
[processedPayload setValue:encodedValue forKey:key];
}
}];
// 4. Base64URLPayload
NSData *payloadData = [NSJSONSerialization dataWithJSONObject:processedPayload options:0 error:nil];
NSString *payloadBase64 = [[self base64EncodedStringFromData:payloadData] stringByReplacingOccurrencesOfString:@"=" withString:@""];
payloadBase64 = [payloadBase64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
payloadBase64 = [payloadBase64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
// 5.
NSString *signingInput = [NSString stringWithFormat:@"%@.%@", headerBase64, payloadBase64];
NSData *signingInputData = [signingInput dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [secretKey dataUsingEncoding:NSUTF8StringEncoding];
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, keyData.bytes, keyData.length, signingInputData.bytes, signingInputData.length, digest);
NSData *signatureData = [NSData dataWithBytes:digest length:CC_SHA256_DIGEST_LENGTH];
NSString *signatureBase64 = [[self base64EncodedStringFromData:signatureData] stringByReplacingOccurrencesOfString:@"=" withString:@""];
signatureBase64 = [signatureBase64 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
signatureBase64 = [signatureBase64 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
// 6. JWT
return [NSString stringWithFormat:@"%@.%@.%@", headerBase64, payloadBase64, signatureBase64];
}
+ (NSString *)base64EncodedStringFromData:(NSData *)data {
return [data base64EncodedStringWithOptions:0];
}
@end

View File

@@ -1,154 +0,0 @@
//
// Copyright 2012 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <Foundation/Foundation.h>
#import <Security/SecCertificate.h>
typedef NS_ENUM(NSInteger, SRReadyState) {
SR_CONNECTING = 0,
SR_OPEN = 1,
SR_CLOSING = 2,
SR_CLOSED = 3,
};
typedef enum SRStatusCode : NSInteger {
// 0999: Reserved and not used.
SRStatusCodeNormal = 1000,
SRStatusCodeGoingAway = 1001,
SRStatusCodeProtocolError = 1002,
SRStatusCodeUnhandledType = 1003,
// 1004 reserved.
SRStatusNoStatusReceived = 1005,
SRStatusCodeAbnormal = 1006,
SRStatusCodeInvalidUTF8 = 1007,
SRStatusCodePolicyViolated = 1008,
SRStatusCodeMessageTooBig = 1009,
SRStatusCodeMissingExtension = 1010,
SRStatusCodeInternalError = 1011,
SRStatusCodeServiceRestart = 1012,
SRStatusCodeTryAgainLater = 1013,
// 1014: Reserved for future use by the WebSocket standard.
SRStatusCodeTLSHandshake = 1015,
// 10161999: Reserved for future use by the WebSocket standard.
// 20002999: Reserved for use by WebSocket extensions.
// 30003999: Available for use by libraries and frameworks. May not be used by applications. Available for registration at the IANA via first-come, first-serve.
// 40004999: Available for use by applications.
} SRStatusCode;
@class SRWebSocket;
extern NSString *const SRWebSocketErrorDomain;
extern NSString *const SRHTTPResponseErrorKey;
#pragma mark - SRWebSocketDelegate
@protocol SRWebSocketDelegate;
#pragma mark - SRWebSocket
@interface SRWebSocket : NSObject <NSStreamDelegate>
@property (nonatomic, weak) id <SRWebSocketDelegate> delegate;
@property (nonatomic, readonly) SRReadyState readyState;
@property (nonatomic, readonly, retain) NSURL *url;
@property (nonatomic, readonly) CFHTTPMessageRef receivedHTTPHeaders;
// Optional array of cookies (NSHTTPCookie objects) to apply to the connections
@property (nonatomic, readwrite) NSArray * requestCookies;
// This returns the negotiated protocol.
// It will be nil until after the handshake completes.
@property (nonatomic, readonly, copy) NSString *protocol;
// Protocols should be an array of strings that turn into Sec-WebSocket-Protocol.
- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;
- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols;
- (id)initWithURLRequest:(NSURLRequest *)request;
// Some helper constructors.
- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;
- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols;
- (id)initWithURL:(NSURL *)url;
// Delegate queue will be dispatch_main_queue by default.
// You cannot set both OperationQueue and dispatch_queue.
- (void)setDelegateOperationQueue:(NSOperationQueue*) queue;
- (void)setDelegateDispatchQueue:(dispatch_queue_t) queue;
// By default, it will schedule itself on +[NSRunLoop SR_networkRunLoop] using defaultModes.
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
// SRWebSockets are intended for one-time-use only. Open should be called once and only once.
- (void)open;
- (void)close;
- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason;
// Send a UTF8 String or Data.
- (void)send:(id)data;
// Send Data (can be nil) in a ping message.
- (void)sendPing:(NSData *)data;
@end
#pragma mark - SRWebSocketDelegate
@protocol SRWebSocketDelegate <NSObject>
// message will either be an NSString if the server is using text
// or NSData if the server is using binary.
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
@optional
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
// Return YES to convert messages sent as Text to an NSString. Return NO to skip NSData -> NSString conversion for Text messages. Defaults to YES.
- (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket;
@end
#pragma mark - NSURLRequest (SRCertificateAdditions)
@interface NSURLRequest (SRCertificateAdditions)
@property (nonatomic, retain, readonly) NSArray *SR_SSLPinnedCertificates;
@end
#pragma mark - NSMutableURLRequest (SRCertificateAdditions)
@interface NSMutableURLRequest (SRCertificateAdditions)
@property (nonatomic, retain) NSArray *SR_SSLPinnedCertificates;
@end
#pragma mark - NSRunLoop (SRWebSocket)
@interface NSRunLoop (SRWebSocket)
+ (NSRunLoop *)SR_networkRunLoop;
@end

View File

@@ -1,17 +0,0 @@
//
// Copyright 2012 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <SocketRocket/SRWebSocket.h>

View File

@@ -1,36 +0,0 @@
//
// WebSocketManager.h
// GuiYuSiri
//
// Created by guiji on 2021/8/11.
//
#import <Foundation/Foundation.h>
#import "SRWebSocket.h"
typedef void (^onMessage)(id message);
typedef void (^onError)(NSError*err);
typedef void (^onSucess)(NSInteger type);
@interface WebSocketManager : NSObject<SRWebSocketDelegate>
{
NSTimer * web_timer;
}
+(WebSocketManager*)manager;
@property (nonatomic, strong)SRWebSocket * webSocket;
@property (nonatomic, copy) onSucess on_success;
@property (nonatomic, copy) onMessage on_message;
@property (nonatomic, copy) onError on_err;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, assign)double time1;
@property (nonatomic, assign)BOOL isASRSucess;
@property (nonatomic, assign) NSInteger connect_count;
-(void)toStart:(NSDictionary*)dic;
-(void)reconnect;
-(void)sendMesage:(NSString*)mesage;
-(void)stopWebSocket;
- (void)sendData:(NSData *)data;
@end

View File

@@ -1,242 +0,0 @@
//
// WebSocketManager.m
// GuiYuSiri
//
// Created by guiji on 2021/8/11.
//
#import "WebSocketManager.h"
#import "GJLGCDTimer.h"
#import "GJHttpManager.h"
@interface WebSocketManager()
@property (nonatomic, strong) GJLGCDTimer *reconnectTimer;
@property (nonatomic, strong) dispatch_queue_t reconnect_timer_queue;
@property (nonatomic, strong)NSMutableDictionary * headDic;
@end
@implementation WebSocketManager
static WebSocketManager *_sharedSingleton = nil;
+(WebSocketManager*)manager
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (_sharedSingleton==nil) {
_sharedSingleton = [[WebSocketManager alloc] init];
}
});
return _sharedSingleton;
}
-(id)init
{
self=[super init];
if(self)
{
self.headDic=[[NSMutableDictionary alloc] init];
self.reconnect_timer_queue= dispatch_queue_create("com.digitalsdk.reconnect_timer_queue", DISPATCH_QUEUE_SERIAL);
}
return self;
}
#pragma mark ---------------------websocket--------------------------
-(void)reconnect
{
self.time1=[[NSDate date] timeIntervalSince1970];
if(self.webSocket!=nil)
{
self.webSocket.delegate = nil;
[self.webSocket close];
self.webSocket = nil;
}
if ([web_timer isValid]) {
[web_timer invalidate];
web_timer=nil;
}
[NSThread cancelPreviousPerformRequestsWithTarget:self];
[NSThread detachNewThreadSelector:@selector(toStartContent) toTarget:self withObject:nil];
}
-(void)toStart:(NSDictionary*)dic
{
[self.headDic removeAllObjects];
[self.headDic addEntriesFromDictionary:dic];
self.connect_count=0;
[self reconnect];
}
-(void)toStartContent
{
NSString *url =[[GJHttpManager manager] getWsUrl];
NSLog(@"url:%@",url);
// url
NSMutableURLRequest* request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.timeoutInterval=60;
[request setHTTPMethod:@"GET"];
// [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];//
// [request setValue:auth forHTTPHeaderField:@"auth"];//
// [request setValue:uuid forHTTPHeaderField:@"uuid"];//
// [request setValue:endpoint forHTTPHeaderField:@"endpoint"];//
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:request];
self.webSocket.delegate = self;
[self.webSocket open];
}
#pragma mark - SRWebSocketDelegate //
//
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
// [self sendHeart];
double time2=[[NSDate date] timeIntervalSince1970];
NSLog(@"连接时长:%f",time2-self.time1);
//30
web_timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(sendHeart) userInfo:nil repeats:YES];
//
NSLog(@"Websocket Connected");
self.isOpen=YES;
if(self.on_success)
{
self.on_success(1);
}
}
//
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
//
self.isOpen=NO;
if(error!=nil)
{
self.connect_count++;
if(self.connect_count>10)
{
[self toStopReconnectTimer];
__weak typeof(self)weakSelf = self;
self.reconnectTimer =[GJLGCDTimer scheduledTimerWithTimeInterval:5 repeats:NO queue:self.reconnect_timer_queue block:^{
[weakSelf reconnect];
}];
}
else
{
[self reconnect];
}
}
if (self.on_err) {
self.on_err(error);
}
NSLog(@":( Websocket Failed With Error %@", error);
}
//
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
//
// NSLog(@"message返回:%@",message);
if (self.on_message)
{
self.on_message(message);
}
// NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:messageData options:0 error:nil];
// if (![jsonObject isKindOfClass:[NSDictionary class]]) {
// NSLog(@"Unexpected message: %@", jsonObject);
// return;
// }
// NSDictionary * dic=jsonObject;
// if([dic isKindOfClass:[NSDictionary class]])
// {
// if (self.on_message) {
// self.on_message(dic);
// }
// }
// NSString * code_str=[dic objectForKey:@"code"]?:@"";
// // NSString * msg_str=[dic objectForKey:@"msg"];
//
// if ([code_str integerValue]==0) {
// NSString * data_str=[dic objectForKey:@"data"]?:@"";
// int position=[data_str intValue];
// if (position>0)
// {
//
// if (self.on_message) {
// self.on_message(position);
// }
//
// }
// }
}
//
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
//
// [SVProgressHUD showInfoWithStatus:@"webSocket Closed"];
NSLog(@"webSocket Closed!:%@",reason);
}
// pong
- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
NSLog(@"Websocket received pong");
}
//
- (void)sendHeart{
// NSMutableDictionary *dict = [NSMutableDictionary dictionary];
// [dict setValue:@"ping" forKey:@"eventType"];
// NSString *heartBeat = [GJLGlobalFunc dataToJsonString:dict];
// @try {
// if (self.isOpen)
// {
// [self sendMesage:heartBeat];
// }
//
// } @catch (NSException *exception) {
// //
// [self reconnect];
// }
}
-(void)sendMesage:(NSString*)mesage
{
if (mesage!=nil && self.isOpen)
{
[ self.webSocket send:mesage];
}
}
- (void)sendData:(NSData *)data {
// NSLog(@"data.length:%ld",data.length);
if (data!=nil&&data.length != 0 && self.isOpen)
{
[ self.webSocket send:data];
}
}
-(void)toStopReconnectTimer
{
if(self.reconnectTimer!=nil) {
[self.reconnectTimer invalidate];
self.reconnectTimer = nil;
}
}
-(void)stopWebSocket
{
[self.headDic removeAllObjects];
if ([web_timer isValid]) {
[web_timer invalidate];
web_timer=nil;
}
[self toStopReconnectTimer];
self.connect_count=0;
self.isOpen = NO;
[self.webSocket close];
self.webSocket = nil;
self.webSocket.delegate = nil;
[NSThread cancelPreviousPerformRequestsWithTarget:self];
}
@end

View File

@@ -1,5 +1,7 @@
## Silicon Basic Edition DUIX SDK Usage Document (1.2.0)
[简体中文](./GJLocalDigitalSDK.md) | English
### Supported Systems and Hardware Versions
 GJLocalDigitalSDK.framework  (-Embed & Sign)
 
@@ -17,8 +19,7 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
if(result==1)
{
// NSString *bgpath =[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],@"bg2.jpg"];
// [[GJLDigitalManager manager] toChangeBBGWithPath:bgpath];
[[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg) {
if(isSuccess)
{
@@ -28,12 +29,11 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
[[GJLDigitalManager manager] toStartRuning];
[weakSelf initASR];
[[GJLASRManager manager] toOpenAsr];
});
//
}
else
@@ -297,78 +297,7 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
-(void)toPause;
```
## Speech Recognition
### Initialize Recording and ASR
```
/*
* Initialize recording and ASR
*/
-(void)initASR;
```
### Start Recognition
```
/*
* Start recognition
*/
-(void)toOpenAsr;
```
### Stop Recognition
```
/*
* Stop recognition
*/
-(void)toCloseAsr;
```
### Speech Recognition Callbacks
```
@property (nonatomic, copy) void (^asrBlock)(NSString * asrText,BOOL isFinish);
/*
* data - recorded data (mono, 16000Hz sample rate)
*/
@property (nonatomic, copy) void (^recordDataBlock)(NSData * data);
/*
* Volume callback
*/
@property (nonatomic, copy) void (^rmsBlock)(float rms);
@property (nonatomic, copy) void (^errBlock)(NSError *err);
/*
* Server starts pushing audio stream
*/
@property (nonatomic, copy) void (^startPushBlock)(void);
/*
* data - server returns audio stream (mono, 16000Hz sample rate)
*/
@property (nonatomic, copy) void (^pushDataBlock)(NSData * data);
/*
* Server stops pushing audio stream
*/
@property (nonatomic, copy) void (^stopPushBlock)(void);
/*
* Large model returns text
*/
@property (nonatomic, copy) void (^speakTextBlock)(NSString * speakText);
/*
* Returns action marker
*/
@property (nonatomic, copy) void (^motionBlock)(NSString * motionText);
```
## Version History

View File

@@ -1,210 +1,187 @@
## 硅基本地版DUIX-PRO SDK使⽤⽂档 (1.2.0)
### 物料准备
 GJLocalDigitalSDK.framework  (-Embed & Sign)
 
简体中文 | [English](./GJLocalDigitalSDK_en.md)
### 开发环境
开发⼯具: Xcode  ios12.0以上 iphone8及以上
---
## 快速开始
## 一、产品概述
`硅基本地版 DUIX-PRO SDK` 是一套轻量级的本地部署 2D 虚拟人解决方案,支持通过语音实时驱动虚拟人形象。该 SDK 可在 iOS 设备上运行,具备低延迟、高帧率、边缘计算离线运行等优势。
### 1.1 适用场景
- **部署成本低**:无需服务端支持,适合大屏终端、本地 App 快速集成;
- **网络依赖小**:本地模型运行,支持政务大厅、展厅、机场等弱网环境;
- **功能多样化**:适用于导览播报、业务咨询、数字迎宾等 AI 数字人应用场景。
### 1.2 核心功能
- **数字人渲染与驱动**:支持本地渲染虚拟人形象,响应语音输入实时口型驱动;
- **语音播报控制**支持音频播放、PCM 推流、动作与播报联动;
- **动作控制系统**:可自定义启动、停止、随机动作;
本 SDK 提供本地部署的 2D 数字人渲染及语音播报能力,适用于 iOS 12+ 版本的设备。支持语音驱动数字人形象的实时呈现,具备低延迟、低功耗、高性能等特点。
---
## 二、开发准备
- **SDK 组件**`GJLocalDigitalSDK.framework`(设置为 Embed & Sign
- **开发环境**
- Xcode 12 及以上
- iPhone 8 及以上设备
- iOS 12.0+
---
## 三、快速开始
```
//授权
NSInteger result= [[GJLDigitalManager manager] initBaseModel:weakSelf.basePath digitalModel:weakSelf.digitalPath showView:weakSelf.showView];
if(result==1)
{
// NSString *bgpath =[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],@"bg2.jpg"];
// [[GJLDigitalManager manager] toChangeBBGWithPath:bgpath];
[[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg) {
if(isSuccess)
{
dispatch_async(dispatch_get_main_queue(), ^{
[[GJLDigitalManager manager] toStartRuning];
[weakSelf initASR];
[[GJLASRManager manager] toOpenAsr];
});
//
NSInteger result = [[GJLDigitalManager manager] initBaseModel:weakSelf.basePath
digitalModel:weakSelf.digitalPath
showView:weakSelf.showView];
}
else
{
[SVProgressHUD showInfoWithStatus:errorMsg];
}
}];
}
```
## 调用流程
```
1. 启动服务前需要准备好授权的appId,appKey以及同步数字人需要的基础配置和模型文件。
2. 使用授权接口授权。
3. 初始化数字人渲染服务。
4. 调用toStart函数开始渲染数字人
5. 调用toSpeakWithPath函数驱动数字人播报。
6. 调用cancelAudioPlay函数可以主动停止播报。
7. 调用toStop结束并释放数字人渲染
```
if (result == 1) {
// 2. 启动渲染
[[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg) {
if (isSuccess) {
dispatch_async(dispatch_get_main_queue(), ^{
// 3. 启动流式驱动
[[GJLDigitalManager manager] toStartRuning];
});
} else {
[SVProgressHUD showInfoWithStatus:errorMsg];
}
}];
}
### SDK回调
```
/*
*数字人渲染报错回调
*0 未授权 -1未初始化 50009资源超时或未配置
*/
@property (nonatomic, copy) void (^playFailed)(NSInteger code,NSString *errorMsg);
---
/*
*音频播放结束回调
*/
@property (nonatomic, copy) void (^audioPlayEnd)(void);
## 四、调用流程
```
1.准备资源:同步数字人所需的基础配置和模型文件
/*
*音频播放进度回调
/
@property (nonatomic, copy) void (^audioPlayProgress)(float current,float total);
2.初始化服务initBaseModel:digitalModel:showView:
3.启动渲染toStart:
4.驱动播报toWavPcmData:(流式驱动)
5.停止播报stopPlaying:(主动停止)
6.释放资源toStop结束渲染
```
## 方法
---
## 五、核心功能接口
### 初始化
### 5.1 初始化配置
```
/*
*basePath 底层通用模型路径-保持不变
*digitalPath 数字人模型路径- 替换数字人只需要替换这个路径
*return 1 返回成功 0未授权 -1 初始化失败
*showView 显示界面
*/
/**
* 初始化数字人服务
* @param basePath 基础模型路径(固定不变)
* @param digitalPath 数字人模型路径(替换数字人时更新此路径)
* @param showView 数字人渲染视图
* @return 状态码 1=成功, 0=未授权, -1=失败
*/
-(NSInteger)initBaseModel:(NSString*)basePath digitalModel:(NSString*)digitalPath showView:(UIView*)showView;
```
### 替换背景
### 5.2 渲染数字人控制
```
/*
* bbgPath 替换背景
* 注意: -jpg格式 ----背景size等于数字人模型的getDigitalSize-----------
*启动数字人渲染
*/
-(void)toStart:(void (^) (BOOL isSuccess, NSString *errorMsg))block;
```
```
/*
*停止渲染并释放资源
*/
-(void)toStop;
```
```
/*
*恢复播放(暂停后调用)
*/
-(void)toPlay;
```
```
/*
*暂停数字人播放
*/
-(void)toPause;
```
### 5.3 背景管理
```
/**
* 动态替换背景
* @param bbgPath JPG格式背景图路径
*/
-(void)toChangeBBGWithPath:(NSString*)bbgPath;
```
### 开始渲染数字人
### 5.4 音频控制
```
/*
*开始
*/
-(void)toStart:(void (^) (BOOL isSuccess, NSString *errorMsg))block;
```
### 结束渲染数字人并释放
```
/*
*结束
*/
-(void)toStop;
```
### 数字人模型的宽度高度
```
/*
*初始化模型过后才能获取
*getDigitalSize 数字人模型的宽度 数字人模型的高度
*/
-(CGSize)getDigitalSize;
```
### 取消播放音频
```
/*
*取消播放音频
*/
-(void)cancelAudioPlay;
```
### 授权成功
```
/*
*是否授权成功
*/
-(NSInteger)isGetAuth;
```
### PCM流式
```
/*
*开始录音和播放
*/
-(void)toStartRuning;
```
```
/*
*一句话或一段话的初始化session
*/
-(void)newSession;
```
```
/*
*一句话或一段话的推流结束调用finishSession 而非播放结束调用
*/
-(void)finishSession;
```
```
/*
*finishSession 结束后调用续上continueSession
*/
-(void)continueSession;
```
```
/*
*是否静音
*/
-(void)toMute:(BOOL)isMute;
```
```
/*
*pcm
*size
* 参考demo里面GJLPCMManager类里toSpeakWithPath 转换成pcm的代码
*audioData播放音频流 参考demo里面GJLPCMManager类里toSpeakWithPath 转换成pcm的代码
*驱动数字人播报(PCM流)
*/
-(void)toWavPcmData:(NSData*)audioData;
```
```
/*
*清空buffer
* 开始音频流播放
*/
- (void)startPlaying;
```
```
/*
* 结束音频流播放
*/
- (void)stopPlaying:(void (^)( BOOL isSuccess))success;
```
```
/*
*设置静音模式
*/
-(void)toMute:(BOOL)isMute;
```
```
/*
*清空音频缓冲区
*/
-(void)clearAudioBuffer;
```
```
/*
*暂停播放音频流
@@ -220,177 +197,143 @@
-(void)toResumePcm;
```
```
/*
* 是否启用录音
*/
*/
-(void)toEnableRecord:(BOOL)isEnable;
```
### 5.5 流式会话管理
```
/*
* 开始音频流播放
*启动流式会话
*/
- (void)startPlaying;
-(void)toStartRuning;
```
```
/*
* 结束音频流播放
*开始新会话(单句/段落)
*/
- (void)stopPlaying:(void (^)( BOOL isSuccess))success;
-(void)newSession;
```
## 动作
### 随机动作
```
/*
* 开始动作前调用
* 随机动作(一段文字包含多个音频,建议第一个音频开始时设置随机动作)
* return 0 数字人模型不支持随机动作 1 数字人模型支持随机动作
*结束当前会话
*/
-(void)finishSession;
```
```
/*
*继续会话finish后调用
*/
-(void)continueSession;
```
### 5.6 动作控制
```
/*
* 启用随机动作(建议在首段音频开始时调用)
* 返回0=不支持, 1=成功
*/
-(NSInteger)toRandomMotion;
```
### 开始动作
```
/*
* 开始动作 (一段文字包含多个音频,第一个音频开始时设置
* return 0 数字人模型不支持开始动作 1 数字人模型支持开始动作
* 启用开始动作(首段音频开始时调用
* 返回0=不支持, 1=成功
*/
-(NSInteger)toStartMotion;
```
### 结束动作
```
/*
* 结束动作 (一段文字包含多个音频,最后一个音频播放结束时设置
*isQuickly YES 立即结束动作 NO 等待动作播放完成再静默
*return 0 数字人模型不支持结束动作 1 数字人模型支持结束动作
* 结束动作(末段音频结束时调用
*isQuickly: YES=立即结束, NO=等待动作完成
*返回0=不支持, 1=成功
*/
-(NSInteger)toSopMotion:(BOOL)isQuickly;
```
### 暂停后开始播放数字人
### 5.7 状态查询
```
/*
*暂停后才需执行播放数字人
*获取数字人模型尺寸(需初始化后调用)
*/
-(CGSize)getDigitalSize;
```
```
/*
*检查授权状态1=已授权)
*/
-(NSInteger)isGetAuth;
```
---
## 六、回调定义
```
/*
*数字人渲染报错
*错误码说明:
* 0 = 未授权
* -1 = 未初始化
* 50009 = 资源超时/未配置
*/
-(void)toPlay;
```
@property (nonatomic, copy) void (^playFailed)(NSInteger code,NSString *errorMsg);
### 暂停数字人播放
```
/*
*暂停数字人播放
*音频播放结束回调
*/
-(void)toPause;
```
## 语音识别
### 初始化录音和ASR
```
/*
*初始化录音和ASR
*/
-(void)initASR;
```
### 开始识别
```
/*
*开始识别
*/
-(void)toOpenAsr;
```
### 停止识别
```
/*
*停止识别
*/
-(void)toCloseAsr;
```
### 语音识别回调
```
@property (nonatomic, copy) void (^asrBlock)(NSString * asrText,BOOL isFinish);
@property (nonatomic, copy) void (^audioPlayEnd)(void);
/*
*data 录音返回 单声道 1 采样率 16000
*/
@property (nonatomic, copy) void (^recordDataBlock)(NSData * data);
/*
*音量回调
*/
@property (nonatomic, copy) void (^rmsBlock)(float rms);
@property (nonatomic, copy) void (^errBlock)(NSError *err);
/*
* 服务端开始推送音频流
*/
@property (nonatomic, copy) void (^startPushBlock)(void);
/*
*data 服务端返回音频流 单声道 1 采样率 16000
*/
@property (nonatomic, copy) void (^pushDataBlock)(NSData * data);
/*
*服务端停止推送音频流
*/
@property (nonatomic, copy) void (^stopPushBlock)(void);
/*
*大模型返回文字
*/
@property (nonatomic, copy) void (^speakTextBlock)(NSString * speakText);
/*
*返回动作标记
*/
@property (nonatomic, copy) void (^motionBlock)(NSString * motionText);
*音频播放进度回调
/
@property (nonatomic, copy) void (^audioPlayProgress)(float current,float total);
```
## 版本记录
---
**1.2.0**
```
1. 支持pcm流式
```
## 七、版本更新记录
**1.0.3**
```
1. 数字人背景透明
2. 解压内存问题
```
### v1.2.0
**1.0.2**
```
1. 问答
2. 语音识别
3. 文字合成
4. 说话动作
```
- 新增 PCM 推流支持
### v1.0.3
**1.0.1**
```
1. 数字人本地授权和初始化
2. 数字人本地渲染
3. 音频播放和驱动嘴形
```
- 支持透明背景
- 优化模型解压内存
### v1.0.2
- 支持问答 / 语音识别 / 动作标注 / 合成播报
### v1.0.1
- 初始版本:授权 + 渲染 + 播报
---
## 八、参考开源项目
| 模块 | 描述 |
| --------------------------------------- | --------------- |
| [ONNX](https://github.com/onnx/onnx) | 通用人工智能模型格式 |
| [ncnn](https://github.com/Tencent/ncnn) | 高性能神经网络推理框架(腾讯) |
---
如需更多集成帮助,请联系技术支持。

View File

@@ -1,5 +1,7 @@
## Silicon Basic Edition DUIX SDK Usage Document (1.2.0)
[简体中文](./GJLocalDigitalSDK.md) | English
### Supported Systems and Hardware Versions
 GJLocalDigitalSDK.framework  (-Embed & Sign)
 
@@ -17,8 +19,7 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
if(result==1)
{
// NSString *bgpath =[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],@"bg2.jpg"];
// [[GJLDigitalManager manager] toChangeBBGWithPath:bgpath];
[[GJLDigitalManager manager] toStart:^(BOOL isSuccess, NSString *errorMsg) {
if(isSuccess)
{
@@ -28,12 +29,11 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
[[GJLDigitalManager manager] toStartRuning];
[weakSelf initASR];
[[GJLASRManager manager] toOpenAsr];
});
//
}
else
@@ -297,78 +297,7 @@ Development Tool: Xcode ios12.0 and above iphone8 and above
-(void)toPause;
```
## Speech Recognition
### Initialize Recording and ASR
```
/*
* Initialize recording and ASR
*/
-(void)initASR;
```
### Start Recognition
```
/*
* Start recognition
*/
-(void)toOpenAsr;
```
### Stop Recognition
```
/*
* Stop recognition
*/
-(void)toCloseAsr;
```
### Speech Recognition Callbacks
```
@property (nonatomic, copy) void (^asrBlock)(NSString * asrText,BOOL isFinish);
/*
* data - recorded data (mono, 16000Hz sample rate)
*/
@property (nonatomic, copy) void (^recordDataBlock)(NSData * data);
/*
* Volume callback
*/
@property (nonatomic, copy) void (^rmsBlock)(float rms);
@property (nonatomic, copy) void (^errBlock)(NSError *err);
/*
* Server starts pushing audio stream
*/
@property (nonatomic, copy) void (^startPushBlock)(void);
/*
* data - server returns audio stream (mono, 16000Hz sample rate)
*/
@property (nonatomic, copy) void (^pushDataBlock)(NSData * data);
/*
* Server stops pushing audio stream
*/
@property (nonatomic, copy) void (^stopPushBlock)(void);
/*
* Large model returns text
*/
@property (nonatomic, copy) void (^speakTextBlock)(NSString * speakText);
/*
* Returns action marker
*/
@property (nonatomic, copy) void (^motionBlock)(NSString * motionText);
```
## Version History