This commit is contained in:
启星
2025-08-11 10:43:19 +08:00
commit fb2c58d96f
8839 changed files with 709982 additions and 0 deletions

57
Podfile Executable file
View File

@@ -0,0 +1,57 @@
#platform :ios, '10.0'
source 'https://github.com/CocoaPods/Specs.git'
inhibit_all_warnings!
# 防止 TUI 组件里的 *.xcassets 与您项目里面冲突。
install! 'cocoapods', :disable_input_output_paths => true
target 'SweetParty' do
pod 'LLDebugTool',:configurations => ['Debug'] #调试工具
pod 'AFNetworking', '~> 3.0.0', :subspecs => ['Reachability', 'Serialization', 'Security', 'NSURLSession']
pod "MJRefresh"
pod 'SVProgressHUD'
pod "YYCache"
pod 'CRBoxInputView', '1.0.2'
pod "MJExtension"
pod "Masonry"
pod 'SVGAPlayer'
pod 'Protobuf', '3.9.0'
pod 'SSZipArchive'
pod 'SDWebImage'
pod 'HWPopController'
pod 'Bugly'
pod "MBProgressHUD" , '~> 1.0.0'
pod 'TZImagePickerController'
pod 'TXIMSDK_Plus_iOS'
pod 'ReactiveObjC'
#pod 'RongCloudIM/IMKit', '~> 5.1.0.1
#pod 'RongCloudIM/IMLib', '~> 5.1.0.1
#pod 'RongCloudRTC', '5.1.0'
pod 'AgoraRtcEngine_Special_iOS', '~> 4.3.2'
pod 'AgoraRtm_iOS'
pod 'AgoraLyricsScore'
pod 'SudMGPWrapper', '~> 1.4.0.1'
pod 'IQKeyboardManager'
pod 'GVUserDefaults'
pod 'BMKLocationKit'
pod 'mob_sharesdk'
#微信不包括支付
pod 'mob_sharesdk/ShareSDKPlatforms/WeChat_Lite'
pod 'mob_sharesdk/ShareSDKPlatforms/QQ'
pod 'WechatOpenSDK'
pod 'AlipaySDK-iOS'
pod 'CL_ShanYanSDK'
pod 'TFPopup'
pod 'SDAutoLayout'
end

239
Podfile.lock Executable file
View File

@@ -0,0 +1,239 @@
PODS:
- AFNetworking/NSURLSession (3.0.4):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (3.0.4)
- AFNetworking/Security (3.0.4)
- AFNetworking/Serialization (3.0.4)
- AgoraComponetLog (0.0.1)
- AgoraLyricsScore (1.1.6):
- AgoraComponetLog
- Zip
- AgoraRtcEngine_Special_iOS (4.3.2.230)
- AgoraRtm_iOS (1.5.1)
- AlipaySDK-iOS (15.8.30)
- BMKLocationKit (2.0.2)
- Bugly (2.5.91)
- CL_ShanYanSDK (2.3.6.0)
- CRBoxInputView (1.0.2):
- Masonry
- FMDB (2.7.12):
- FMDB/standard (= 2.7.12)
- FMDB/Core (2.7.12)
- FMDB/standard (2.7.12):
- FMDB/Core
- GVUserDefaults (1.0.2)
- HWPopController (1.0.7)
- IQKeyboardManager (6.5.9)
- LLDebugTool (1.3.8.1):
- LLDebugTool/AppInfo (= 1.3.8.1)
- LLDebugTool/Core (= 1.3.8.1)
- LLDebugTool/Crash (= 1.3.8.1)
- LLDebugTool/Hierarchy (= 1.3.8.1)
- LLDebugTool/Html (= 1.3.8.1)
- LLDebugTool/Location (= 1.3.8.1)
- LLDebugTool/Log (= 1.3.8.1)
- LLDebugTool/Magnifier (= 1.3.8.1)
- LLDebugTool/Network (= 1.3.8.1)
- LLDebugTool/Ruler (= 1.3.8.1)
- LLDebugTool/Sandbox (= 1.3.8.1)
- LLDebugTool/Screenshot (= 1.3.8.1)
- LLDebugTool/ShortCut (= 1.3.8.1)
- LLDebugTool/Storage (= 1.3.8.1)
- LLDebugTool/WidgetBorder (= 1.3.8.1)
- LLDebugTool/AppInfo (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Core (1.3.8.1)
- LLDebugTool/Crash (1.3.8.1):
- LLDebugTool/Storage
- LLDebugTool/Hierarchy (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Html (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Location (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Log (1.3.8.1):
- LLDebugTool/Storage
- LLDebugTool/Magnifier (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Network (1.3.8.1):
- LLDebugTool/Storage
- LLDebugTool/Ruler (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Sandbox (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Screenshot (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/ShortCut (1.3.8.1):
- LLDebugTool/Core
- LLDebugTool/Storage (1.3.8.1):
- FMDB (~> 2.0)
- LLDebugTool/Core
- LLDebugTool/WidgetBorder (1.3.8.1):
- LLDebugTool/Core
- Masonry (1.1.0)
- MBProgressHUD (1.0.0)
- MJExtension (3.4.1)
- MJRefresh (3.7.5)
- mob_sharesdk (4.4.12):
- mob_sharesdk/ShareSDK (= 4.4.12)
- MOBFoundation (>= 3.2.9)
- mob_sharesdk/ShareSDK (4.4.12):
- MOBFoundation (>= 3.2.9)
- mob_sharesdk/ShareSDKPlatforms/QQ (4.4.12):
- mob_sharesdk/ShareSDK
- MOBFoundation (>= 3.2.9)
- mob_sharesdk/ShareSDKPlatforms/WeChat_Lite (4.4.12):
- mob_sharesdk/ShareSDK
- MOBFoundation (>= 3.2.9)
- MOBFoundation (3.2.46)
- Protobuf (3.9.0)
- ReactiveObjC (3.1.1)
- SDAutoLayout (2.2.1)
- SDWebImage (5.12.5):
- SDWebImage/Core (= 5.12.5)
- SDWebImage/Core (5.12.5)
- SSZipArchive (2.4.3)
- SudMGP (1.4.0)
- SudMGPWrapper (1.4.0.1):
- MJExtension (~> 3.4.1)
- SudMGP
- SVGAPlayer (2.5.7):
- SVGAPlayer/Core (= 2.5.7)
- SVGAPlayer/ProtoFiles (= 2.5.7)
- SVGAPlayer/Core (2.5.7):
- SSZipArchive (>= 1.8.1)
- SVGAPlayer/ProtoFiles
- SVGAPlayer/ProtoFiles (2.5.7):
- Protobuf (~> 3.4)
- SVProgressHUD (2.2.5)
- TFPopup (1.4.4)
- TXIMSDK_Plus_iOS (7.1.3925)
- TZImagePickerController (3.8.8):
- TZImagePickerController/Basic (= 3.8.8)
- TZImagePickerController/Location (= 3.8.8)
- TZImagePickerController/Basic (3.8.8)
- TZImagePickerController/Location (3.8.8)
- WechatOpenSDK (2.0.4)
- YYCache (1.0.4)
- Zip (2.1.2)
DEPENDENCIES:
- AFNetworking/NSURLSession (~> 3.0.0)
- AFNetworking/Reachability (~> 3.0.0)
- AFNetworking/Security (~> 3.0.0)
- AFNetworking/Serialization (~> 3.0.0)
- AgoraLyricsScore
- AgoraRtcEngine_Special_iOS (~> 4.3.2)
- AgoraRtm_iOS
- AlipaySDK-iOS
- BMKLocationKit
- Bugly
- CL_ShanYanSDK
- CRBoxInputView (= 1.0.2)
- GVUserDefaults
- HWPopController
- IQKeyboardManager
- LLDebugTool
- Masonry
- MBProgressHUD (~> 1.0.0)
- MJExtension
- MJRefresh
- mob_sharesdk
- mob_sharesdk/ShareSDKPlatforms/QQ
- mob_sharesdk/ShareSDKPlatforms/WeChat_Lite
- Protobuf (= 3.9.0)
- ReactiveObjC
- SDAutoLayout
- SDWebImage
- SSZipArchive
- SudMGPWrapper (~> 1.4.0.1)
- SVGAPlayer
- SVProgressHUD
- TFPopup
- TXIMSDK_Plus_iOS
- TZImagePickerController
- WechatOpenSDK
- YYCache
SPEC REPOS:
https://github.com/CocoaPods/Specs:
- AFNetworking
- AgoraComponetLog
- AgoraLyricsScore
- AgoraRtcEngine_Special_iOS
- AgoraRtm_iOS
- AlipaySDK-iOS
- BMKLocationKit
- Bugly
- CL_ShanYanSDK
- CRBoxInputView
- FMDB
- GVUserDefaults
- HWPopController
- IQKeyboardManager
- LLDebugTool
- Masonry
- MBProgressHUD
- MJExtension
- MJRefresh
- mob_sharesdk
- MOBFoundation
- Protobuf
- ReactiveObjC
- SDAutoLayout
- SDWebImage
- SSZipArchive
- SudMGP
- SudMGPWrapper
- SVGAPlayer
- SVProgressHUD
- TFPopup
- TXIMSDK_Plus_iOS
- TZImagePickerController
- WechatOpenSDK
- YYCache
- Zip
SPEC CHECKSUMS:
AFNetworking: cacd04e21e78f4e11d6b7fb14bc8b6c7b8b24658
AgoraComponetLog: c52aec8db3ea38c5693fd4f1beee05ba7715e68b
AgoraLyricsScore: 7576387b199cdc3b2752a113688abd0a807a2ca3
AgoraRtcEngine_Special_iOS: 6c5df86608ab6f6cd09f5b4037d5432a039da7dc
AgoraRtm_iOS: 595a9fa33a409831e6183396ea8f8bc563918403
AlipaySDK-iOS: 913a1df564c64798903e71cf3d63141d9e1904d2
BMKLocationKit: 3b96beefb31c3b12d53e9156aa4ab19ecd695dec
Bugly: afe841bba2ea6de6d432a3c125240a5e75949c55
CL_ShanYanSDK: c30ff25cdae916616de88cfe964004780f0d948e
CRBoxInputView: 12a2b657801d757c176dc45a40a216ee07c5de95
FMDB: 728731dd336af3936ce00f91d9d8495f5718a0e6
GVUserDefaults: 52d48cf8ba578b40a1a76312b196dfc9134ba36a
HWPopController: 5602105c25252437adb37fbfc3111f10d846e890
IQKeyboardManager: 241cc94ccabc9deb8f8bd7d12f00d73288d13ecc
LLDebugTool: 6026a1df690f5f94524567fce7f97fa53ce131d8
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
MBProgressHUD: 4890f671c94e8a0f3cf959aa731e9de2f036d71a
MJExtension: 21c5f6f8c4d5d8844b7ae8fbae08fed0b501f961
MJRefresh: fdf5e979eb406a0341468932d1dfc8b7f9fce961
mob_sharesdk: 0f0508e54fc8c0bc00c448ab9b236d6fc9eee105
MOBFoundation: f913202e97a59c78d6e9695e6e359537add3360d
Protobuf: 1097ca58584c8d9be81bfbf2c5ff5975648dd87a
ReactiveObjC: 011caa393aa0383245f2dcf9bf02e86b80b36040
SDAutoLayout: 8bf6b3bbc8b01f775d4defbb4fda2ace805461be
SDWebImage: 0905f1b7760fc8ac4198cae0036600d67478751e
SSZipArchive: fe6a26b2a54d5a0890f2567b5cc6de5caa600aef
SudMGP: 780c36ec2468e41995d593b74801c9b08bfdf4d6
SudMGPWrapper: c5f794982d1a94cb18cf09fd155e5c2a3af3078a
SVGAPlayer: 318b85a78b61292d6ae9dfcd651f3f0d1cdadd86
SVProgressHUD: 1428aafac632c1f86f62aa4243ec12008d7a51d6
TFPopup: 5787d01ff90c5fc7fe19a991df1fb160c342529a
TXIMSDK_Plus_iOS: 3edf95acc3dff794287ea858b5205ed6f4dd339f
TZImagePickerController: d084a7b97c82d387e7669dd86dc9a9057500aacf
WechatOpenSDK: 290989072e87b79d52225a01bb4e5e58f6f88593
YYCache: 8105b6638f5e849296c71f331ff83891a4942952
Zip: b3fef584b147b6e582b2256a9815c897d60ddc67
PODFILE CHECKSUM: 905c5699da84201322e0b653cee0aceb422360f2
COCOAPODS: 1.16.2

View File

@@ -0,0 +1,295 @@
// AFHTTPSessionManager.h
// Copyright (c) 20112015 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>
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import "AFURLSessionManager.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.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
## 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: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 AFHTTPSessionManager : AFURLSessionManager <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) AFHTTPRequestSerializer <AFURLRequestSerialization> * 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) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
///---------------------
/// @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 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 *)GET:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
/**
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 progress 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
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 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
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 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 *)POST:(NSString *)URLString
parameters:(nullable id)parameters
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
/**
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 progress 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
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 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 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 *)POST:(NSString *)URLString
parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE;
/**
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 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 progress 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
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 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
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 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
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 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
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

@@ -0,0 +1,361 @@
// AFHTTPSessionManager.m
// Copyright (c) 20112015 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 "AFHTTPSessionManager.h"
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.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 AFHTTPSessionManager ()
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end
@implementation AFHTTPSessionManager
@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 = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
return self;
}
#pragma mark -
- (void)setRequestSerializer:(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[super setResponseSerializer:responseSerializer];
}
#pragma mark -
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
return [self GET:URLString parameters:parameters progress:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))downloadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET"
URLString:URLString
parameters:parameters
uploadProgress:nil
downloadProgress:downloadProgress
success:success
failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) {
if (success) {
success(task);
}
} failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
return [self POST:URLString parameters:parameters progress:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(nullable id)parameters
constructingBodyWithBlock:(nullable void (^)(id<AFMultipartFormData> _Nonnull))block
success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
{
return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
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:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
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) {
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
#else
configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
#endif
}
}
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy 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 {
AFHTTPSessionManager *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

@@ -0,0 +1,206 @@
// AFNetworkReachabilityManager.h
// Copyright (c) 20112015 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 AFNetworkReachabilityManager : 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;
///--------------------------------------------------
/// @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

@@ -0,0 +1,260 @@
// AFNetworkReachabilityManager.m
// Copyright (c) 20112015 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 "AFNetworkReachabilityManager.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);
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, AFNetworkReachabilityStatusBlock block) {
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
dispatch_async(dispatch_get_main_queue(), ^{
if (block) {
block(status);
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
[notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
});
}
static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info);
}
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
return Block_copy(info);
}
static void AFNetworkReachabilityReleaseCallback(const void *info) {
if (info) {
Block_release(info);
}
}
@interface AFNetworkReachabilityManager ()
@property (readwrite, nonatomic, strong) id networkReachability;
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
@end
@implementation AFNetworkReachabilityManager
+ (instancetype)sharedManager {
static AFNetworkReachabilityManager *_sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedManager = [self manager];
});
return _sharedManager;
}
#ifndef __clang_analyzer__
+ (instancetype)managerForDomain:(NSString *)domain {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
return manager;
}
#endif
#ifndef __clang_analyzer__
+ (instancetype)managerForAddress:(const void *)address {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
return manager;
}
#endif
+ (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;
}
self.networkReachability = CFBridgingRelease(reachability);
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
return self;
}
- (instancetype)init NS_UNAVAILABLE
{
return nil;
}
- (void)dealloc {
[self stopMonitoring];
}
#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;
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.networkReachabilityStatus = status;
if (strongSelf.networkReachabilityStatusBlock) {
strongSelf.networkReachabilityStatusBlock(status);
}
};
id networkReachability = self.networkReachability;
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback((__bridge SCNetworkReachabilityRef)networkReachability, AFNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop((__bridge SCNetworkReachabilityRef)networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags((__bridge SCNetworkReachabilityRef)networkReachability, &flags)) {
AFPostReachabilityStatusChange(flags, callback);
}
});
}
- (void)stopMonitoring {
if (!self.networkReachability) {
return;
}
SCNetworkReachabilityUnscheduleFromRunLoop((__bridge SCNetworkReachabilityRef)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

@@ -0,0 +1,154 @@
// AFSecurityPolicy.h
// Copyright (c) 20112015 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 AFSecurityPolicy : 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.
By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`.
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
*/
@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.
@param pinningMode The SSL pinning mode.
@return A new security policy.
*/
+ (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.
*/
+ (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

@@ -0,0 +1,353 @@
// AFSecurityPolicy.m
// Copyright (c) 20112015 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 "AFSecurityPolicy.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;
SecCertificateRef allowedCertificates[1];
CFArrayRef tempCertificates = nil;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out);
allowedCertificates[0] = allowedCertificate;
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
if (allowedTrust) {
CFRelease(allowedTrust);
}
if (policy) {
CFRelease(policy);
}
if (tempCertificates) {
CFRelease(tempCertificates);
}
if (allowedCertificate) {
CFRelease(allowedCertificate);
}
return allowedPublicKey;
}
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
BOOL isValid = NO;
SecTrustResultType result;
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
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;
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
[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 AFSecurityPolicy()
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
@end
@implementation AFSecurityPolicy
+ (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];
}
+ (NSSet *)defaultPinnedCertificates {
static NSSet *_defaultPinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
_defaultPinnedCertificates = [self certificatesInBundle:bundle];
});
return _defaultPinnedCertificates;
}
+ (instancetype)defaultPolicy {
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
return securityPolicy;
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
AFSecurityPolicy *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 (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return NO;
}
switch (self.SSLPinningMode) {
case AFSSLPinningModeNone:
default:
return NO;
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;
}
}
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:[NSArray 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 {
AFSecurityPolicy *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

@@ -0,0 +1,454 @@
// AFURLRequestSerialization.h
// Copyright (c) 20112015 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
/**
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 AFURLRequestSerialization <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 AFHTTPRequestSerializer : NSObject <AFURLRequestSerialization>
/**
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 * (^)(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.
*/
- (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 AFJSONRequestSerializer : AFHTTPRequestSerializer
/**
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 AFPropertyListRequestSerializer : AFHTTPRequestSerializer
/**
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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,311 @@
// AFURLResponseSerialization.h
// Copyright (c) 20112015 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
/**
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 AFURLResponseSerialization <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 AFHTTPResponseSerializer : NSObject <AFURLResponseSerialization>
- (instancetype)init;
/**
The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
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`
*/
@interface AFJSONResponseSerializer : AFHTTPResponseSerializer
- (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 AFXMLParserResponseSerializer : AFHTTPResponseSerializer
@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 AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
- (instancetype)init;
/**
Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `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 AFPropertyListResponseSerializer : AFHTTPResponseSerializer
- (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 AFImageResponseSerializer : AFHTTPResponseSerializer
#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 AFCompoundResponseSerializer : AFHTTPResponseSerializer
/**
The component response serializers.
*/
@property (readonly, nonatomic, copy) NSArray <id<AFURLResponseSerialization>> *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<AFURLResponseSerialization>> *)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

@@ -0,0 +1,828 @@
// AFURLResponseSerialization.m
// Copyright (c) 20112015 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 "AFURLResponseSerialization.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;
}
static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
[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 AFHTTPResponseSerializer
+ (instancetype)serializer {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = NSUTF8StringEncoding;
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 && [response isKindOfClass:[NSHTTPURLResponse class]]) {
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
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:[NSIndexSet 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 {
AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
return serializer;
}
@end
#pragma mark -
@implementation AFJSONResponseSerializer
+ (instancetype)serializer {
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
}
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
AFJSONResponseSerializer *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
NSStringEncoding stringEncoding = self.stringEncoding;
if (response.textEncodingName) {
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
}
id responseObject = nil;
NSError *serializationError = nil;
@autoreleasepool {
NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (responseString && ![responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
if (data) {
if ([data length] > 0) {
responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
} else {
return nil;
}
} else {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString]
};
serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
}
if (self.removesKeysWithNullValues && responseObject) {
responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
}
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return responseObject;
}
#pragma mark - NSSecureCoding
- (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 {
AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.readingOptions = self.readingOptions;
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
return serializer;
}
@end
#pragma mark -
@implementation AFXMLParserResponseSerializer
+ (instancetype)serializer {
AFXMLParserResponseSerializer *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 AFXMLDocumentResponseSerializer
+ (instancetype)serializer {
return [self serializerWithXMLDocumentOptions:0];
}
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
AFXMLDocumentResponseSerializer *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 (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
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 {
AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.options = self.options;
return serializer;
}
@end
#endif
#pragma mark -
@implementation AFPropertyListResponseSerializer
+ (instancetype)serializer {
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
}
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
readOptions:(NSPropertyListReadOptions)readOptions
{
AFPropertyListResponseSerializer *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;
}
}
id responseObject;
NSError *serializationError = nil;
if (data) {
responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
}
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return responseObject;
}
#pragma mark - NSSecureCoding
- (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 {
AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
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 AFImageResponseSerializer
- (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
- (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 {
AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
#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 AFCompoundResponseSerializer ()
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
@end
@implementation AFCompoundResponseSerializer
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
AFCompoundResponseSerializer *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 <AFURLResponseSerialization> serializer in self.responseSerializers) {
if (![serializer isKindOfClass:[AFHTTPResponseSerializer 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
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] 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 {
AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.responseSerializers = self.responseSerializers;
return serializer;
}
@end

View File

@@ -0,0 +1,499 @@
// AFURLSessionManager.h
// Copyright (c) 20112015 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 "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h"
#import "AFSecurityPolicy.h"
#if !TARGET_OS_WATCH
#import "AFNetworkReachabilityManager.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:didCompleteWithError:`
### `NSURLSessionDataDelegate`
- `URLSession:dataTask:didReceiveResponse:completionHandler:`
- `URLSession:dataTask:didBecomeDownloadTask:`
- `URLSession:dataTask:didReceiveData:`
- `URLSession:dataTask:willCacheResponse:completionHandler:`
### `NSURLSessionDownloadDelegate`
- `URLSession:downloadTask:didFinishDownloadingToURL:`
- `URLSession:downloadTask:didWriteData:totalBytesWritten: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 AFURLSessionManager : 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 <AFURLResponseSerialization> 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) AFSecurityPolicy *securityPolicy;
#if !TARGET_OS_WATCH
///--------------------------------------
/// @name Monitoring Network Reachability
///--------------------------------------
/**
The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *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 Working Around System Bugs
///---------------------------------
/**
Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
@bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again.
@see https://github.com/AFNetworking/AFNetworking/issues/1675
*/
@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
///---------------------
/// @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.
@param cancelPendingTasks Whether or not to cancel pending tasks.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
///-------------------------
/// @name Running Data Tasks
///-------------------------
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@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
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the 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 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 progress 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 progress 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 progress 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 progress 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 progress 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.
*/
- (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 * (^)(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 block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/
- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
/**
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;
///-------------------------------------------
/// @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;
///-----------------------------------------------
/// @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: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 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;
NS_ASSUME_NONNULL_END

File diff suppressed because it is too large Load Diff

19
Pods/AFNetworking/LICENSE generated Executable file
View File

@@ -0,0 +1,19 @@
Copyright (c) 20112015 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.

320
Pods/AFNetworking/README.md generated Executable file
View File

@@ -0,0 +1,320 @@
<p align="center" >
<img src="https://raw.github.com/AFNetworking/AFNetworking/assets/afnetworking-logo.png" alt="AFNetworking" title="AFNetworking">
</p>
[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking)
[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master)
[![Cocoapods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking)
[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking)
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
## How To Get Started
- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps
- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki)
- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking
- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0.
## Communication
- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking')
- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking).
- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue.
- If you **have a feature request**, open an issue.
- If you **want to contribute**, submit a pull request.
## Installation
AFNetworking supports multiple methods for installing the library in a project.
## Installation with CocoaPods
[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command:
```bash
$ gem install cocoapods
```
> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+.
#### Podfile
To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`:
```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
pod 'AFNetworking', '~> 3.0'
```
Then, run the following command:
```bash
$ pod install
```
### Installation with Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
You can install Carthage with [Homebrew](http://brew.sh/) using the following command:
```bash
$ brew update
$ brew install carthage
```
To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "AFNetworking/AFNetworking" ~> 3.0
```
Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project.
## Requirements
| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes |
|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:|
| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. |
| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. |
| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. |
| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a |
| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a |
(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)).
> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs.
## Architecture
### NSURLSession
- `AFURLSessionManager`
- `AFHTTPSessionManager`
### Serialization
* `<AFURLRequestSerialization>`
- `AFHTTPRequestSerializer`
- `AFJSONRequestSerializer`
- `AFPropertyListRequestSerializer`
* `<AFURLResponseSerialization>`
- `AFHTTPResponseSerializer`
- `AFJSONResponseSerializer`
- `AFXMLParserResponseSerializer`
- `AFXMLDocumentResponseSerializer` _(Mac OS X)_
- `AFPropertyListResponseSerializer`
- `AFImageResponseSerializer`
- `AFCompoundResponseSerializer`
### Additional Functionality
- `AFSecurityPolicy`
- `AFNetworkReachabilityManager`
## Usage
### AFURLSessionManager
`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
#### Creating a Download Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
```
#### Creating an Upload Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
```
#### Creating an Upload Task for a Multi-Part Request, with Progress
```objective-c
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
```
#### Creating a Data Task
```objective-c
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[dataTask resume];
```
---
### Request Serialization
Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
```objective-c
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
```
#### Query String Parameter Encoding
```objective-c
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
```
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
#### URL Form Parameter Encoding
```objective-c
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
```
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
#### JSON Parameter Encoding
```objective-c
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
```
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
---
### Network Reachability Manager
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
* Do not use Reachability to determine if the original request should be sent.
* You should try to send it.
* You can use Reachability to determine when a request should be automatically retried.
* Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something.
* Network reachability is a useful tool for determining why a request might have failed.
* After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out."
See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/).
#### Shared Network Reachability
```objective-c
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
```
---
### Security Policy
`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.
#### Allowing Invalid SSL Certificates
```objective-c
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production
```
---
## Unit Tests
AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test.
## Credits
AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org).
AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla).
AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/).
And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors).
### Security Disclosure
If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
## License
AFNetworking is released under the MIT license. See LICENSE for details.

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AvailableLibraries</key>
<array>
<dict>
<key>LibraryIdentifier</key>
<string>ios-arm64</string>
<key>LibraryPath</key>
<string>AgoraComponetLog.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
</dict>
<dict>
<key>LibraryIdentifier</key>
<string>ios-arm64_x86_64-simulator</string>
<key>LibraryPath</key>
<string>AgoraComponetLog.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
</dict>
</array>
<key>CFBundlePackageType</key>
<string>XFWK</string>
<key>XCFrameworkFormatVersion</key>
<string>1.0</string>
</dict>
</plist>

View File

@@ -0,0 +1,23 @@
//
// AgoraComponetConsoleLogger.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetConsoleLogger : NSObject <AgoraComponetLogger>
- (instancetype)initWithDomainName:(NSString *)domainName;
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,50 @@
//
// AgoraComponetFileLogger.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetFileLogger : NSObject <AgoraComponetLogger>
#pragma mark - public
/// init
/// - Parameters:
/// - logFilePath: custom file path, use default value if set nil
/// - filePrefixName: the prefixName of file, use default value if set nil
/// - maxFileSizeOfBytes: maxFileSize in every file
/// - maxFileCount: the number of file that save in local, no less than 2
/// - domainName: a flag of your domain
- (instancetype)initWithLogFilePath:(NSString * _Nullable)logFilePath
filePrefixName:(NSString * _Nullable)prefixName
maxFileSizeOfBytes:(uint64_t)maxFileSizeOfBytes
maxFileCount:(NSUInteger)maxFileCount
domainName:(NSString *)domainName;
- (instancetype)init __attribute__((unavailable("Use initWithLogFilePath instead")));
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
#pragma mark - only for unit test
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (NSString *)makeFilePathAtNum:(NSUInteger)num;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (uint64_t)fileSizeWithPath:(NSString *)path;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (NSString *)getDefaultFilePath;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (instancetype)initWithLogFilePath:(NSString * _Nullable)logFilePath
filePrefixName:(NSString * _Nullable)prefixName
maxFileSizeOfBytes:(uint64_t)maxFileSizeOfBytes
maxFileCount:(NSUInteger)maxFileCount
domainName:(NSString *)domainName
internalLogSaveInFile:(BOOL)internalLogSaveInFile;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,20 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "AgoraComponetLog.h"
#import "AgoraComponetConsoleLogger.h"
#import "AgoraComponetFileLogger.h"
#import "AgoraComponetLogProtocol.h"
FOUNDATION_EXPORT double AgoraComponetLogVersionNumber;
FOUNDATION_EXPORT const unsigned char AgoraComponetLogVersionString[];

View File

@@ -0,0 +1,21 @@
//
// EntLogger.h
//
//
// Created by ZYP on 2023/9/25.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetLog : NSObject
+ (void)setLoggers:(NSArray<id<AgoraComponetLogger>> *)loggers;
+ (void)errorWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)infoWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)debugWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)warningWithText:(NSString *)text tag:(NSString * _Nullable)tag;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,26 @@
//
// AgoraComponetLogProtocol.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, AgoraComponetLoggerLevel) {
AgoraComponetLoggerLevelDebug,
AgoraComponetLoggerLevelInfo,
AgoraComponetLoggerLevelWarning,
AgoraComponetLoggerLevelError
};
@protocol AgoraComponetLogger <NSObject>
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
framework module AgoraComponetLog {
umbrella header "AgoraComponetLog-umbrella.h"
export *
module * { export * }
}

View File

@@ -0,0 +1,23 @@
//
// AgoraComponetConsoleLogger.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetConsoleLogger : NSObject <AgoraComponetLogger>
- (instancetype)initWithDomainName:(NSString *)domainName;
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,50 @@
//
// AgoraComponetFileLogger.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetFileLogger : NSObject <AgoraComponetLogger>
#pragma mark - public
/// init
/// - Parameters:
/// - logFilePath: custom file path, use default value if set nil
/// - filePrefixName: the prefixName of file, use default value if set nil
/// - maxFileSizeOfBytes: maxFileSize in every file
/// - maxFileCount: the number of file that save in local, no less than 2
/// - domainName: a flag of your domain
- (instancetype)initWithLogFilePath:(NSString * _Nullable)logFilePath
filePrefixName:(NSString * _Nullable)prefixName
maxFileSizeOfBytes:(uint64_t)maxFileSizeOfBytes
maxFileCount:(NSUInteger)maxFileCount
domainName:(NSString *)domainName;
- (instancetype)init __attribute__((unavailable("Use initWithLogFilePath instead")));
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
#pragma mark - only for unit test
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (NSString *)makeFilePathAtNum:(NSUInteger)num;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (uint64_t)fileSizeWithPath:(NSString *)path;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (NSString *)getDefaultFilePath;
/// ⚠️⚠️⚠️⚠️⚠️ this method only for unit test ⚠️⚠️⚠️⚠️⚠️
- (instancetype)initWithLogFilePath:(NSString * _Nullable)logFilePath
filePrefixName:(NSString * _Nullable)prefixName
maxFileSizeOfBytes:(uint64_t)maxFileSizeOfBytes
maxFileCount:(NSUInteger)maxFileCount
domainName:(NSString *)domainName
internalLogSaveInFile:(BOOL)internalLogSaveInFile;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,20 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "AgoraComponetLog.h"
#import "AgoraComponetConsoleLogger.h"
#import "AgoraComponetFileLogger.h"
#import "AgoraComponetLogProtocol.h"
FOUNDATION_EXPORT double AgoraComponetLogVersionNumber;
FOUNDATION_EXPORT const unsigned char AgoraComponetLogVersionString[];

View File

@@ -0,0 +1,21 @@
//
// EntLogger.h
//
//
// Created by ZYP on 2023/9/25.
//
#import <Foundation/Foundation.h>
#import "AgoraComponetLogProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface AgoraComponetLog : NSObject
+ (void)setLoggers:(NSArray<id<AgoraComponetLogger>> *)loggers;
+ (void)errorWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)infoWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)debugWithText:(NSString *)text tag:(NSString * _Nullable)tag;
+ (void)warningWithText:(NSString *)text tag:(NSString * _Nullable)tag;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,26 @@
//
// AgoraComponetLogProtocol.h
// AgoraComponetLogger
//
// Created by ZYP on 2023/12/6.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, AgoraComponetLoggerLevel) {
AgoraComponetLoggerLevelDebug,
AgoraComponetLoggerLevelInfo,
AgoraComponetLoggerLevelWarning,
AgoraComponetLoggerLevelError
};
@protocol AgoraComponetLogger <NSObject>
- (void)onLogWithContent:(NSString *)content
tag:(NSString * _Nullable)tag
time:(NSString *)time
level:(AgoraComponetLoggerLevel)level;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
framework module AgoraComponetLog {
umbrella header "AgoraComponetLog-umbrella.h"
export *
module * { export * }
}

View File

@@ -0,0 +1,192 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Headers/AgoraComponetConsoleLogger.h</key>
<data>
rWMMF7eepKvq4bytD0A0pl+hjfY=
</data>
<key>Headers/AgoraComponetFileLogger.h</key>
<data>
XEllTj96Qxxd98QpgLO4fg+xcdg=
</data>
<key>Headers/AgoraComponetLog-umbrella.h</key>
<data>
DsJrrf72ovk303sNjCk12VG1yzg=
</data>
<key>Headers/AgoraComponetLog.h</key>
<data>
8KQgQ3gq9X7+wuy97utf2ZXQ9LE=
</data>
<key>Headers/AgoraComponetLogProtocol.h</key>
<data>
WRlVBe2axNlbSz5zB+QP3Vz/t8E=
</data>
<key>Info.plist</key>
<data>
e0phcUDXjOANLNnFRrS38Wpa0us=
</data>
<key>Modules/module.modulemap</key>
<data>
LXEG0x9oCt6dS9fRXxMReAo+Dic=
</data>
</dict>
<key>files2</key>
<dict>
<key>Headers/AgoraComponetConsoleLogger.h</key>
<dict>
<key>hash</key>
<data>
rWMMF7eepKvq4bytD0A0pl+hjfY=
</data>
<key>hash2</key>
<data>
xK8qgtogNRO14mrR1X5vVFCRODsBbRY8v0En3oWhiXg=
</data>
</dict>
<key>Headers/AgoraComponetFileLogger.h</key>
<dict>
<key>hash</key>
<data>
XEllTj96Qxxd98QpgLO4fg+xcdg=
</data>
<key>hash2</key>
<data>
/14HA3jVCgpKCoTpAa3UU3vmiyMxIA4SYf4Ofph4eug=
</data>
</dict>
<key>Headers/AgoraComponetLog-umbrella.h</key>
<dict>
<key>hash</key>
<data>
DsJrrf72ovk303sNjCk12VG1yzg=
</data>
<key>hash2</key>
<data>
fAYleJZkYsXpblpGj7OLpWnV6DHxr0tHUiWc63macTU=
</data>
</dict>
<key>Headers/AgoraComponetLog.h</key>
<dict>
<key>hash</key>
<data>
8KQgQ3gq9X7+wuy97utf2ZXQ9LE=
</data>
<key>hash2</key>
<data>
QsOLVqldhK2nYn9QOnsONSqOG001+uuYqY9deiFAUWQ=
</data>
</dict>
<key>Headers/AgoraComponetLogProtocol.h</key>
<dict>
<key>hash</key>
<data>
WRlVBe2axNlbSz5zB+QP3Vz/t8E=
</data>
<key>hash2</key>
<data>
WV2H+iP0zzAkCd5SBqs7JyV5Xvwq3+jnpj1idCNOI7g=
</data>
</dict>
<key>Modules/module.modulemap</key>
<dict>
<key>hash</key>
<data>
LXEG0x9oCt6dS9fRXxMReAo+Dic=
</data>
<key>hash2</key>
<data>
xME0ypa+p7dIZXpZwaBGW+qdbeafvhs/byLaPlhX5o8=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>

View File

@@ -0,0 +1,100 @@
//
// Algorithm.c
// AgoraLyricsScore
//
// Created by ZYP on 2023/11/9.
//
#include "Algorithm.h"
#import <math.h>
//modify by xuguangjian
#define PTS_version "20231021001"
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
double pitchToToneC(double pitch) {
double eps = 1e-6;
return (fmax(0, log(pitch / 55 + eps) / log(2))) * 12;
}
float calculedScoreC(double voicePitch, double stdPitch, int scoreLevel, int scoreCompensationOffset) {
if (voicePitch <= 0) {
return 0;
}
if(stdPitch <= 0){
return 0;
}
if(scoreLevel<=0){
scoreLevel = 1;
}else if(scoreLevel > 100){
scoreLevel = 100;
}
if(scoreCompensationOffset<0){
scoreCompensationOffset = 0;
}else if(scoreCompensationOffset > 100){
scoreCompensationOffset = 100;
}
double stdTone = pitchToToneC(stdPitch);
double voiceTone = pitchToToneC(voicePitch);
float match = 1 - (float)scoreLevel / 100 * fabs(voiceTone - stdTone) + (float)scoreCompensationOffset / 100;
float rate = 1 + ((float)scoreLevel/(float)50);
match = match * 100 * rate;
match = max(0, match);
match = min(100, match);
return match;
}
static double n;
static double offset;
// octave pitch compensation v0.2
double handlePitchC(double stdPitch, double voicePitch, double stdMaxPitch) {
int cnt = 0;
double stdTone = pitchToToneC(stdPitch);
double voiceTone = pitchToToneC(voicePitch);
if (voicePitch <= 0) {
return 0;
}
if(stdPitch <= 0){
return 0;
}
if(fabs(voiceTone - stdTone) <= 6){
return voicePitch;
}
else if(voicePitch < stdPitch){
for(cnt = 0; cnt <11; cnt++){
voicePitch = 2*voicePitch;
voiceTone = pitchToToneC(voicePitch);
if(fabs(voiceTone - stdTone) <= 6){
return voicePitch;
}
}
}
else if(voicePitch > stdPitch){
for(cnt = 0; cnt <11; cnt++){
voicePitch = voicePitch/2;
voiceTone = pitchToToneC(voicePitch);
if(fabs(voiceTone - stdTone) <= 6){
return voicePitch;
}
}
}
return voicePitch;
}
void resetC(void) {
offset = 0.0;
n = 0.0;
}

View File

@@ -0,0 +1,18 @@
//
// Algorithm.h
// AgoraLyricsScore
//
// Created by ZYP on 2023/11/9.
//
#ifndef Algorithm_h
#define Algorithm_h
#include <stdio.h>
double pitchToToneC(double pitch);
float calculedScoreC(double voicePitch, double stdPitch, int scoreLevel, int scoreCompensationOffset);
void resetC(void);
double handlePitchC(double stdPitch, double voicePitch, double stdMaxPitch);
#endif /* Algorithm_h */

View File

@@ -0,0 +1,154 @@
//
// Downloader.swift
// URLSessionDownloadDemo
//
// Created by FancyLou on 2019/2/22.
// Copyright © 2019 O2OA. All rights reserved.
//
import Foundation
import UIKit
typealias DownloadProgressClosure = ((_ progress:Float)->Void)
typealias DownloadCompletionClosure = ((_ filePath: String)->Void)
typealias DownloadFailClosure = ((_ error: DownloadError)-> Void)
class Downloader: NSObject {
private var fail: DownloadFailClosure?
private var completion: DownloadCompletionClosure?
private var progress: DownloadProgressClosure?
private var downloadUrl: URL?
private var localUrl: URL?
private var downloadSession: URLSession?
private var fileOutputStream: OutputStream?
private var downloadLoop: CFRunLoop?
private var currentLength: Float = 0.0
static var requestTimeoutInterval: TimeInterval = 60
private var logTag = "Downloader"
deinit {
Log.info(text: "deinit", tag: logTag)
if (downloadLoop != nil) {
CFRunLoopStop(downloadLoop)
}
}
override init() {
super.init()
Log.info(text: "init", tag: logTag)
}
//
func download(url: URL, progress: @escaping DownloadProgressClosure, completion: @escaping DownloadCompletionClosure, fail: @escaping DownloadFailClosure) {
logTag += "[\(url.lastPathComponent)]"
self.progress = progress
self.completion = completion
self.fail = fail
self.downloadUrl = url
guard self.downloadSession == nil else {
Log.errorText(text: "已经开始下载。。。。", tag: logTag)
return
}
DispatchQueue.global().async { [weak self] in
guard let self = self else {
return
}
var request = URLRequest(url: self.downloadUrl!)
request.httpMethod = "GET"
request.cachePolicy = .reloadIgnoringLocalCacheData
request.timeoutInterval = Downloader.requestTimeoutInterval
// session
downloadSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
//
let downloadTask = self.downloadSession?.dataTask(with: request)
//
downloadTask?.resume()
//
downloadLoop = CFRunLoopGetCurrent()
CFRunLoopRun()
}
}
//
func cancel() {
downloadSession?.invalidateAndCancel()
downloadSession = nil
fileOutputStream = nil
// 线
if (downloadLoop != nil) {
CFRunLoopStop(downloadLoop)
}
}
func resetEventCloure() {
fail = nil
completion = nil
progress = nil
}
}
extension Downloader: URLSessionDataDelegate {
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
Log.debug(text: "remote server start respone...", tag: logTag)
if let resp = response as? HTTPURLResponse, resp.statusCode != 200 {
Log.errorText(text: resp.description, tag: logTag)
let e = DownloadError(domainType: .httpDownloadErrorLogic, code: resp.statusCode, msg: "http error: \(resp.statusCode)")
Log.errorText(text: e.description, tag: logTag)
fail?(e)
fail = nil
completionHandler(.cancel)
cancel()
return
}
// file name of remote
let filename = dataTask.response?.suggestedFilename ?? "unKnownFileTitle.tmp"
let downloadFloderURL = NSURL(fileURLWithPath: String.downloadedFloderPath())
FileManager.createDirectoryIfNeeded(atPath: downloadFloderURL.path!)
localUrl = downloadFloderURL.appendingPathComponent(filename)
Log.debug(text: "local path\(self.localUrl?.path ?? "")", tag: logTag)
fileOutputStream = OutputStream(url: self.localUrl!, append: true)
fileOutputStream?.open()
completionHandler(.allow)
}
/// didReceive
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
Log.debug(text: "didReceive...", tag: logTag)
data.withUnsafeBytes { bufferPointer in
guard let baseAddress = bufferPointer.baseAddress else { return }
self.fileOutputStream?.write(baseAddress, maxLength: bufferPointer.count)
}
currentLength += Float(data.count)
// headerlength
let totalLength = Float(dataTask.response?.expectedContentLength ?? -1)
var progress = currentLength / totalLength
if totalLength<0 {
progress = 0.0
}
Log.info(text: "current: \(currentLength) , total:\(totalLength), progress:\(progress)", tag: logTag)
self.progress?(progress)
}
/// Complete
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
fileOutputStream?.close()
cancel()
if error != nil {
Log.errorText(text: "download fail: \(error!.localizedDescription)", tag: logTag)
let e = DownloadError(domainType: .httpDownloadError, error: error! as NSError)
fail?(e)
fail = nil
} else {
Log.info(text: "download success", tag: logTag)
completion?(self.localUrl?.path ?? "")
completion = nil
}
}
}

View File

@@ -0,0 +1,68 @@
//
// DownloaderManager.swift
// URLSessionDownloadDemo
//
// Created by FancyLou on 2019/2/22.
// Copyright © 2019 O2OA. All rights reserved.
//
import Foundation
class DownloaderManager: NSObject {
//
private var downloadCache = SafeDictionary<String, Downloader>()
private var failback: DownloadFailClosure?
private let logTag = "DownloaderManager"
deinit {
Log.info(text: "deinit", tag: logTag)
let downloadFloderURL = NSURL(fileURLWithPath: String.downloadedFloderPath())
FileManager.createDirectoryIfNeeded(atPath: downloadFloderURL.path!)
}
override init() {
Log.info(text: "init", tag: logTag)
}
func download(url: URL,
progress: @escaping DownloadProgressClosure,
completion: @escaping DownloadCompletionClosure,
fail: @escaping DownloadFailClosure) {
self.failback = fail
//
var downloader = downloadCache.getValue(forkey: url.absoluteString)
if downloader != nil {
Log.errorText(text: "当前下载已存在不需要重复下载!", tag: logTag)
let e = DownloadError(domainType: .repeatDownloading,
code: DownloadErrorDomainType.repeatDownloading.rawValue,
msg: "当前下载已存在不需要重复下载")
self.failback?(e)
return
}
downloader = Downloader()
downloadCache.set(value: downloader!, forkey: url.absoluteString)
downloader?.download(url: url, progress: progress, completion: { [weak self](filePath) in
guard let self = self else {
return
}
downloadCache.removeValue(forkey: url.absoluteString)
completion(filePath)
}, fail: fail)
}
func cancelTask(url: URL) {
let downloader = downloadCache.getValue(forkey: url.absoluteString)
if downloader == nil {
Log.debug(text: "任务已经移除,不需要重复移除!", tag: logTag)
return
}
//
downloadCache.removeValue(forkey: url.absoluteString)
//
downloader?.resetEventCloure()
downloader?.cancel()
}
}

View File

@@ -0,0 +1,64 @@
//
// AgoraStringExtention.swift
// AgoraKaraokeScore
//
// Created by zhaoyongqiang on 2021/12/10.
//
import UIKit
extension String {
//
func timeIntervalToMMSSFormat(interval: TimeInterval) -> String {
if interval >= 3600 {
let hour = interval / 3600
let min = interval.truncatingRemainder(dividingBy: 3600) / 60
let sec = interval.truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy: 60)
return String(format: "%02d:%02d:%02d", Int(hour), Int(min), Int(sec))
} else {
let min = interval / 60
let sec = interval.truncatingRemainder(dividingBy: 60)
return String(format: "%02d:%02d", Int(min), Int(sec))
}
}
/**
*
*/
static func cacheFolderPath() -> String {
return NSHomeDirectory().appending("/Library").appending("/MusicCaches").appending("/lyricFiles")
}
///
static func downloadedFloderPath() -> String {
return NSHomeDirectory().appending("/tmp").appending("/LyricDownloadFiles")
}
/**
*
*/
var fileName: String {
components(separatedBy: "/").last ?? ""
}
}
extension FileManager {
static func createDirectoryIfNeeded(atPath path: String) {
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: path, isDirectory: &isDirectory) {
if !isDirectory.boolValue {
Log.debug(text: "给定的路径是一个文件: \(path)", tag: "Downloader Extension")
return
}
Log.debug(text: "已存在:\(path)")
} else {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
Log.debug(text: "已成功创建目录: \(path)", tag: "Downloader Extension")
} catch {
Log.errorText(text: "创建目录失败: \(error.localizedDescription)", tag: "Downloader Extension")
}
}
}
}

View File

@@ -0,0 +1,138 @@
//
// FileCache.swift
// Demo
//
// Created by ZYP on 2023/2/7.
//
import Foundation
import Zip
class FileCache {
/// ()
var maxFileNum: UInt8 = 50 { didSet { removeFilesIfNeeded() } }
/// :s
var maxFileAge: UInt = 8 * 60 * 60 { didSet { removeFilesIfNeeded() } }
private let logTag = "FileCache"
init() {
Log.info(text: "init", tag: logTag)
let cacheFolderPathUrl = NSURL(fileURLWithPath: String.cacheFolderPath())
FileManager.createDirectoryIfNeeded(atPath: cacheFolderPathUrl.path!)
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
func removeFilesIfNeeded() {
let files = findFiles(inDirectory: String.cacheFolderPath())
let manager = FileManager.default
var hasFileBeRemove = false
var fileForMinCreationTime: ExistedFile?
let currentTime = Date().timeIntervalSince1970
for file in files { /** remove out date one **/
let gap = UInt(currentTime - file.createdTimeStamp)
let maxAge = UInt(maxFileAge)
if gap > maxAge {
do {
try manager.removeItem(atPath: file.path)
hasFileBeRemove = true
Log.debug(text: "did remove file: \(file.path)", tag: logTag)
} catch let error {
Log.error(error: "removeFilesIfNeed error \(error.localizedDescription)", tag: logTag)
}
}
else {
if let currentFileForMinCreationTime = fileForMinCreationTime {
fileForMinCreationTime = currentFileForMinCreationTime.createdTimeStamp <= file.createdTimeStamp ? currentFileForMinCreationTime : file
}
else {
fileForMinCreationTime = file
}
}
}
/// remove earliest one
if files.count > maxFileNum,
!hasFileBeRemove,
let currentFileForMinCreationTime = fileForMinCreationTime {
do {
try manager.removeItem(atPath: currentFileForMinCreationTime.path)
hasFileBeRemove = true
Log.debug(text: "did remove file: \(currentFileForMinCreationTime.path)", tag: logTag)
} catch let error {
Log.error(error: "removeFilesIfNeed 2 error \(error.localizedDescription)", tag: logTag)
}
}
}
func findFiles(inDirectory directoryPath: String) -> [ExistedFile] {
let fileManager = FileManager.default
guard let directoryURL = URL(string: directoryPath) else {
return []
}
var files: [ExistedFile] = []
do {
let directoryContents = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles])
for item in directoryContents {
if let creationDate = try item.resourceValues(forKeys: [.creationDateKey]).creationDate {
let file = ExistedFile(path: item.path, createdTimeStamp: creationDate.timeIntervalSince1970)
files.append(file)
}
}
} catch {
Log.error(error: "findXMLandLRCFiles: \(error)", tag: logTag)
}
return files
}
func clearAll() {
Log.debug(text: "clearAll start", tag: logTag)
let fileManager = FileManager.default
let files = findFiles(inDirectory: String.cacheFolderPath())
if files.isEmpty {
Log.debug(text: "no need to clear", tag: logTag)
return
}
do {
for file in files {
try fileManager.removeItem(atPath: file.path)
Log.debug(text: "rm \(file.path.fileName)", tag: logTag)
}
} catch let error {
Log.error(error: "clearAll: \(error)", tag: logTag)
}
Log.debug(text: "clearAll end", tag: logTag)
}
}
extension FileCache {
/**
* nil
*/
static func cacheFileExists(with url: String) -> String? {
let cacheFilePath = "\(String.cacheFolderPath())/\(url.fileName)"
if FileManager.default.fileExists(atPath: cacheFilePath) {
return cacheFilePath
}
return nil
}
/**
*
*/
static func clearCache() -> Bool? {
let manager = FileManager.default
if let _ = try? manager.removeItem(atPath: String.cacheFolderPath()) {
return true
}
return false
}
struct ExistedFile {
let path: String
let createdTimeStamp: Double
}
}

View File

@@ -0,0 +1,15 @@
//
// LyricsFileDownloader+Info.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/12/14.
//
import Foundation
extension LyricsFileDownloader {
struct TaskInfo {
let requestId: Int
let urlString: String
}
}

View File

@@ -0,0 +1,365 @@
//
// LyricsFileDownloader.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/12/13.
//
import Foundation
import Zip
public class LyricsFileDownloader: NSObject {
typealias RequestId = Int
/// max number of file in local (if reach max, sdk will remove oldest file)
@objc public var maxFileNum: UInt8 = 50 { didSet { fileCache.maxFileNum = maxFileNum } }
/// age of file (seconds), default is 8 hours
@objc public var maxFileAge: UInt = 8 * 60 * 60 { didSet { fileCache.maxFileAge = maxFileAge } }
@objc public weak var delegate: LyricsFileDownloaderDelegate?
@objc public var delegateQueue = DispatchQueue.main
private let fileCache = FileCache()
private let downloaderManager = DownloaderManager()
private let queue = DispatchQueue(label: "com.agora.LyricsFileDownloader.queue")
private var requestIdDict = [RequestId : String]()
private var currentRequestId: RequestId = 0
private let maxConcurrentRequestCount = 3
private var waittingTaskQueue = Queue<TaskInfo>()
private let logTag = "LyricsFileDownloader"
// MARK: - Public Method
public override init() {
Log.info(text: "init", tag: logTag)
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
/// start a download
/// - Parameters:
/// - urlString: url from result of `AgoraMusicContentCenter`
/// - Returns: `requestId`, if rseult < 0, means fail, such as -1 means urlString not valid. if rseult >= 0, means success
@objc public func download(urlString: String) -> Int {
guard isValidURL(urlString: urlString) else {
return -1
}
let requestId = genId()
Log.info(text: "download: \(requestId)", tag: logTag)
/// remove file outdate
fileCache.removeFilesIfNeeded()
/** check file Exist **/
if let fileData = fetchFromLocal(urlString: urlString) {
queue.async { [weak self] in
guard let self = self else {
return
}
invokeOnLyricsFileDownloadCompleted(requestId: requestId,
fileData: fileData,
error: nil)
}
return requestId
}
/** start download **/
queue.async { [weak self] in
guard let self = self else {
return
}
Log.info(text: "requestId:\(requestId) start work", tag: logTag)
if requestIdDict.count >= maxConcurrentRequestCount {
let logText = "request(\(requestId) was enqueued in waittingTaskQueue, current num of requesting task is \(requestIdDict.count)"
Log.info(text: logText, tag: logTag)
let taskInfo = TaskInfo(requestId: requestId, urlString: urlString)
waittingTaskQueue.enqueue(taskInfo)
}
else {
_addRequest(id: requestId, urlString: urlString)
_startDownload(requestId: requestId, urlString: urlString)
}
}
return requestId
}
/// cancel a downloading task
@objc public func cancelDownload(requestId: Int) {
Log.info(text: "cancelDownload: \(requestId)", tag: logTag)
queue.async { [weak self] in
guard let self = self else {
return
}
_cancelDownload(requestId: requestId)
_resumeTaskIfNeeded()
}
}
/// clean all files in local
@objc public func cleanAll() {
_cleanAll()
}
// MARK: - Private Method - 0
func fetchFromLocal(urlString: String) -> Data? {
/** check if Exist **/
let fileName = urlString.fileName.components(separatedBy: ".").first ?? ""
if let xmlPath = FileCache.cacheFileExists(with: fileName + ".xml") {
let url = URL(fileURLWithPath: xmlPath)
let data = try? Data(contentsOf: url)
return data
}
return nil
}
func _startDownload(requestId: Int, urlString: String) {
Log.debug(text: "_startDownload requestId:\(requestId)", tag: logTag)
guard let url = URL(string: urlString) else {
_removeRequest(id: requestId)
_resumeTaskIfNeeded()
return
}
downloaderManager.download(url: url) { [weak self](progress) in
guard let self = self else {
return
}
invokeOnLyricsFileDownloadProgress(requestId: requestId, progress: progress)
} completion: { [weak self](filePath) in
guard let self = self else {
return
}
if filePath.split(separator: ".").last == "lrc" { /** lrc type **/
let url = URL(fileURLWithPath: filePath)
var data: Data?
do {
data = try Data(contentsOf: url)
removeRequest(id: requestId)
resumeTaskIfNeeded()
} catch let error {
let logText = "get data from [\(url.path)] failed: \(error.localizedDescription)"
Log.errorText(text: logText, tag: logTag)
let e = DownloadError(domainType: .general, error: error as NSError)
invokeOnLyricsFileDownloadCompleted(requestId: requestId,
fileData: nil,
error: e)
}
do {
FileManager.createDirectoryIfNeeded(atPath: .cacheFolderPath())
if FileManager.default.fileExists(atPath: filePath) {
Log.debug(text: "file exist: \(filePath)")
}
try FileManager.default.copyItem(atPath: filePath, toPath: .cacheFolderPath() + "/" + url.lastPathComponent)
Log.debug(text: "ready to removeItem: \(filePath)")
try FileManager.default.removeItem(atPath: filePath)
} catch let error {
let logText = "get data from [\(url.path)] failed: \(error.localizedDescription)"
Log.errorText(text: logText, tag: logTag)
}
invokeOnLyricsFileDownloadCompleted(requestId: requestId,
fileData: data,
error: nil)
return
}
/** xml type **/
unzip(filePath: filePath, requestId: requestId)
} fail: { [weak self](error) in
guard let self = self else {
return
}
removeRequest(id: requestId)
resumeTaskIfNeeded()
invokeOnLyricsFileDownloadCompleted(requestId: requestId, fileData: nil, error: error)
}
}
func _cancelDownload(requestId: Int) {
if let urlString = requestIdDict[requestId] {
guard let url = URL(string: urlString) else {
Log.errorText(text: "\(urlString) is not valid url", tag: logTag)
return
}
Log.info(text: "_cancelDownload in current request: \(requestId)", tag: logTag)
_removeRequest(id: requestId)
downloaderManager.cancelTask(url: url)
}
else {
_removeWaittingTaskIfNeeded(requestId: requestId)
}
}
func _cleanAll() {
fileCache.clearAll()
_clearDownloadFloder()
}
// MARK: - Private Method
private func unzip(filePath: String, requestId: Int) {
queue.async { [weak self] in
guard let self = self else {
return
}
_unzip(filePath: filePath, requestId: requestId)
}
}
private func _unzip(filePath: String, requestId: Int) {
let fileName = filePath.fileName.components(separatedBy: ".").first ?? ""
let zipFile = URL(fileURLWithPath: filePath)
let destination = URL(fileURLWithPath: .cacheFolderPath())
do {
try Zip.unzipFile(zipFile, destination: destination, overwrite: true, password: nil)
let path = destination.path + "/" + fileName + ".xml"
let url = URL(fileURLWithPath: path)
let data = try Data(contentsOf: url)
removeRequest(id: requestId)
resumeTaskIfNeeded()
invokeOnLyricsFileDownloadCompleted(requestId: requestId,
fileData: data,
error: nil)
} catch let error {
removeRequest(id: requestId)
resumeTaskIfNeeded()
let e = DownloadError(domainType: .unzipFail,
code: DownloadErrorDomainType.unzipFail.rawValue,
msg: error.localizedDescription)
invokeOnLyricsFileDownloadCompleted(requestId: requestId,
fileData: nil,
error: e)
}
}
private func genId() -> RequestId {
let id = currentRequestId
currentRequestId = currentRequestId == Int.max ? 0 : currentRequestId + 1
return id
}
private func addRequest(id: RequestId, urlString: String) {
queue.async { [weak self] in
guard let self = self else {
return
}
_addRequest(id: id, urlString: urlString)
}
}
private func removeRequest(id: RequestId) {
queue.async { [weak self] in
guard let self = self else {
return
}
_removeRequest(id: id)
}
}
private func _addRequest(id: RequestId, urlString: String) {
requestIdDict[id] = urlString
}
private func _removeRequest(id: RequestId) {
requestIdDict.removeValue(forKey: id)
}
private func resumeTaskIfNeeded() {
queue.async { [weak self] in
guard let self = self else {
return
}
_resumeTaskIfNeeded()
}
}
private func _resumeTaskIfNeeded() {
Log.debug(text: "_resumeTaskIfNeeded", tag: logTag)
if requestIdDict.count >= maxConcurrentRequestCount {
return
}
if let taskInfo = waittingTaskQueue.dequeue() {
Log.info(text: "task was resume, requestId: \(taskInfo.requestId)", tag: logTag)
_addRequest(id: taskInfo.requestId, urlString: taskInfo.urlString)
_startDownload(requestId: taskInfo.requestId, urlString: taskInfo.urlString)
}
}
private func _removeWaittingTaskIfNeeded(requestId: Int) {
Log.debug(text: "_removeWaittingTaskIfNeeded \(requestId)", tag: logTag)
var tasks = waittingTaskQueue.getAll()
let contain = tasks.contains(where: { $0.requestId == requestId })
if contain {
tasks = tasks.filter({ requestId != $0.requestId })
waittingTaskQueue.reset(newElements: tasks)
Log.debug(text: "task (id:\(requestId)) was remove in waitting tasks ", tag: logTag)
}
else {
Log.debug(text: "no task (id:\(requestId)) was should be remove in waitting tasks", tag: logTag)
}
}
private func _clearDownloadFloder() {
Log.debug(text: "[DownloadFloder]clearDownloadFloder", tag: logTag)
guard let directoryURL = URL(string: String.downloadedFloderPath()) else {
return
}
let fileManager = FileManager.default
do {
let directoryContents = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles])
for url in directoryContents {
try fileManager.removeItem(atPath: url.path)
Log.debug(text: "[DownloadFloder]rm \(url.path.fileName)", tag: logTag)
}
} catch let error {
Log.error(error: "[DownloadFloder]clearAll: \(error)", tag: logTag)
}
Log.debug(text: "[DownloadFloder]clearAll end", tag: logTag)
}
private func isValidURL(urlString: String) -> Bool {
if urlString.isEmpty {
return false
}
return urlString.hasPrefix("http://") || urlString.hasPrefix("https://")
}
}
// MARK: - Invoke
extension LyricsFileDownloader {
fileprivate func invokeOnLyricsFileDownloadCompleted(requestId: Int,
fileData: Data?,
error: DownloadError?) {
/** check local file **/
fileCache.removeFilesIfNeeded()
Log.debug(text: "invokeOnLyricsFileDownloadCompleted requestId:\(requestId) isSuccess:\(error == nil)", tag: logTag)
if Thread.isMainThread {
delegate?.onLyricsFileDownloadCompleted(requestId: requestId,
fileData: fileData,
error: error)
return
}
delegateQueue.async { [weak self] in
self?.delegate?.onLyricsFileDownloadCompleted(requestId: requestId,
fileData: fileData,
error: error)
}
}
fileprivate func invokeOnLyricsFileDownloadProgress(requestId: Int, progress: Float) {
if Thread.isMainThread {
delegate?.onLyricsFileDownloadProgress(requestId: requestId, progress: progress)
return
}
delegateQueue.async { [weak self] in
self?.delegate?.onLyricsFileDownloadProgress(requestId: requestId, progress: progress)
}
}
}

View File

@@ -0,0 +1,97 @@
//
// LyricsFileDownloaderProtocol.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/12/13.
//
import Foundation
/// the enum type to describe the error
@objc public enum DownloadErrorDomainType: Int {
case general = 0
/// repeat url request, a same url is requesting
case repeatDownloading = 1
/// error from http framework in ios, such as time out
case httpDownloadError = 2
/// http logic error, such as 400/500
case httpDownloadErrorLogic = 3
/// unzip fail
case unzipFail = 4
/// the string to indicate the type
public var domain: String {
switch self {
case .general:
return "io.agora.LyricsFileDownloader.general"
case .repeatDownloading:
return "io.agora.LyricsFileDownloader.repeatDownloading"
case .httpDownloadError:
return "io.agora.LyricsFileDownloader.httpDownloadError"
case .httpDownloadErrorLogic:
return "io.agora.LyricsFileDownloader.httpDownloadErrorLogic"
case .unzipFail:
return "io.agora.LyricsFileDownloader.unzipFail"
}
}
/// the name to describe the type
public var name: String {
switch self {
case .general:
return "general"
case .repeatDownloading:
return "repeatDownloading"
case .httpDownloadError:
return "httpDownloadError"
case .httpDownloadErrorLogic:
return "httpDownloadErrorLogic"
case .unzipFail:
return "unzipFail"
}
}
}
/// the class to describe the error
public class DownloadError: NSError {
/// the message to describe the error
public let msg: String
/// the type of different error
public let domainType: DownloadErrorDomainType
/// original error from http framework in ios, such as time out
public var originalError: NSError?
init(domainType: DownloadErrorDomainType, code: Int, msg: String) {
self.domainType = domainType
self.msg = msg
super.init(domain: domainType.domain, code: code)
}
init(domainType: DownloadErrorDomainType, error: NSError) {
self.domainType = domainType
self.msg = error.localizedDescription
self.originalError = error
super.init(domain: domainType.domain, code: error.code)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var description: String {
return "error: \(domainType.name) domain: \(domain) code:\(code) msg:\(msg) originalError:\(originalError?.localizedDescription ?? "nil")"
}
}
@objc public protocol LyricsFileDownloaderDelegate: NSObjectProtocol {
/// progress event
/// - Parameters:
/// - progress: [0, 1], if equal `1`, means success
func onLyricsFileDownloadProgress(requestId: Int, progress: Float)
/// Completed event
/// - Parameters:
/// - fileData: lyric data from file, if `nil` means fail
/// - error: if `nil` means success
func onLyricsFileDownloadCompleted(requestId: Int, fileData: Data?, error: DownloadError?)
}

View File

@@ -0,0 +1,71 @@
//
// Events.swift
// NewApi
//
// Created by ZYP on 2022/11/22.
//
import Foundation
@objc public protocol KaraokeDelegate: NSObjectProtocol {
///
/// - Note: `KaraokeConfig.lyricConfig.draggable == true`
/// - Parameters:
/// - view: KaraokeView
/// - position: (ms)
@objc optional func onKaraokeView(view: KaraokeView, didDragTo position: Int)
/// (Line)
/// - Parameters:
/// - model:
/// - score: [0, 100]
/// - cumulativeScore:
/// - lineIndex: 0
/// - lineCount:
@objc optional func onKaraokeView(view: KaraokeView,
didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int)
}
///
@objc public protocol IScoreAlgorithm {
// MARK: -
/// (Line)
/// - Parameters:
/// - models:
/// - Returns: [0, 100]
@objc func getLineScore(with toneScores: [ToneScoreModel]) -> Int
}
///
@objc public protocol ILogger {
///
/// - Note: 线
/// - Parameters:
/// - content:
/// - tag:
/// - time:
/// - level:
@objc func onLog(content: String, tag: String?, time: String, level: LoggerLevel)
}
@objc public enum LoggerLevel: UInt8, CustomStringConvertible {
case debug, info, warning, error
public var description: String {
switch self {
case .debug:
return "D"
case .info:
return "I"
case .warning:
return "W"
case .error:
return "E"
}
}
}

View File

@@ -0,0 +1,319 @@
//
// KaraokeView.swift
// NewApi
//
// Created by ZYP on 2022/11/22.
//
import UIKit
public class KaraokeView: UIView {
///
@objc public var backgroundImage: UIImage? = nil {
didSet { updateUI() }
}
/// 使
/// - Note: `false`,
@objc public var scoringEnabled: Bool = true {
didSet { updateUI() }
}
/// : 0
@objc public var spacing: CGFloat = 0 {
didSet { updateUI() }
}
@objc public weak var delegate: KaraokeDelegate?
@objc public let lyricsView = LyricsView()
@objc public let scoringView = ScoringView()
fileprivate let backgroundImageView = UIImageView()
fileprivate var lyricsViewTopConstraint: NSLayoutConstraint!
fileprivate var scoringViewHeightConstraint, scoringViewTopConstraint: NSLayoutConstraint!
fileprivate var lyricData: LyricModel?
fileprivate let progressChecker = ProgressChecker()
fileprivate var pitchIsZeroCount = 0
fileprivate var isStart = false
fileprivate let logTag = "KaraokeView"
/// use for debug
fileprivate var lastProgress = 0
fileprivate var progressPrintCount = 0
fileprivate var progressPrintCountMax = 80
/// init
/// - !!! Only one init method
/// - Note: can set custom logger
/// - Note: use for Objective-C. `[[KaraokeView alloc] initWithFrame:frame loggers:@[[ConsoleLogger new], [FileLogger new]]]`
/// - Note: use for Swift. `KaraokeView(frame: frame)`
/// - Parameters:
/// - logger: custom logger
@objc public convenience init(frame: CGRect, loggers: [ILogger] = [FileLogger(), ConsoleLogger()]) {
Log.setLoggers(loggers: loggers)
self.init(frame: frame)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Not Public, Please use `init(frame, loggers)`
override init(frame: CGRect) {
super.init(frame: frame)
Log.debug(text: "version \(versionName)", tag: logTag)
setupUI()
commonInit()
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
}
// MARK: - Public Method
extension KaraokeView {
/// xml
/// - Parameter data: xml
/// - Returns:
@objc public static func parseLyricData(data: Data) -> LyricModel? {
let parser = Parser()
return parser.parseLyricData(data: data)
}
///
/// - Parameter data: `parseLyricData(data: Data)` . , `nil`.
@objc public func setLyricData(data: LyricModel?) {
Log.info(text: "setLyricData \(data?.name ?? "nil")", tag: logTag)
if !Thread.isMainThread {
Log.error(error: "invoke setLyricData not isMainThread ", tag: logTag)
}
/** Fix incorrect value of tableView.Height in lyricsView, after update scoringView.height/topSpace **/
layoutIfNeeded()
lyricData = data
/** **/
if data == nil {
scoringEnabled = false
}
lyricsView.setLyricData(data: data)
scoringView.setLyricData(data: data)
isStart = true
}
/// ,
@objc public func reset() {
Log.info(text: "reset", tag: logTag)
if !Thread.isMainThread {
Log.error(error: "invoke reset not isMainThread ", tag: logTag)
}
progressChecker.reset()
isStart = false
pitchIsZeroCount = 0
lastProgress = 0
progressPrintCount = 0
lyricsView.reset()
scoringView.reset()
}
/// (mic)Pitch
/// - Note: AgoraRTC `- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine reportAudioVolumeIndicationOfSpeakers:(NSArray<AgoraRtcAudioVolumeInfo *> * _Nonnull)speakers totalVolume:(NSInteger)totalVolume`
/// - Parameter pitch:
@objc public func setPitch(pitch: Double) {
Log.info(text: "p:\(pitch)", tag: logTag)
if !Thread.isMainThread {
Log.error(error: "invoke setPitch not isMainThread ", tag: logTag)
}
if pitch < 0 { return }
guard isStart else { return }
if pitch == 0 {
pitchIsZeroCount += 1
}
else {
pitchIsZeroCount = 0
}
if pitch > 0 || pitchIsZeroCount >= 10 { /** 100* **/
pitchIsZeroCount = 0
scoringView.setPitch(pitch: pitch)
}
}
///
/// - Note:
/// - Parameter progress: (ms)
@objc public func setProgress(progress: Int) {
if !Thread.isMainThread {
Log.error(error: "invoke setProgress not isMainThread ", tag: logTag)
}
guard isStart else { return }
logProgressIfNeed(progress: progress)
lyricsView.setProgress(progress: progress)
scoringView.progress = progress
progressChecker.set(progress: progress)
}
/// Pitch (使)
/// - Parameters:
/// - pitch:
/// - progress: (ms)
@objc public func setPitch(pitch: Double, progress: Int) {
if !Thread.isMainThread {
Log.error(error: "invoke setPitch(pitch, progress) not isMainThread ", tag: logTag)
}
setProgress(progress: progress)
setPitch(pitch: pitch)
}
///
/// - Note: 使
/// - Parameter algorithm: `IScoreAlgorithm`
@objc public func setScoreAlgorithm(algorithm: IScoreAlgorithm) {
if !Thread.isMainThread {
Log.error(error: "invoke setScoreAlgorithm not isMainThread ", tag: logTag)
}
scoringView.setScoreAlgorithm(algorithm: algorithm)
}
/// ()
/// - Note:
/// - Parameter level: , [0, 100], 15
@objc public func setScoreLevel(level: Int) {
if !Thread.isMainThread {
Log.error(error: "invoke setScoreLevel not isMainThread ", tag: logTag)
}
if level < 0 || level > 100 {
Log.error(error: "setScoreLevel out bounds \(level), [0, 100]", tag: logTag)
return
}
scoringView.scoreLevel = level
}
///
/// - Note:
/// - Parameter offset: [-100, 100], 0
@objc public func setScoreCompensationOffset(offset: Int) {
if !Thread.isMainThread {
Log.error(error: "invoke setScoreCompensationOffset not isMainThread ", tag: logTag)
}
if offset < -100 || offset > 100 {
Log.error(error: "setScoreCompensationOffset out bounds \(offset), [-100, 100]", tag: logTag)
return
}
scoringView.scoreCompensationOffset = offset
}
}
// MARK: - UI
extension KaraokeView {
fileprivate func setupUI() {
scoringView.backgroundColor = .clear
lyricsView.backgroundColor = .clear
backgroundImageView.isHidden = true
addSubview(backgroundImageView)
addSubview(scoringView)
addSubview(lyricsView)
scoringView.translatesAutoresizingMaskIntoConstraints = false
lyricsView.translatesAutoresizingMaskIntoConstraints = false
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
scoringView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
scoringView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
scoringViewHeightConstraint = scoringView.heightAnchor.constraint(equalToConstant: scoringView.viewHeight)
scoringViewHeightConstraint.isActive = true
scoringViewTopConstraint = scoringView.topAnchor.constraint(equalTo: topAnchor, constant: scoringView.topSpaces)
scoringViewTopConstraint.isActive = true
lyricsView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
lyricsView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
lyricsViewTopConstraint = lyricsView.topAnchor.constraint(equalTo: scoringView.bottomAnchor, constant: spacing)
lyricsViewTopConstraint.isActive = true
lyricsView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
backgroundImageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
backgroundImageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
backgroundImageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
backgroundImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
fileprivate func commonInit() {
lyricsView.delegate = self
scoringView.delegate = self
progressChecker.delegate = self
}
fileprivate func updateUI() {
backgroundImageView.image = backgroundImage
backgroundImageView.isHidden = backgroundImage == nil
lyricsViewTopConstraint.constant = scoringEnabled ? spacing : 0 - scoringView.viewHeight
scoringViewHeightConstraint.constant = scoringView.viewHeight
scoringView.isHidden = !scoringEnabled
scoringViewTopConstraint.constant = scoringView.topSpaces
}
fileprivate var versionName: String {
guard let version = Bundle.currentBundle.infoDictionary?["CFBundleShortVersionString"] as? String else {
return "unknow version"
}
return version
}
}
// MARK: - ProgressCheckerDelegate
extension KaraokeView: LyricsViewDelegate {
func onLyricsViewBegainDrag(view: LyricsView) {
scoringView.dragBegain()
}
func onLyricsView(view: LyricsView, didDragTo position: Int) {
Log.debug(text: "=== didDragTo \(position)", tag: "drag")
scoringView.dragDidEnd(position: position)
delegate?.onKaraokeView?(view: self, didDragTo: position)
}
}
// MARK: - ProgressCheckerDelegate
extension KaraokeView: ScoringViewDelegate {
func scoringViewShouldUpdateViewLayout(view: ScoringView) {
updateUI()
}
func scoringView(_ view: ScoringView,
didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int) {
Log.info(text: "didFinishLineWith score:\(score) lineIndex:\(lineIndex) lineCount:\(lineCount) cumulativeScore:\(cumulativeScore)", tag: logTag)
delegate?.onKaraokeView?(view: self,
didFinishLineWith: model,
score: score,
cumulativeScore: cumulativeScore,
lineIndex: lineIndex,
lineCount: lineCount)
}
}
extension KaraokeView: ProgressCheckerDelegate {
func progressCheckerDidProgressPause() {
Log.debug(text: "progressCheckerDidProgressPause", tag: logTag)
scoringView.forceStopIndicatorAnimationWhenReachingContinuousZeros()
}
}
// MARK: -- Log
extension KaraokeView {
func logProgressIfNeed(progress: Int) {
let gap = progress - lastProgress
if progressPrintCount < progressPrintCountMax, gap > 20 {
let text = "setProgress:\(progress) last:\(lastProgress) gap:\(progress-lastProgress)"
Log.warning(text: text, tag: logTag)
progressPrintCount += 1
}
lastProgress = progress
}
}

View File

@@ -0,0 +1,118 @@
//
// FirstToneHintView.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/22.
//
import UIKit
public class FirstToneHintViewStyle: NSObject {
///
@objc public var backgroundColor: UIColor = .gray { didSet { didUpdate?() } }
///
@objc public var size: CGFloat = 10 { didSet { didUpdate?() } }
///
@objc public var bottomMargin: CGFloat = 0 { didSet { didUpdate?() } }
typealias VoidBlock = () -> Void
var didUpdate: VoidBlock?
}
class FirstToneHintView: UIView {
var style = FirstToneHintViewStyle() { didSet { updateUI() } }
var mustHidden = false
private let loadViews: [UIView] = [.init(), .init(), .init()]
private var loadViewConstraints = [NSLayoutConstraint]()
/// ms
private var remainingTime = 0
private var lastRemainingTime = 0
fileprivate let logTag = "FirstToneHintView"
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
for view in loadViews {
view.backgroundColor = style.backgroundColor
view.layer.cornerRadius = style.size / 2
view.layer.masksToBounds = true
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = view.widthAnchor.constraint(equalToConstant: style.size)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: style.size)
widthConstraint.isActive = true
heightConstraint.isActive = true
loadViewConstraints.append(widthConstraint)
loadViewConstraints.append(heightConstraint)
}
loadViews[1].centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
loadViews[1].centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
loadViews[0].leftAnchor.constraint(equalTo: loadViews[1].rightAnchor, constant: 10).isActive = true
loadViews[0].centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
loadViews[2].rightAnchor.constraint(equalTo: loadViews[1].leftAnchor, constant: -10).isActive = true
loadViews[2].centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
isHidden = true
}
private func updateUI() {
for view in loadViews {
view.backgroundColor = style.backgroundColor
view.layer.cornerRadius = style.size / 2
}
for constraint in loadViewConstraints {
constraint.constant = style.size
}
}
func updateStyle(style: FirstToneHintViewStyle) {
self.style = style
updateUI()
}
/// -
/// - Parameter time:
func setRemainingTime(time: Int) {
if time < 0 {
reset()
return
}
/** 500ms **/
if lastRemainingTime == 0 {
lastRemainingTime = time
}
if lastRemainingTime - time < 500 {
return
}
lastRemainingTime = time
remainingTime = time
Log.info(text: "remainingTime: \(remainingTime)", tag: logTag)
loadViews[0].isHidden = (remainingTime >= 3 * 1000) ? !loadViews[0].isHidden : true
loadViews[1].isHidden = !(remainingTime >= 2 * 1000)
loadViews[2].isHidden = !(remainingTime >= 1 * 1000)
}
func reset() {
isHidden = true
self.loadViews[0].isHidden = false
self.loadViews[1].isHidden = false
self.loadViews[2].isHidden = false
lastRemainingTime = 0
remainingTime = 0
}
}

View File

@@ -0,0 +1,188 @@
//
// LyricsCell.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/23.
//
import UIKit
class LyricCell: UITableViewCell {
private let label = LyricLabel()
///
var textNormalColor: UIColor = .gray {
didSet { updateUI() }
}
///
var textSelectedColor: UIColor = .white {
didSet { updateUI() }
}
///
var textHighlightedColor: UIColor = .colorWithHex(hexStr: "#FF8AB4") {
didSet { updateUI() }
}
///
var textNormalFontSize: UIFont = .systemFont(ofSize: 15) {
didSet { updateUI() }
}
///
var textHighlightFontSize: UIFont = .systemFont(ofSize: 18) {
didSet { updateUI() }
}
///
var maxWidth: CGFloat = UIScreen.main.bounds.width - 30 {
didSet { updateUI() }
}
///
var lyricLineSpacing: CGFloat = 10 {
didSet { updateUI() }
}
private var hasSetupUI = false
private var leftConstraint, rightConstraint, bottomConstraint, topConstraint: NSLayoutConstraint!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
label.text = ""
label.status = .normal
label.progressRate = 0
leftConstraint.constant = 0
label.alpha = 1
contentView.layoutIfNeeded()
}
private func setupUI() {
guard !hasSetupUI else {
return
}
contentView.backgroundColor = .clear
backgroundColor = .clear
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
leftConstraint = label.leftAnchor.constraint(equalTo: contentView.leftAnchor)
rightConstraint = label.rightAnchor.constraint(greaterThanOrEqualTo: contentView.rightAnchor)
topConstraint = label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10)
bottomConstraint = label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
topConstraint!.isActive = true
bottomConstraint!.isActive = true
leftConstraint.isActive = true
rightConstraint.isActive = true
hasSetupUI = true
}
private func updateUI() {
if topConstraint!.constant != lyricLineSpacing {
topConstraint!.constant = lyricLineSpacing
bottomConstraint!.constant = -1 * lyricLineSpacing
}
label.textNormalColor = textNormalColor
label.textSelectedColor = textSelectedColor
label.textHighlightedColor = textHighlightedColor
label.textNormalFontSize = textNormalFontSize
label.textHighlightFontSize = textHighlightFontSize
}
func update(model: Model) {
if model.text.contains("我不会发现") {
print("contentView.bounds.width: \(contentView.bounds.width)")
}
label.text = model.text
label.status = model.status
label.progressRate = CGFloat(model.progressRate)
rollLabelIfNeed(model: model)
}
private func rollLabelIfNeed(model: Model) {
if model.status == .normal { /** **/
leftConstraint.constant = 0
return
}
if model.status == .selectedOrHighlighted,
label.bounds.width <= contentView.bounds.width { /** **/
leftConstraint.constant = 0
return
}
let progressRatio = model.progressRate
/** label **/
///
let displayRatio = contentView.bounds.width / label.bounds.width
///
let startRollingPositionRatio = displayRatio/2
///
let stopRollingPositionRatio = 1 - startRollingPositionRatio
if progressRatio > startRollingPositionRatio, progressRatio < stopRollingPositionRatio {
///
let deltaRatio = progressRatio - startRollingPositionRatio
///
let constant = deltaRatio * label.bounds.width
/// label
leftConstraint.constant = constant * -1
UIView.animate(withDuration: 0.2) { [weak self] in
self?.contentView.layoutIfNeeded()
}
}
}
}
extension LyricCell {
class Model {
let text: String
/// 0-1
var progressRate: Double
///
let beginTime: Int
/// (ms)
let duration: Int
///
var status: Status
var tones: [LyricToneModel]
init(text: String,
progressRate: Double,
beginTime: Int,
duration: Int,
status: Status,
tones: [LyricToneModel]) {
self.text = text
self.progressRate = progressRate
self.beginTime = beginTime
self.duration = duration
self.status = status
self.tones = tones
}
func update(progressRate: Double) {
self.progressRate = progressRate
}
func update(status: Status) {
self.status = status
}
var endTime: Int {
beginTime + duration
}
}
typealias Status = LyricLabel.Status
}

View File

@@ -0,0 +1,79 @@
//
// LyricsLabel.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/23.
//
import UIKit
class LyricLabel: UILabel {
/// [0, 1]
var progressRate: CGFloat = 0 { didSet { setNeedsDisplay() } }
///
var textNormalColor: UIColor = .gray
///
var textSelectedColor: UIColor = .white
///
var textHighlightedColor: UIColor = .orange
///
var textNormalFontSize: UIFont = .systemFont(ofSize: 15)
///
var textHighlightFontSize: UIFont = .systemFont(ofSize: 18)
var status: Status = .normal { didSet { updateState() } }
override init(frame: CGRect) {
super.init(frame: frame)
textAlignment = .center
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateState() {
if status == .selectedOrHighlighted {
textColor = textSelectedColor
font = textHighlightFontSize
}
else {
textColor = textNormalColor
font = textNormalFontSize
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if progressRate <= 0 {
return
}
let textWidth = sizeThatFits(CGSize(width: CGFloat(MAXFLOAT),
height: font.lineHeight)).width
let leftRightSpace = (bounds.width - textWidth) / 2
let path = CGMutablePath()
let fillRect = CGRect(x: leftRightSpace,
y: 0,
width: progressRate * textWidth,
height: font.lineHeight)
path.addRect(fillRect)
if let context = UIGraphicsGetCurrentContext(), !path.isEmpty {
context.setLineWidth(1.0)
context.setLineCap(.butt)
context.addPath(path)
context.clip()
let _textColor = textColor
textColor = textHighlightedColor
super.draw(rect)
textColor = _textColor
}
}
}
extension LyricLabel {
enum Status {
case normal
case selectedOrHighlighted
}
}

View File

@@ -0,0 +1,99 @@
//
// LyricMachine+Events.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/3/13.
//
import Foundation
protocol LyricMachineDelegate: NSObjectProtocol {
/// `setLyricData`
func lyricMachine(_ lyricMachine: LyricMachine,
didSetLyricData datas: [LyricCell.Model])
/// `setLyricData`
/// - Parameters:
/// - remainingTime:
func lyricMachine(_ lyricMachine: LyricMachine, didUpdate remainingTime: Int)
///
func lyricMachine(_ lyricMachine: LyricMachine,
didStartLineAt newIndexPath: IndexPath,
oldIndexPath: IndexPath,
animated: Bool)
///
func lyricMachine(_ lyricMachine: LyricMachine, didUpdateLineAt indexPath: IndexPath)
/// Consloe (debug)
func lyricMachine(_ lyricMachine: LyricMachine, didUpdateConsloe text: String)
}
extension LyricMachine { /** invoke **/
func invokeLyricMachine(didSetLyricData datas: [LyricCell.Model]) {
if Thread.isMainThread {
delegate?.lyricMachine(self, didSetLyricData: datas)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.lyricMachine(self, didSetLyricData: datas)
}
}
func invokeLyricMachine(didUpdate remainingTime: Int) {
if Thread.isMainThread {
delegate?.lyricMachine(self, didUpdate: remainingTime)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.lyricMachine(self, didUpdate: remainingTime)
}
}
func invokeLyricMachine(didStartLineAt newIndexPath: IndexPath,
oldIndexPath: IndexPath, animated: Bool) {
if Thread.isMainThread {
delegate?.lyricMachine(self,
didStartLineAt: newIndexPath,
oldIndexPath: oldIndexPath,
animated: animated)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.lyricMachine(self,
didStartLineAt: newIndexPath,
oldIndexPath: oldIndexPath,
animated: animated)
}
}
func invokeLyricMachine(didUpdateLineAt indexPath: IndexPath) {
if Thread.isMainThread {
delegate?.lyricMachine(self, didUpdateLineAt: indexPath)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.lyricMachine(self, didUpdateLineAt: indexPath)
}
}
func invokeLyricMachine(didUpdateConsloe text: String) {
if Thread.isMainThread {
delegate?.lyricMachine(self, didUpdateConsloe: text)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.lyricMachine(self, didUpdateConsloe: text)
}
}
}

View File

@@ -0,0 +1,167 @@
//
// LyricMachine.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/3/13.
//
import Foundation
class LyricMachine {
weak var delegate: LyricMachineDelegate?
fileprivate var lyricData: LyricModel?
fileprivate var dataList = [LyricCell.Model]()
fileprivate var progress: Int = 0
fileprivate var currentIndex = 0
fileprivate var ignoreAnimationAfterDrag = false
fileprivate var isStart = false
fileprivate let logTag = "LyricMachine"
fileprivate let queue = DispatchQueue(label: "queue.LyricMachine")
// MARK: - Internal
func setLyricData(data: LyricModel?) {
queue.async { [weak self] in
self?._setLyricData(data: data)
}
}
func setProgress(progress: Int) {
queue.async { [weak self] in
self?._setProgress(progress: progress)
}
}
func setDragEnd() {
queue.async { [weak self] in
self?._setDragEnd()
}
}
func reset() {
queue.async { [weak self] in
self?._reset()
}
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
// MARK: - Private
private func _setLyricData(data: LyricModel?) {
lyricData = data
dataList = data?.lines.map({ LyricCell.Model(text: $0.content,
progressRate: 0,
beginTime: $0.beginTime,
duration: $0.duration,
status: .normal,
tones: $0.tones) }) ?? []
if let first = dataList.first { /** **/
first.update(status: .selectedOrHighlighted)
}
invokeLyricMachine(didSetLyricData: dataList)
isStart = true
Log.info(text: "_setLyricData", tag: logTag)
}
private func _setProgress(progress: Int) {
guard let data = lyricData else { return }
let remainingTime = data.preludeEndPosition - progress
invokeLyricMachine(didUpdate: remainingTime)
if currentIndex < dataList.count {
if let item = dataList.enumerated().first(where: { progress < $0.element.endTime }) { /** **/
let newCurrentIndex = item.offset
if newCurrentIndex != currentIndex { /** **/
///
let lastIndex = currentIndex
let last = dataList[lastIndex]
last.update(status: .normal)
last.update(progressRate: 0)
let lastIndexPath = IndexPath(row: lastIndex, section: 0)
///
currentIndex = newCurrentIndex
let current = dataList[currentIndex]
current.update(status: .selectedOrHighlighted)
var progressRate: Double = 0
if progress > item.element.beginTime, progress <= item.element.endTime { /** **/
progressRate = LyricMachine.calculateProgressRate(progress: progress,
model: item.element,
canScoring: data.hasPitch) ?? current.progressRate
}
current.update(progressRate: progressRate)
let indexPath = IndexPath(row: currentIndex, section: 0)
let text = "new \(currentIndex) progressRate: \(progressRate) progress:\(progress)"
Log.debug(text: text, tag: logTag)
invokeLyricMachine(didStartLineAt: indexPath, oldIndexPath: lastIndexPath, animated: !ignoreAnimationAfterDrag)
ignoreAnimationAfterDrag = false
invokeLyricMachine(didUpdateConsloe: text)
return
}
if newCurrentIndex == currentIndex,
progress > item.element.beginTime,
progress <= item.element.endTime { /** **/
let current = dataList[currentIndex]
let progressRate: Double = LyricMachine.calculateProgressRate(progress: progress,
model: item.element,
canScoring: data.hasPitch) ?? current.progressRate
current.update(progressRate: progressRate)
let indexPath = IndexPath(row: currentIndex, section: 0)
invokeLyricMachine(didUpdateLineAt: indexPath)
let text = "append \(currentIndex) progressRate: \(progressRate) progress:\(progress)"
Log.debug(text: text, tag: logTag)
invokeLyricMachine(didUpdateConsloe: text)
}
}
}
}
private func _setDragEnd() {
ignoreAnimationAfterDrag = true
Log.info(text: "_setDragEnd", tag: logTag)
}
private func _reset() {
isStart = false
lyricData = nil
dataList = []
currentIndex = 0
progress = 0
ignoreAnimationAfterDrag = false
Log.info(text: "_reset", tag: logTag)
}
}
extension LyricMachine {
///
/// - Parameters:
/// - canScoring: lrc
/// - Returns: `nil` , [0, 1]
static func calculateProgressRate(progress: Int,
model: LyricCell.Model,
canScoring: Bool) -> Double? {
if canScoring {
let toneCount = model.tones.filter({ $0.word.isEmpty == false }).count
for (index, tone) in model.tones.enumerated() {
if progress >= tone.beginTime, progress <= tone.beginTime + tone.duration {
let progressRate = Double((progress - tone.beginTime)) / Double(tone.duration)
let total = (Double(index) + progressRate) / Double(toneCount)
return total
}
}
return nil
}
else {
let progressRate = Double(progress - model.beginTime) / Double(model.duration)
return progressRate
}
}
}

View File

@@ -0,0 +1,296 @@
//
// LyricView.swift
// NewApi
//
// Created by ZYP on 2022/11/22.
//
import UIKit
protocol LyricsViewDelegate: NSObjectProtocol {
func onLyricsViewBegainDrag(view: LyricsView)
func onLyricsView(view: LyricsView, didDragTo position: Int)
}
public class LyricsView: UIView {
///
@objc public var noLyricTipsText: String = "无歌词" { didSet { updateUI() } }
///
@objc public var noLyricTipsColor: UIColor = .orange { didSet { updateUI() } }
///
@objc public var noLyricTipsFont: UIFont = .systemFont(ofSize: 17) { didSet { updateUI() } }
///
@objc public var waitingViewHidden: Bool = false { didSet { updateUI() } }
///
@objc public var inactiveLineTextColor: UIColor = .white
///
@objc public var activeLineUpcomingTextColor: UIColor = .white
///
@objc public var activeLinePlayedTextColor: UIColor = .colorWithHex(hexStr: "#FF8AB4")
///
@objc public var inactiveLineFontSize = UIFont(name: "PingFangSC-Semibold", size: 15)!
///
@objc public var activeLineUpcomingFontSize = UIFont(name: "PingFangSC-Semibold", size: 18)!
///
@objc public var maxWidth: CGFloat = UIScreen.main.bounds.width - 30
///
@objc public var lyricLineSpacing: CGFloat = 10
///
@objc public let firstToneHintViewStyle: FirstToneHintViewStyle = .init()
///
@objc public var draggable: Bool = false
///
@objc public var activeLinePosition: UITableView.ScrollPosition = .middle
/// use for debug only
@objc public var showDebugView = false { didSet { updateUI() } }
weak var delegate: LyricsViewDelegate?
/// view
fileprivate let firstToneHintView = FirstToneHintView()
fileprivate let consoleView = ConsoleView()
fileprivate let noLyricTipsLabel = UILabel()
fileprivate let tableView = UITableView()
fileprivate let logTag = "LyricsView"
fileprivate var dataList = [LyricCell.Model]()
fileprivate var isNoLyric = false
fileprivate let referenceLineView = UIView()
fileprivate var isDragging = false { didSet { referenceLineView.isHidden = !isDragging } }
fileprivate var tableViewTopConstraint: NSLayoutConstraint!, firstToneHintViewHeightConstraint: NSLayoutConstraint!
fileprivate let lyricMachine = LyricMachine()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
updateUI()
commonInit()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
func setLyricData(data: LyricModel?) {
isNoLyric = data == nil
updateUI()
lyricMachine.setLyricData(data: data)
}
func reset() {
lyricMachine.reset()
tableView.isScrollEnabled = false
firstToneHintView.reset()
dataList = []
tableView.reloadData()
Log.info(text: "reset", tag: logTag)
}
func setProgress(progress: Int) {
guard !isDragging else { return }
lyricMachine.setProgress(progress: progress)
}
private func dragCellHandler(scrollView: UIScrollView) {
guard !dataList.isEmpty else {
Log.error(error: "dragCellHandler dataList isEmpty", tag: logTag)
return
}
let point = CGPoint(x: 0, y: scrollView.contentOffset.y + scrollView.bounds.height * 0.5)
var indexPath = tableView.indexPathForRow(at: point)
if indexPath == nil { /** **/
if scrollView.contentOffset.y < 0 {
indexPath = IndexPath(row: 0, section: 0)
}
else {
Log.debug(text: "selecte last at \(point.y)", tag: logTag)
indexPath = IndexPath(row: dataList.count - 1, section: 0)
}
}
Log.debug(text:"dragCellHandler \(indexPath!.row) \(point.y) = \(scrollView.contentOffset.y) + \(scrollView.bounds.height * 0.5)", tag: logTag)
let model = dataList[indexPath!.row]
delegate?.onLyricsView(view: self, didDragTo: model.beginTime)
}
}
// MARK: - UI
extension LyricsView {
fileprivate func setupUI() {
backgroundColor = .clear
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.showsVerticalScrollIndicator = false
referenceLineView.backgroundColor = .red
referenceLineView.isHidden = true
firstToneHintView.style = firstToneHintViewStyle
addSubview(noLyricTipsLabel)
addSubview(firstToneHintView)
addSubview(tableView)
addSubview(referenceLineView)
noLyricTipsLabel.translatesAutoresizingMaskIntoConstraints = false
firstToneHintView.translatesAutoresizingMaskIntoConstraints = false
tableView.translatesAutoresizingMaskIntoConstraints = false
referenceLineView.translatesAutoresizingMaskIntoConstraints = false
noLyricTipsLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
noLyricTipsLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
let topSpace: CGFloat = 5
firstToneHintView.topAnchor.constraint(equalTo: topAnchor, constant: topSpace).isActive = true
firstToneHintView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
firstToneHintView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
firstToneHintViewHeightConstraint = firstToneHintView.heightAnchor.constraint(equalToConstant: firstToneHintViewStyle.size)
firstToneHintViewHeightConstraint.isActive = true
let constant = firstToneHintViewStyle.size + firstToneHintViewStyle.bottomMargin + topSpace
tableViewTopConstraint = tableView.topAnchor.constraint(equalTo: topAnchor, constant: constant)
tableViewTopConstraint.isActive = true
tableView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
referenceLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
referenceLineView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
referenceLineView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
referenceLineView.centerYAnchor.constraint(equalTo: tableView.centerYAnchor).isActive = true
}
fileprivate func commonInit() {
tableView.register(LyricCell.self, forCellReuseIdentifier: "LyricsCell")
tableView.delegate = self
tableView.dataSource = self
firstToneHintViewStyle.didUpdate = { [weak self] in
guard let self = self else { return }
self.updateUI()
}
lyricMachine.delegate = self
}
fileprivate func updateUI() {
noLyricTipsLabel.textColor = noLyricTipsColor
noLyricTipsLabel.text = noLyricTipsText
noLyricTipsLabel.font = noLyricTipsFont
noLyricTipsLabel.isHidden = !isNoLyric
tableView.isHidden = isNoLyric
tableView.isScrollEnabled = draggable
firstToneHintView.isHidden = isNoLyric ? true : waitingViewHidden
firstToneHintView.style = firstToneHintViewStyle
let constant = firstToneHintViewStyle.size + firstToneHintViewStyle.bottomMargin
tableViewTopConstraint.constant = constant
firstToneHintViewHeightConstraint.constant = firstToneHintViewStyle.size
if tableView.bounds.width > 0 {
let viewFrame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: tableView.bounds.height/2)
tableView.tableHeaderView = .init(frame: viewFrame)
tableView.tableFooterView = .init(frame: viewFrame)
Log.debug(text: "viewFrame:\(viewFrame.height)", tag: logTag)
}
if showDebugView {
if !subviews.contains(consoleView) {
addSubview(consoleView)
consoleView.translatesAutoresizingMaskIntoConstraints = false
consoleView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
consoleView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
consoleView.widthAnchor.constraint(equalToConstant: 80).isActive = true
consoleView.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
}
else {
consoleView.removeFromSuperview()
}
}
}
// MARK: - UITableViewDataSource UITableViewDelegate
extension LyricsView: UITableViewDataSource, UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LyricsCell", for: indexPath) as! LyricCell
cell.textNormalColor = inactiveLineTextColor
cell.textSelectedColor = activeLineUpcomingTextColor
cell.textHighlightedColor = activeLinePlayedTextColor
cell.textNormalFontSize = inactiveLineFontSize
cell.textHighlightFontSize = activeLineUpcomingFontSize
cell.maxWidth = maxWidth
cell.lyricLineSpacing = lyricLineSpacing
let model = dataList[indexPath.row]
cell.update(model: model)
return cell
}
public func scrollViewWillBeginDragging(_: UIScrollView) {
Log.info(text: "scrollViewWillBeginDragging", tag: logTag)
isDragging = true
delegate?.onLyricsViewBegainDrag(view: self)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
Log.info(text: "scrollViewDidEndDragging decelerate \(decelerate)", tag: logTag)
if isDragging {
dragCellHandler(scrollView: scrollView)
lyricMachine.setDragEnd()
isDragging = false
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
Log.info(text: "scrollViewDidEndDecelerating", tag: logTag)
if isDragging {
dragCellHandler(scrollView: scrollView)
lyricMachine.setDragEnd()
isDragging = false
}
}
}
// MARK: - LyricMachineDelegate
extension LyricsView: LyricMachineDelegate {
func lyricMachine(_ lyricMachine: LyricMachine, didSetLyricData datas: [LyricCell.Model]) {
Log.debug(text: "set dataList \(datas.count)", tag: logTag)
dataList = datas
tableView.reloadData()
if !datas.isEmpty { /** **/
let indexPath = IndexPath(row: 0, section: 0)
tableView.scrollToRow(at: indexPath, at: activeLinePosition, animated: true)
UIView.performWithoutAnimation {
tableView.reloadRows(at: [indexPath], with: .fade)
}
}
}
func lyricMachine(_ lyricMachine: LyricMachine, didUpdate remainingTime: Int) {
firstToneHintView.setRemainingTime(time: remainingTime)
}
func lyricMachine(_ lyricMachine: LyricMachine,
didStartLineAt newIndexPath: IndexPath,
oldIndexPath: IndexPath,
animated: Bool) {
guard !dataList.isEmpty else {
Log.debug(text: "update tableView will be ignore because dataList is empty", tag: logTag)
return
}
UIView.performWithoutAnimation {
tableView.reloadRows(at: [newIndexPath, oldIndexPath], with: .fade)
}
tableView.scrollToRow(at: newIndexPath, at: activeLinePosition, animated: animated)
}
func lyricMachine(_ lyricMachine: LyricMachine, didUpdateLineAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? LyricCell{
let model = dataList[indexPath.row]
cell.update(model: model)
}
}
func lyricMachine(_ lyricMachine: LyricMachine, didUpdateConsloe text: String) {
consoleView.set(text: text)
}
}

View File

@@ -0,0 +1,161 @@
//
// Model.swift
// NewApi
//
// Created by ZYP on 2022/11/22.
//
import Foundation
@objc public enum MusicType: Int, CustomStringConvertible {
///
case fast = 1
///
case slow = 2
public var description: String {
switch self {
case .fast:
return "fast"
default:
return "slow"
}
}
}
public class LyricModel: NSObject {
///
@objc public var name: String
///
@objc public var singer: String
///
@objc public var type: MusicType
///
@objc public var lines: [LyricLineModel]
///
@objc public var preludeEndPosition: Int
/// (ms)
@objc public var duration: Int
/// pitch
@objc public var hasPitch: Bool
@objc public init(name: String,
singer: String,
type: MusicType,
lines: [LyricLineModel],
preludeEndPosition: Int,
duration: Int,
hasPitch: Bool) {
self.name = name
self.singer = singer
self.type = type
self.lines = lines
self.preludeEndPosition = preludeEndPosition
self.duration = duration
self.hasPitch = hasPitch
}
/// xml
/// - Parameter data: xml
/// - Returns:
@objc public init(data: Data) throws {
self.name = "name"
self.singer = "singer"
self.type = .fast
self.lines = []
self.preludeEndPosition = 0
self.duration = 0
self.hasPitch = true
}
@objc public override init() {
self.name = ""
self.singer = ""
self.type = .fast
self.lines = []
self.preludeEndPosition = 0
self.duration = 0
self.hasPitch = false
super.init()
}
@objc public override var description: String {
let dict = ["name" : name,
"singer" : singer,
"type" : type,
"preludeEndPosition" : preludeEndPosition,
"duration" : duration,
"hasPitch" : hasPitch] as [String : Any]
return "\(dict)"
}
}
public class LyricLineModel: NSObject {
///
@objc public var beginTime: Int
/// (ms)
@objc public var duration: Int
///
@objc public var content: String
///
@objc public var tones: [LyricToneModel]
@objc public init(beginTime: Int,
duration: Int,
content: String,
tones: [LyricToneModel]) {
self.beginTime = beginTime
self.duration = duration
self.content = content
self.tones = tones
}
}
public class LyricToneModel: NSObject {
@objc public let beginTime: Int
@objc public let duration: Int
@objc public var word: String
@objc public let pitch: Double
@objc public var lang: Lang
@objc public let pronounce: String
@objc public init(beginTime: Int,
duration: Int,
word: String,
pitch: Double,
lang: Lang,
pronounce: String) {
self.beginTime = beginTime
self.duration = duration
self.word = word
self.pitch = pitch
self.lang = lang
self.pronounce = pronounce
}
}
///
public class ToneScoreModel: NSObject {
@objc public let tone: LyricToneModel
/// 0-100
@objc public var score: Float
var scores = [Float]()
@objc public init(tone: LyricToneModel,
score: Float) {
self.tone = tone
self.score = score
}
func addScore(score: Float) {
scores.append(score)
self.score = scores.reduce(0, +) / Float(scores.count)
}
}
@objc public enum Lang: Int {
case zh = 1
case en = 2
case unknown = -1
}

View File

@@ -0,0 +1,81 @@
//
// DataStructs.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/12/14.
//
import Foundation
struct Queue<T> {
private var elements: [T] = []
mutating func enqueue(_ element: T) {
elements.append(element)
}
mutating func dequeue() -> T? {
return elements.isEmpty ? nil : elements.removeFirst()
}
var isEmpty: Bool {
return elements.isEmpty
}
var count: Int {
return elements.count
}
func peek() -> T? {
return elements.first
}
mutating func removeAll() {
elements.removeAll()
}
func getAll() -> [T] {
return elements
}
mutating func reset(newElements: [T]) {
elements = newElements
}
}
/// Dictionary for safe, use rwlock
class SafeDictionary<T_KEY: Hashable, T_VALUE: Hashable> {
private var dict: Dictionary<T_KEY, T_VALUE> = Dictionary()
private var rwlock = pthread_rwlock_t()
private let logTag = "SafeDictionary"
init() {
Log.debug(text: "init", tag: logTag)
pthread_rwlock_init(&rwlock, nil)
}
deinit {
Log.debug(text: "deinit", tag: logTag)
pthread_rwlock_destroy(&rwlock)
}
func set(value: T_VALUE, forkey: T_KEY) {
pthread_rwlock_wrlock(&rwlock)
dict[forkey] = value
pthread_rwlock_unlock(&rwlock)
}
func getValue(forkey: T_KEY) -> T_VALUE? {
pthread_rwlock_rdlock(&rwlock)
let value = dict[forkey]
pthread_rwlock_unlock(&rwlock)
return value
}
func removeValue(forkey: T_KEY) {
pthread_rwlock_wrlock(&rwlock)
dict.removeValue(forKey: forkey)
pthread_rwlock_unlock(&rwlock)
}
}

View File

@@ -0,0 +1,116 @@
//
// Extensions.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/21.
//
import Foundation
class AgoraLyricsScore {}
extension String {
//
func textSubstring(startIndex: Int, length: Int) -> String {
let startIndex = index(self.startIndex, offsetBy: startIndex)
let endIndex = index(startIndex, offsetBy: length)
let subvalues = self[startIndex ..< endIndex]
return String(subvalues)
}
}
extension LyricLineModel {
var endTime: Int {
beginTime + duration
}
}
extension LyricToneModel {
var endTime: Int {
beginTime + duration
}
}
extension Bundle {
static var currentBundle: Bundle {
let bundle = Bundle(for: AgoraLyricsScore.self)
let path = bundle.path(forResource: "AgoraLyricsScoreBundle", ofType: "bundle")
if path == nil {
Log.error(error: "bundle not found path", tag: "Bundle")
}
let current = Bundle(path: path!)
if current == nil {
Log.error(error: "bundle not found path: \(path!)", tag: "Bundle")
}
return current!
}
func image(name: String) -> UIImage? {
return UIImage(named: name, in: self, compatibleWith: nil)
}
}
extension UIColor{
class func colorWithHex(hexStr:String) -> UIColor{
return UIColor.colorWithHex(hexStr : hexStr, alpha:1)
}
class func colorWithHex(hexStr:String, alpha:Float) -> UIColor{
var cStr = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
if(cStr.length < 6){
return UIColor.clear;
}
if(cStr.hasPrefix("0x")){
cStr = cStr.substring(from: 2) as NSString
}
if(cStr.hasPrefix("#")){
cStr = cStr.substring(from: 1) as NSString
}
if(cStr.length != 6){
return UIColor.clear
}
let rStr = (cStr as NSString).substring(to: 2)
let gStr = ((cStr as NSString).substring(from: 2) as NSString).substring(to: 2)
let bStr = ((cStr as NSString).substring(from: 4) as NSString).substring(to: 2)
var r: UInt32 = 0x0
var g: UInt32 = 0x0
var b: UInt32 = 0x0
Scanner.init(string: rStr).scanHexInt32(&r)
Scanner.init(string: gStr).scanHexInt32(&g)
Scanner.init(string: bStr).scanHexInt32(&b)
return UIColor.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(alpha));
}
}
extension Date {
/// - 10
var timeStamp: Int {
let timeInterval = timeIntervalSince1970
let timeStamp = Int(timeInterval)
return timeStamp
}
/// - 13
var milliStamp: CLongLong {
let timeInterval = timeIntervalSince1970
let millisecond = CLongLong(round(timeInterval * 1000))
return millisecond
}
}
extension Double {
/// 2
var keep2: Double {
return Double(Darwin.round(self * 100)/100)
}
}

View File

@@ -0,0 +1,118 @@
//
// LogProvider.swift
//
//
// Created by ZYP on 2021/5/28.
//
import Foundation
import UIKit
class Log {
static let provider = LogManager.share
static func errorText(text: String,
tag: String? = nil) {
provider.errorText(text: text, tag: tag)
}
static func error(error: CustomStringConvertible,
tag: String? = nil) {
provider.errorText(text: error.description, tag: tag)
}
static func info(text: String,
tag: String? = nil) {
provider.info(text: text, tag: tag)
}
static func debug(text: String,
tag: String? = nil) {
provider.debug(text: text, tag: tag)
}
static func warning(text: String,
tag: String? = nil) {
provider.warning(text: text, tag: tag)
}
static func setLoggers(loggers: [ILogger]) {
provider.loggers = loggers
}
}
class LogManager {
static let share = LogManager()
var loggers = [ILogger]()
private let queue = DispatchQueue(label: "LogManager")
let dateFormatter: DateFormatter
init() {
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/YY HH:mm:ss:SSS"
}
fileprivate func error(error: Error?,
tag: String?,
domainName: String) {
guard let e = error else {
return
}
var text = "<can not get error info>"
if e.localizedDescription.count > 1 {
text = e.localizedDescription
}
let err = e as CustomStringConvertible
if err.description.count > 1 {
text = err.description
}
errorText(text: text,
tag: tag)
}
fileprivate func errorText(text: String,
tag: String?) {
log(type: .error,
text: text,
tag: tag)
}
fileprivate func info(text: String,
tag: String?) {
log(type: .info,
text: text,
tag: tag)
}
fileprivate func warning(text: String,
tag: String?) {
log(type: .warning,
text: text,
tag: tag)
}
fileprivate func debug(text: String,
tag: String?) {
log(type: .debug,
text: text,
tag: tag)
}
fileprivate func log(type: LoggerLevel,
text: String,
tag: String?) {
queue.async { [weak self] in
guard let self = self, !self.loggers.isEmpty else { return }
let time = self.dateFormatter.string(from: .init())
self.log(content: text, tag: tag, time: time, level: type)
}
}
func log(content: String, tag: String?, time: String, level: LoggerLevel) {
for logger in loggers {
logger.onLog(content: content, tag: tag, time: time, level: level)
}
}
}

View File

@@ -0,0 +1,60 @@
//
// Logger.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/2/3.
//
import Foundation
import AgoraComponetLog
// MARK:- ConsoleLogger
public class ConsoleLogger: NSObject, ILogger {
@objc public func onLog(content: String,
tag: String?,
time: String,
level: LoggerLevel) {
let text = tag == nil ? "[\(time)][ALS][\(level)]: " + content : "[\(time)][ALS][\(level)][\(tag!)]: " + content
print(text)
}
}
// MARK:- FileLogger
public class FileLogger: NSObject, ILogger {
let componetFileLogger: AgoraComponetFileLogger!
let filePrefixName = "agora.AgoraLyricsScore"
let maxFileSizeOfBytes: UInt64 = 1024 * 1024 * 1
let maxFileCount: UInt = 4
let domainName = "ALS"
@objc public override init() {
self.componetFileLogger = AgoraComponetFileLogger(logFilePath: nil,
filePrefixName: filePrefixName,
maxFileSizeOfBytes: maxFileSizeOfBytes,
maxFileCount: maxFileCount,
domainName: domainName)
super.init()
}
/// init
/// - Parameter logFilePath: custom log file path.
@objc public init(logFilePath: String) {
componetFileLogger = AgoraComponetFileLogger(logFilePath: logFilePath,
filePrefixName: filePrefixName,
maxFileSizeOfBytes: maxFileSizeOfBytes,
maxFileCount: maxFileCount,
domainName: domainName)
}
@objc public func onLog(content: String,
tag: String?,
time: String,
level: LoggerLevel) {
let newLevel = AgoraComponetLoggerLevel(rawValue: UInt(level.rawValue))!
componetFileLogger.onLog(withContent: content, tag: tag, time: time, level: newLevel)
}
}

View File

@@ -0,0 +1,85 @@
//
// LrcParser.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/21.
//
import Foundation
class LrcParser {
private let logTag = "LrcParser"
private var lines = [LyricLineModel]()
deinit {
Log.info(text: "deinit", tag: logTag)
}
func parseLyricData(data: Data) -> LyricModel? {
lines = []
guard let string = String(data: data, encoding: .utf8) else {
Log.errorText(text: "convert to string fail", tag: logTag)
return nil
}
return parse(lrcString: string)
}
private func parse(lrcString: String) -> LyricModel? {
let lrcConnectArray = lrcString.components(separatedBy: "\r\n")
let pattern = "\\[[0-9][0-9]:[0-9][0-9].[0-9]{1,}\\]"
guard let regular = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else {
return nil
}
for line in lrcConnectArray {
let matchesArray = regular.matches(in: line,
options: .reportProgress,
range: NSRange(location: 0, length: line.count))
guard let lrc = line.components(separatedBy: "]").last else {
continue
}
for match in matchesArray {
var timeStr = NSString(string: line).substring(with: match.range)
// [], 00:00.00
timeStr = timeStr.textSubstring(startIndex: 1, length: timeStr.count - 2)
let df = DateFormatter()
df.dateFormat = "mm:ss.SS"
let date1 = df.date(from: timeStr)
let date2 = df.date(from: "00:00.00")
var interval1 = date1!.timeIntervalSince1970
let interval2 = date2!.timeIntervalSince1970
interval1 -= interval2
if interval1 < 0 {
interval1 *= -1
}
let line = LyricLineModel(beginTime: Int(interval1 * 1000),
duration: 0,
content: lrc,
tones: [])
if let lastLine = lines.last { /** **/
lastLine.duration = line.beginTime - lastLine.beginTime
}
lines.append(line)
}
}
guard lines.count != 0, let preludeEndPosition = lines.first?.beginTime else {
return nil
}
let result = LyricModel(name: "unknow",
singer: "unknow",
type: .fast,
lines: lines,
preludeEndPosition: preludeEndPosition,
duration: 0,
hasPitch: false)
return result
}
}

View File

@@ -0,0 +1,35 @@
//
// File.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/21.
//
import Foundation
class Parser {
private let logTag = "Parser"
func parseLyricData(data: Data) -> LyricModel? {
guard data.count > 0 else {
Log.errorText(text: "data.count == 0", tag: logTag)
return nil
}
guard let string = String(data: data, encoding: .utf8) else {
Log.errorText(text: "can not verified file type", tag: logTag)
return nil
}
if string.first == "<" { /** XML **/
let parser = XmlParser()
return parser.parseLyricData(data: data)
}
if string.first == "[" { /** LRC **/
let parser = LrcParser()
return parser.parseLyricData(data: data)
}
fatalError("unknow file type")
}
}

View File

@@ -0,0 +1,112 @@
//
// ProgressChecker.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/3/21.
//
import Foundation
protocol ProgressCheckerDelegate: NSObjectProtocol {
func progressCheckerDidProgressPause()
}
/// check progress if pause
class ProgressChecker: NSObject {
private var lastProgress = 0
private var progress = 0
private var isStart = false
private let queue = DispatchQueue(label: "queue.progressChecker")
weak var delegate: ProgressCheckerDelegate?
private var isPause = false
private var timer: DispatchSourceTimer?
private let logTag = "ProgressChecker"
// MARK: - Internal
/// progress input
func set(progress: Int) {
queue.async { [weak self] in
self?._set(progress: progress)
}
}
func reset() {
queue.async { [weak self] in
self?._reset()
}
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
// MARK: - Private
private func _set(progress: Int) {
self.progress = progress
_start()
}
private func _start() {
if isStart { return }
isStart = true
setupTimer()
}
private func _check() {
guard progress > 0 else {
return
}
if lastProgress == progress {
if !isPause {
invokeProgressCheckerDidProgressPause()
}
isPause = true
}
else {
isPause = false
}
lastProgress = progress
}
private func _reset() {
cancleTimer()
isPause = false
isStart = false
lastProgress = 0
progress = 0
}
private func setupTimer() {
timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
timer?.schedule(deadline: .now(), repeating: .seconds(1), leeway: .seconds(0))
timer?.setEventHandler { [weak self] in
self?._check()
}
timer?.resume()
}
private func cancleTimer() {
guard let t = timer else {
return
}
t.cancel()
timer = nil
}
}
extension ProgressChecker {
fileprivate func invokeProgressCheckerDidProgressPause() {
if Thread.isMainThread {
delegate?.progressCheckerDidProgressPause()
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.progressCheckerDidProgressPause()
}
}
}

View File

@@ -0,0 +1,269 @@
//
// Parser.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/12/21.
//
import Foundation
class XmlParser: NSObject {
fileprivate let logTag = "XmlParser"
fileprivate var parserTypes: [ParserType] = []
fileprivate var song: LyricModel!
deinit {
Log.info(text: "deinit", tag: logTag)
}
func parseLyricData(data: Data) -> LyricModel? {
song = nil
parserTypes = []
let parser = XMLParser(data: data)
parser.delegate = self
let success = parser.parse()
if !success {
let error = parser.parserError
let line = parser.lineNumber
let col = parser.columnNumber
Log.error(error: "parsing Error(\(error?.localizedDescription ?? "")) at \(line):\(col)", tag: logTag)
return nil
}
if song == nil {
return nil
}
return process()
}
private func process() -> LyricModel? {
if song.lines.count == 0 {
let text = "data error. song.lines: \(song.lines)"
Log.error(error: text, tag: logTag)
return nil
}
var hasPitch = false
var preludeEndPosition = -1
for line in song.lines {
var content = ""
for item in line.tones.enumerated() {
let tone = item.element
let index = item.offset
if tone.lang == .en, tone.word != "" { /** **/
let count = line.tones.count
let lead = (index >= 1 && line.tones[index - 1].lang != .en && line.tones[index - 1].word != "") ? " " : ""
let trail = index == count - 1 ? "" : " "
tone.word = "\(lead)\(tone.word)\(trail)"
}
if tone.pitch > 0 {
hasPitch = true
}
if preludeEndPosition == -1 {
preludeEndPosition = tone.beginTime
}
content += tone.word
}
let lineBeginTime = line.tones.first?.beginTime ?? -1
let lineEndTime = (line.tones.last?.duration ?? -1) + (line.tones.last?.beginTime ?? -1)
if lineBeginTime < 0 || lineEndTime < 0 || lineEndTime - lineBeginTime < 0 {
let text = "data error. lineBeginTime: \(lineBeginTime) lineEndTime: \(lineEndTime)"
Log.error(error: text, tag: logTag)
return nil
}
line.beginTime = lineBeginTime
line.duration = lineEndTime - lineBeginTime
line.content = content
}
if let lastDuration = song.lines.last?.duration,
let lastBeginTime = song.lines.last?.beginTime {
song.duration = lastDuration + lastBeginTime
}
song.hasPitch = hasPitch
song.preludeEndPosition = preludeEndPosition
return song
}
}
// MARK: -
extension XmlParser {
fileprivate func current(type: ParserType) -> Bool {
return parserTypes.last == type
}
fileprivate func push(_ type: ParserType) {
parserTypes.append(type)
}
fileprivate func pop() {
parserTypes.removeLast()
}
fileprivate func pop(equal: ParserType) {
if current(type: equal) {
pop()
}
}
}
// MARK: - XMLParserDelegate
extension XmlParser: XMLParserDelegate {
func parserDidStartDocument(_: XMLParser) {}
func parserDidEndDocument(_: XMLParser) {}
func parser(_: XMLParser, parseErrorOccurred parseError: Error) {
Log.error(error: parseError.localizedDescription, tag: logTag)
}
func parser(_: XMLParser, validationErrorOccurred validationError: Error) {
Log.error(error: validationError.localizedDescription, tag: logTag)
}
func parser(_: XMLParser,
didStartElement elementName: String,
namespaceURI _: String?,
qualifiedName _: String?,
attributes attributeDict: [String: String] = [:]) {
switch elementName {
case "song":
song = LyricModel()
case "general":
push(.general)
case "name":
push(.name)
case "singer":
push(.singer)
case "type":
push(.type)
case "sentence":
push(.sentence)
let line = LyricLineModel(beginTime: -1, duration: -1, content: "", tones: [])
song.lines.append(line)
case "tone":
push(.tone)
if let sentence = song.lines.last {
let beginValue = Double(attributeDict["begin"] ?? "0") ?? 0
let endValue = Double(attributeDict["end"] ?? "0") ?? 0
let pitchValue = Float(attributeDict["pitch"] ?? "0") ?? 0
let begin = Int(beginValue * 1000)
let end = Int(endValue * 1000)
let pitch = Double(pitchValue)
let pronounce = attributeDict["pronounce"] ?? ""
let langValue = Int(attributeDict["lang"] ?? "") ?? -1
let lang = Lang(rawValue: langValue)!
let tone = LyricToneModel(beginTime: begin,
duration: end - begin,
word: "",
pitch: pitch,
lang: lang,
pronounce: pronounce)
sentence.tones.append(tone)
}
case "word":
push(.word)
case "overlap":
push(.overlap)
let beginValue = Double(attributeDict["begin"] ?? "0") ?? 0
let endValue = Double(attributeDict["end"] ?? "0") ?? 0
let begin = Int(beginValue * 1000)
let end = Int(endValue * 1000)
let pitch: Double = 0
let pronounce = ""
let langValue = Int(attributeDict["lang"] ?? "") ?? -1
let lang = Lang(rawValue: langValue)!
let tone = LyricToneModel(beginTime: begin,
duration: end - begin,
word: "",
pitch: pitch,
lang: lang,
pronounce: pronounce)
let line = LyricLineModel(beginTime: 0, duration: 0, content: "", tones: [tone])
song.lines.append(line)
default:
break
}
}
func parser(_: XMLParser, foundCharacters string: String) {
if let last = parserTypes.last {
switch last {
case .name:
song.name = string
// if song.name != nil {
// song.name += string
// }
// else {
// song.name = string
// }
case .singer:
song.singer = string
case .type:
if let value = Int(string) {
song.type = MusicType(rawValue: value) ?? .fast
}
else {
song.type = .fast
}
case .word, .overlap:
if let tone = song.lines.last?.tones.last {
tone.word = tone.word + string
if tone.lang == .unknown { /** **/
do {
let regular = try NSRegularExpression(pattern: "[a-zA-Z]", options: .caseInsensitive)
let count = regular.numberOfMatches(in: tone.word, options: .anchored, range: NSRange(location: 0, length: tone.word.count))
if count > 0 {
tone.lang = .en
} else {
tone.lang = .zh
}
} catch {
tone.lang = .en
}
}
}
default:
break
}
}
}
func parser(_: XMLParser,
didEndElement elementName: String,
namespaceURI _: String?,
qualifiedName _: String?) {
switch elementName {
case "general":
pop(equal: .general)
case "name":
pop(equal: .name)
case "singer":
pop(equal: .singer)
case "type":
pop(equal: .type)
case "sentence":
pop(equal: .sentence)
case "tone":
pop(equal: .tone)
case "word":
pop(equal: .word)
case "overlap":
pop(equal: .overlap)
default:
break
}
}
}
private enum ParserType {
case general
case name
case singer
case type
case sentence
case tone
case word
case overlap
}

View File

@@ -0,0 +1,16 @@
//
// ScoreAlgorithm.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/11.
//
import Foundation
class ScoreAlgorithm: IScoreAlgorithm {
func getLineScore(with toneScores: [ToneScoreModel]) -> Int {
if toneScores.isEmpty { return 0 }
let ret = toneScores.map({ $0.score }).reduce(0.0, +) / Float(toneScores.count)
return Int(ret)
}
}

View File

@@ -0,0 +1,37 @@
//
// ToneCalculator.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/11.
//
import Foundation
var useC = true
class ToneCalculator {
/// tone
static func calculedScore(voicePitch: Double,
stdPitch: Double,
scoreLevel: Int,
scoreCompensationOffset: Int) -> Float {
if useC {
return calculedScoreC(voicePitch, stdPitch, Int32(scoreLevel), Int32(scoreCompensationOffset))
}
let stdTone = ToneCalculator.pitchToTone(pitch: stdPitch)
let voiceTone = ToneCalculator.pitchToTone(pitch: voicePitch)
var match = 1 - Float(scoreLevel)/100 * Float(abs(voiceTone - stdTone)) + Float(scoreCompensationOffset)/100
match = max(0, match)
match = min(1, match)
return match * 100
}
static func pitchToTone(pitch: Double) -> Double {
if useC {
return pitchToToneC(pitch)
}
let eps = 1e-6
return (max(0, log(pitch / 55 + eps) / log(2))) * 12
}
}

View File

@@ -0,0 +1,73 @@
//
// VoicePitchChanger.swift
// AgoraLyricsScore
//
// Created by ZYP on 2022/11/23.
//
import Foundation
class VoicePitchChanger {
///
var offset: Double = 0.0
///
var n: Double = 0
/// Pitch
/// - Parameters:
/// - stdPitch:
/// - voicePitch: rtc
/// - stdMaxPitch:
/// - Returns:
func handlePitch(stdPitch: Double,
voicePitch: Double,
stdMaxPitch: Double) -> Double {
if useC {
return handlePitchC(stdPitch, voicePitch, stdMaxPitch)
}
if voicePitch <= 0 {
return 0
}
n += 1.0
let gap = stdPitch - voicePitch
offset = offset * (n - 1)/n + gap/n
if offset < 0 {
offset = max(offset, -1 * stdMaxPitch * 0.4)
}
else {
offset = min(offset, stdMaxPitch * 0.4)
}
if abs(voicePitch - stdPitch) < 1 { /** **/
return voicePitch
}
switch n {
case 1:
return min(voicePitch + 0.5 * offset, stdMaxPitch)
case 2:
return min(voicePitch + 0.6 * offset, stdMaxPitch)
case 3:
return min(voicePitch + 0.7 * offset, stdMaxPitch)
case 4:
return min(voicePitch + 0.8 * offset, stdMaxPitch)
case 5:
return min(voicePitch + 0.9 * offset, stdMaxPitch)
default:
return min(voicePitch + offset, stdMaxPitch)
}
}
func reset() {
if useC {
resetC()
return
}
offset = 0.0
n = 0.0
}
}

View File

@@ -0,0 +1,278 @@
//
// ScoringMachine+DataHandle.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/2/2.
//
import Foundation
extension ScoringMachine {
/// Scoring
/// - shouldFixTime:
/// - return: (, )
static func createData(data: LyricModel, shouldFixTime: Bool = true) -> ([Int], [Info]) {
var array = [Info]()
var lineEndTimes = [Int]()
var preEndTime = 0
for line in data.lines {
for tone in line.tones {
var beginTime = tone.beginTime
var duration = tone.duration
if shouldFixTime { /** **/
if beginTime < preEndTime {
/// endTime
let endTime = tone.endTime
beginTime = preEndTime
duration = endTime - beginTime
}
}
let info = Info(beginTime: beginTime,
duration: duration,
word: tone.word,
pitch: tone.pitch,
drawBeginTime: tone.beginTime,
drawDuration: tone.duration,
isLastInLine: tone == line.tones.last)
preEndTime = tone.endTime
array.append(info)
}
lineEndTimes.append(preEndTime)
}
return (lineEndTimes, array)
}
func makeHighlightInfos(progress: Int,
hitedInfo: Info,
currentVisiableInfos: [Info],
currentHighlightInfos: [Info]) -> [Info] {
let pitchDuration = 50
if let preHitInfo = currentHighlightInfos.last, preHitInfo.beginTime == hitedInfo.beginTime { /** **/
let newDrawBeginTime = max(progress, preHitInfo.beginTime)
let distance = newDrawBeginTime - preHitInfo.drawEndTime
if distance < pitchDuration { /** **/
let drawDuration = min(preHitInfo.drawDuration + pitchDuration + distance, preHitInfo.duration)
preHitInfo.drawDuration = drawDuration
return currentHighlightInfos
}
}
/** **/
let stdInfo = hitedInfo
let drawBeginTime = max(progress, stdInfo.beginTime)
let drawDuration = min(pitchDuration, stdInfo.duration)
let info = Info(beginTime: stdInfo.beginTime,
duration: stdInfo.duration,
word: stdInfo.word,
pitch: stdInfo.pitch,
drawBeginTime: drawBeginTime,
drawDuration: drawDuration,
isLastInLine: false)
var temp = currentHighlightInfos
temp.append(info)
return temp
}
/// DrawInfo
/// - Returns: (visiableDrawInfos, highlightDrawInfos, currentVisiableInfos, currentHighlightInfos)
func makeInfos(progress: Int,
dataList: [Info],
currentHighlightInfos: [Info],
defaultPitchCursorX: CGFloat,
widthPreMs: CGFloat,
canvasViewSize: CGSize,
standardPitchStickViewHeight: CGFloat,
minPitch: Double,
maxPitch: Double) -> ([DrawInfo], [DrawInfo], [Info], [Info]) {
///
let defaultPitchCursorXTime = Int(defaultPitchCursorX / widthPreMs)
///
let remainTime = Int((canvasViewSize.width - defaultPitchCursorX) / widthPreMs)
///
let beginTime = max(progress - defaultPitchCursorXTime, 0)
///
let endTime = progress + remainTime
let currentVisiableInfos = filterInfos(infos: dataList,
beginTime: beginTime,
endTime: endTime)
let highlightInfos = filterInfos(infos: currentHighlightInfos,
beginTime: beginTime,
endTime: endTime)
var visiableDrawInfos = [DrawInfo]()
for info in currentVisiableInfos {
let rect = calculateDrawRect(progress: progress,
info: info,
standardPitchStickViewHeight: standardPitchStickViewHeight,
widthPreMs: widthPreMs,
canvasViewSize: canvasViewSize,
minPitch: minPitch,
maxPitch: maxPitch)
let drawInfo = DrawInfo(rect: rect)
visiableDrawInfos.append(drawInfo)
}
var highlightDrawInfos = [DrawInfo]()
for info in highlightInfos {
let rect = calculateDrawRect(progress: progress,
info: info,
standardPitchStickViewHeight: standardPitchStickViewHeight,
widthPreMs: widthPreMs,
canvasViewSize: canvasViewSize,
minPitch: minPitch,
maxPitch: maxPitch)
let drawInfo = DrawInfo(rect: rect)
highlightDrawInfos.append(drawInfo)
}
return (visiableDrawInfos, highlightDrawInfos, currentVisiableInfos, highlightInfos)
}
/// Pitch
/// - Returns: (minPitch, maxPitch)
func makeMinMaxPitch(dataList: [Info]) -> (Double, Double) {
/** set value **/
let pitchs = dataList.filter({ $0.word != " " }).map({ $0.pitch })
let maxValue = pitchs.max() ?? 0
let minValue = pitchs.min() ?? 0
return (minValue, maxValue)
}
///
func getHitedInfo(progress: Int,
currentVisiableInfos: [Info]) -> Info? {
let pitchBeginTime = progress
return currentVisiableInfos.first { info in
return pitchBeginTime >= info.drawBeginTime && pitchBeginTime <= info.endTime
}
}
///
/// - Parameters:
/// - Returns: `nil` , ==`lineEndTimes.count`
func findCurrentIndexOfLine(progress: Int, lineEndTimes: [Int]) -> Int? {
if lineEndTimes.isEmpty {
return nil
}
if progress > lineEndTimes.last! {
return lineEndTimes.count
}
if progress <= lineEndTimes.first! {
return 0
}
var lastEnd = 0
for (offset, value) in lineEndTimes.enumerated() {
if progress > lastEnd, progress <= value {
return offset
}
lastEnd = value
}
return nil
}
/// infos
func filterInfos(infos: [Info],
beginTime: Int,
endTime: Int) -> [Info] {
var result = [Info]()
for info in infos {
if info.drawBeginTime >= endTime {
break
}
if info.endTime <= beginTime {
continue
}
result.append(info)
}
return result
}
///
/// - Parameters:
/// - indexOfLine: index 2, 0,1,2
func calculatedCumulativeScore(indexOfLine: Int, lineScores: [Int]) -> Int {
var cumulativeScore = 0
for (offset, value) in lineScores.enumerated() {
if offset <= indexOfLine {
cumulativeScore += value
}
}
return cumulativeScore
}
}
extension ScoringMachine { /** ui **/
/// 线
func calculateDrawRect(progress: Int,
info: Info,
standardPitchStickViewHeight: CGFloat,
widthPreMs: CGFloat,
canvasViewSize: CGSize,
minPitch: Double,
maxPitch: Double) -> CGRect {
let beginTime = info.drawBeginTime
let duration = info.drawDuration
let pitch = info.pitch
///
let defaultPitchCursorXTime = Int(defaultPitchCursorX / widthPreMs)
let x = CGFloat(beginTime - (progress - defaultPitchCursorXTime)) * widthPreMs
let y = calculatedY(pitch: pitch,
viewHeight: canvasViewSize.height,
minPitch: minPitch,
maxPitch: maxPitch,
standardPitchStickViewHeight: standardPitchStickViewHeight) ?? 0 - (standardPitchStickViewHeight / 2)
let w = widthPreMs * CGFloat(duration)
let h = standardPitchStickViewHeight
let rect = CGRect(x: x, y: y, width: w, height: h)
return rect
}
func calculatedY(pitch: Double,
viewHeight: CGFloat,
minPitch: Double,
maxPitch: Double,
standardPitchStickViewHeight: CGFloat) -> CGFloat? {
if viewHeight <= 0 {
Log.errorText(text: "calculatedY viewHeight invalid \(viewHeight)", tag: logTag)
return nil
}
/** **/
let pitchPerPoint = (CGFloat(maxPitch) - CGFloat(minPitch)) / viewHeight
let extends = pitchPerPoint * standardPitchStickViewHeight
if pitch < minPitch {
return viewHeight - extends/2
}
if pitch > maxPitch {
return extends/2
}
/** **/
let rate = (pitch - minPitch) / (maxPitch - minPitch)
let renderingHeight = viewHeight - extends
/** bottomtop **/
let distance = extends/2 + (renderingHeight * rate)
/** y **/
let y = viewHeight - distance
if y.isNaN {
Log.errorText(text: "calculatedY result invalid pitch:\(pitch) viewHeight:\(viewHeight) minPitch:\(minPitch) maxPitch:\(maxPitch) standardPitchStickViewHeight:\(standardPitchStickViewHeight)", tag: logTag)
return nil
}
return y
}
}

View File

@@ -0,0 +1,96 @@
//
// ScoringMachine+Events.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/11.
//
import Foundation
protocol ScoringMachineDelegate: NSObjectProtocol {
///
func sizeOfCanvasView(_ scoringMachine: ScoringMachine) -> CGSize
///
func scoringMachine(_ scoringMachine: ScoringMachine,
didUpdateDraw standardInfos: [ScoringMachine.DrawInfo],
highlightInfos: [ScoringMachine.DrawInfo])
///
func scoringMachine(_ scoringMachine: ScoringMachine,
didUpdateCursor centerY: CGFloat,
showAnimation: Bool,
debugInfo: ScoringMachine.DebugInfo)
///
func scoringMachine(_ scoringMachine: ScoringMachine,
didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int)
}
extension ScoringMachine { /** invoke **/
func invokeScoringMachine(didUpdateDraw standardInfos: [ScoringMachine.DrawInfo],
highlightInfos: [ScoringMachine.DrawInfo]) {
if Thread.isMainThread {
delegate?.scoringMachine(self,
didUpdateDraw: standardInfos,
highlightInfos: highlightInfos)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.scoringMachine(self,
didUpdateDraw: standardInfos,
highlightInfos: highlightInfos)
}
}
func invokeScoringMachine(didUpdateCursor centerY: CGFloat,
showAnimation: Bool,
debugInfo: DebugInfo) {
if Thread.isMainThread {
delegate?.scoringMachine(self,
didUpdateCursor: centerY,
showAnimation: showAnimation,
debugInfo: debugInfo)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.scoringMachine(self,
didUpdateCursor: centerY,
showAnimation: showAnimation,
debugInfo: debugInfo)
}
}
func invokeScoringMachine(didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int) {
if Thread.isMainThread {
delegate?.scoringMachine(self,
didFinishLineWith: model,
score: score,
cumulativeScore: cumulativeScore,
lineIndex: lineIndex,
lineCount: lineCount)
return
}
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.delegate?.scoringMachine(self,
didFinishLineWith: model,
score: score,
cumulativeScore: cumulativeScore,
lineIndex: lineIndex,
lineCount: lineCount)
}
}
}

View File

@@ -0,0 +1,73 @@
//
// ScoringVM+Info.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/11.
//
import Foundation
extension ScoringMachine {
class Info {
///
let beginTime: Int
///
let duration: Int
///
let drawBeginTime: Int
///
var drawDuration: Int
let word: String
let pitch: Double
///
let isLastInLine: Bool
required init(beginTime: Int,
duration: Int,
word: String,
pitch: Double,
drawBeginTime: Int,
drawDuration: Int,
isLastInLine: Bool) {
self.beginTime = beginTime
self.duration = duration
self.word = word
self.pitch = pitch
self.drawBeginTime = drawBeginTime
self.drawDuration = drawDuration
self.isLastInLine = isLastInLine
}
var endTime: Int {
beginTime + duration
}
var drawEndTime: Int {
drawBeginTime + drawDuration
}
var tone: LyricToneModel {
return LyricToneModel(beginTime: beginTime,
duration: duration,
word: word,
pitch: pitch,
lang: .zh,
pronounce: "")
}
}
struct DrawInfo {
let rect: CGRect
}
struct DebugInfo {
/// pitch
let originalPitch: Double
/// pitch
let pitch: Double
let hitedInfo: ScoringMachine.Info?
let progress: Int
}
}

View File

@@ -0,0 +1,314 @@
//
// ScoringVM.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/11.
//
import Foundation
class ScoringMachine {
///
var defaultPitchCursorX: CGFloat = 100
/// 线
var standardPitchStickViewHeight: CGFloat = 3
/// 线
var movingSpeedFactor: CGFloat = 120
/// 0-1
var hitScoreThreshold: Float = 0.7
var scoreLevel = 10
var scoreCompensationOffset = 0
var scoreAlgorithm: IScoreAlgorithm = ScoreAlgorithm()
weak var delegate: ScoringMachineDelegate?
fileprivate var progress: Int = 0
fileprivate var widthPreMs: CGFloat { movingSpeedFactor / 1000 }
fileprivate var dataList = [Info]()
fileprivate var lineEndTimes = [Int]()
fileprivate var currentVisiableInfos = [Info]()
fileprivate var currentHighlightInfos = [Info]()
fileprivate var maxPitch: Double = 0
fileprivate var minPitch: Double = 0
fileprivate var canvasViewSize: CGSize = .zero
fileprivate var toneScores = [ToneScoreModel]()
fileprivate var lineScores = [Int]()
fileprivate var currentIndexOfLine = 0
fileprivate var lyricData: LyricModel?
fileprivate var cumulativeScore = 0
fileprivate var isDragging = false
fileprivate var voiceChanger = VoicePitchChanger()
fileprivate let queue = DispatchQueue(label: "ScoringMachine")
let logTag = "ScoringMachine"
// MARK: - Internal
func setLyricData(data: LyricModel?) {
guard let lyricData = data else { return }
guard let size = delegate?.sizeOfCanvasView(self) else { fatalError("sizeOfCanvasView has not been implemented") }
queue.async { [weak self] in
self?._setLyricData(lyricData: lyricData, size: size)
}
}
func setProgress(progress: Int) {
Log.debug(text: "progress: \(progress)", tag: "progress")
queue.async { [weak self] in
self?._setProgress(progress: progress)
}
}
func setPitch(pitch: Double) {
queue.async { [weak self] in
self?._setPitch(pitch: pitch)
}
}
func dragBegain() {
queue.async { [weak self] in
self?._dragBegain()
}
}
func dragDidEnd(position: Int) {
queue.async { [weak self] in
self?._dragDidEnd(position: position)
}
}
func getCumulativeScore() -> Int {
Log.debug(text: "== getCumulativeScore cumulativeScore:\(cumulativeScore)", tag: "drag")
return cumulativeScore
}
func setScoreAlgorithm(algorithm: IScoreAlgorithm) {
self.scoreAlgorithm = algorithm
}
func reset() {
queue.async { [weak self] in
self?._reset()
}
}
deinit {
Log.info(text: "deinit", tag: logTag)
}
// MARK: - Private
private func _setLyricData(lyricData: LyricModel, size: CGSize) {
canvasViewSize = size
self.lyricData = lyricData
let (lineEnds, infos) = ScoringMachine.createData(data: lyricData)
dataList = infos
lineEndTimes = lineEnds
let (min, max) = makeMinMaxPitch(dataList: dataList)
minPitch = min
maxPitch = max
toneScores = lyricData.lines[0].tones.map({ ToneScoreModel(tone: $0, score: 0) })
lineScores = .init(repeating: 0, count: lyricData.lines.count)
handleProgress()
}
private func _setProgress(progress: Int) {
guard !isDragging else { return }
guard let model = lyricData, model.hasPitch else { return }
Log.debug(text: "progress: \(progress)", tag: logTag)
self.progress = progress
handleProgress()
}
private func _setPitch(pitch: Double) {
guard !isDragging else { return }
guard let model = lyricData, model.hasPitch else { return }
if pitch <= 0 {
let y = canvasViewSize.height
let debugInfo = DebugInfo(originalPitch: pitch,
pitch: pitch,
hitedInfo: nil,
progress: progress)
invokeScoringMachine(didUpdateCursor: y, showAnimation: false, debugInfo: debugInfo)
return
}
/** 1.get hitedInfo **/
guard let hitedInfo = getHitedInfo(progress: progress,
currentVisiableInfos: currentVisiableInfos) else {
let y = calculatedY(pitch: pitch,
viewHeight: canvasViewSize.height,
minPitch: minPitch,
maxPitch: maxPitch,
standardPitchStickViewHeight: standardPitchStickViewHeight)
if y == nil {
Log.errorText(text: "y is invalid, at getHitedInfo step", tag: logTag)
}
let yValue = (y != nil) ? y! : (canvasViewSize.height >= 0 ? canvasViewSize.height : 0)
let debugInfo = DebugInfo(originalPitch: pitch,
pitch: pitch,
hitedInfo: nil,
progress: progress)
invokeScoringMachine(didUpdateCursor: yValue, showAnimation: false, debugInfo: debugInfo)
return
}
/** 2.voice change **/
let voicePitch = voiceChanger.handlePitch(stdPitch: hitedInfo.pitch,
voicePitch: pitch,
stdMaxPitch: maxPitch)
Log.debug(text: "pitch: \(pitch) after: \(voicePitch) stdPitch:\(hitedInfo.pitch)", tag: logTag)
/** 3.calculted score **/
let score = ToneCalculator.calculedScore(voicePitch: voicePitch,
stdPitch: hitedInfo.pitch,
scoreLevel: scoreLevel,
scoreCompensationOffset: scoreCompensationOffset)
/** 4.save tone score **/
var hitToneScore = toneScores.first(where: { $0.tone.beginTime == hitedInfo.beginTime })
if hitToneScore != nil {
hitToneScore!.addScore(score: score)
}
else { /** reresetToneScores while can not find a specific one **/
resetToneScores(position: progress)
hitToneScore = toneScores.first(where: { $0.tone.beginTime == hitedInfo.beginTime })
if hitToneScore != nil {
hitToneScore!.addScore(score: score)
}
else {
Log.error(error: "ignore score \(score) progress: \(progress), beginTime: \(hitedInfo.beginTime), endTime: \(hitedInfo.endTime) \(toneScores.map({ "\($0.tone.beginTime)-" }).reduce("", +))", tag: logTag)
}
}
/** 5.update HighlightInfos **/
if score >= hitScoreThreshold * 100 {
currentHighlightInfos = makeHighlightInfos(progress: progress,
hitedInfo: hitedInfo,
currentVisiableInfos: currentVisiableInfos,
currentHighlightInfos: currentHighlightInfos)
}
Log.debug(text: "progress:\(progress) score: \(score) pitch: \(pitch) after: \(voicePitch) stdPitch:\(hitedInfo.pitch)", tag: logTag)
/** 6.calculated ui info **/
let showAnimation = score >= hitScoreThreshold * 100
let y = calculatedY(pitch: voicePitch,
viewHeight: canvasViewSize.height,
minPitch: minPitch,
maxPitch: maxPitch,
standardPitchStickViewHeight: standardPitchStickViewHeight)
if y == nil {
Log.errorText(text: "y is invalid, at calculated ui info step", tag: logTag)
}
let yValue = (y != nil) ? y! : (canvasViewSize.height >= 0 ? canvasViewSize.height : 0)
let debugInfo = DebugInfo(originalPitch: pitch,
pitch: voicePitch,
hitedInfo: hitedInfo,
progress: progress)
invokeScoringMachine(didUpdateCursor: yValue, showAnimation: showAnimation, debugInfo: debugInfo)
}
private func _dragBegain() {
isDragging = true
}
private func _dragDidEnd(position: Int) {
guard let index = findCurrentIndexOfLine(progress: position, lineEndTimes: lineEndTimes) else {
return
}
let indexOfLine = index-1
cumulativeScore = calculatedCumulativeScore(indexOfLine: indexOfLine, lineScores: lineScores)
Log.debug(text: "== dragDidEnd cumulativeScore:\(cumulativeScore)", tag: "drag")
if index >= 0, index < lineEndTimes.count, let data = lyricData {
toneScores = data.lines[index].tones.map({ ToneScoreModel(tone: $0, score: 0) })
for offset in index..<lineEndTimes.count {
lineScores[offset] = 0
}
}
progress = position
currentHighlightInfos = []
isDragging = false
}
private func resetToneScores(position: Int) {
guard let index = findCurrentIndexOfLine(progress: position, lineEndTimes: lineEndTimes) else {
return
}
if index >= 0, index < lineEndTimes.count, let data = lyricData {
toneScores = data.lines[index].tones.map({ ToneScoreModel(tone: $0, score: 0) })
for offset in index..<lineEndTimes.count {
lineScores[offset] = 0
}
}
currentHighlightInfos = []
Log.info(text: "resetToneScores", tag: logTag)
}
private func _reset() {
cumulativeScore = 0
lyricData = nil
currentVisiableInfos = []
currentHighlightInfos = []
dataList = []
lineEndTimes = []
cumulativeScore = 0
currentIndexOfLine = 0
lineScores = []
toneScores = []
progress = 0
minPitch = 0
maxPitch = 0
voiceChanger.reset()
}
private func handleProgress() {
///
let (visiableDrawInfos, highlightDrawInfos, visiableInfos, highlightInfos) = makeInfos(progress: progress,
dataList: dataList,
currentHighlightInfos: currentHighlightInfos,
defaultPitchCursorX: defaultPitchCursorX,
widthPreMs: widthPreMs,
canvasViewSize: canvasViewSize,
standardPitchStickViewHeight: standardPitchStickViewHeight,
minPitch: minPitch,
maxPitch: maxPitch)
currentVisiableInfos = visiableInfos
currentHighlightInfos = highlightInfos
invokeScoringMachine(didUpdateDraw: visiableDrawInfos, highlightInfos: highlightDrawInfos)
guard let index = findCurrentIndexOfLine(progress: progress, lineEndTimes: lineEndTimes) else {
return
}
if currentIndexOfLine != index {
if index - currentIndexOfLine == 1 { /** , **/
didLineEnd(indexOfLineEnd: currentIndexOfLine)
}
Log.debug(text: "currentIndexOfLine: \(index) from old: \(currentIndexOfLine)", tag: "drag")
currentIndexOfLine = index
}
}
private func didLineEnd(indexOfLineEnd: Int) {
guard let data = lyricData, indexOfLineEnd <= data.lines.count else {
return
}
let lineScore = scoreAlgorithm.getLineScore(with: toneScores)
lineScores[indexOfLineEnd] = lineScore
cumulativeScore = calculatedCumulativeScore(indexOfLine: indexOfLineEnd,
lineScores: lineScores)
Log.debug(text: "score didLineEnd indexOfLineEnd: \(indexOfLineEnd) \(lineScore) \(lineScores) cumulativeScore:\(cumulativeScore)", tag: logTag)
invokeScoringMachine(didFinishLineWith: data.lines[indexOfLineEnd],
score: lineScore,
cumulativeScore: cumulativeScore,
lineIndex: indexOfLineEnd,
lineCount: data.lines.count)
let nextIndex = indexOfLineEnd + 1
if nextIndex < data.lines.count {
toneScores = data.lines[nextIndex].tones.map({ ToneScoreModel(tone: $0, score: 0) })
}
}
}

View File

@@ -0,0 +1,36 @@
//
// ConsoleView.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/30.
//
import UIKit
/// use for debug only
class ConsoleView: UIView {
private let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.black.withAlphaComponent(0.2)
label.numberOfLines = 0
label.textColor = .white
label.font = .systemFont(ofSize: 9)
addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
label.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(text: String) {
label.text = text
}
}

View File

@@ -0,0 +1,214 @@
//
// LocalPitchView.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/4.
//
import UIKit
class LocalPitchView: UIView {
private let emitter = Emitter()
private let bgView = UIImageView()
private let verticalLineView = UIImageView()
private let indicatedView = UIImageView()
private var indicatedCenterYConstant: CGFloat = 0.0
static let scoreAnimateWidth: CGFloat = 30
///
var defaultPitchCursorX: CGFloat = 100
///
var particleEffectHidden: Bool = false
/** (X) 线
- 0线线
- 0:
- 0 **/
var localPitchCursorOffsetX: CGFloat = -3 { didSet { updateUI() } }
///
var localPitchCursorImage: UIImage? = nil { didSet { updateUI() } }
var emitterImages: [UIImage]? {
didSet {
emitter.images = emitterImages
}
}
private var indicatedViewCenterYConstraint, indicatedViewCenterXConstraint: NSLayoutConstraint!
fileprivate let logTag = "LocalPitchView"
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
bgView.image = Bundle.currentBundle.image(name: "bg_scoring_left")
verticalLineView.image = Bundle.currentBundle.image(name: "icon_vertical_line")
indicatedView.image = Bundle.currentBundle.image(name: "icon_trangle")
backgroundColor = .clear
addSubview(bgView)
addSubview(verticalLineView)
addSubview(indicatedView)
layer.addSublayer(emitter.layer)
bgView.translatesAutoresizingMaskIntoConstraints = false
verticalLineView.translatesAutoresizingMaskIntoConstraints = false
indicatedView.translatesAutoresizingMaskIntoConstraints = false
bgView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
bgView.rightAnchor.constraint(equalTo: rightAnchor, constant: -1 * LocalPitchView.scoreAnimateWidth).isActive = true
bgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
bgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
verticalLineView.rightAnchor.constraint(equalTo: rightAnchor, constant: -1 * (LocalPitchView.scoreAnimateWidth - 0.5)).isActive = true
verticalLineView.topAnchor.constraint(equalTo: topAnchor).isActive = true
verticalLineView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
indicatedViewCenterXConstraint = indicatedView.centerXAnchor.constraint(equalTo: verticalLineView.centerXAnchor, constant: localPitchCursorOffsetX)
indicatedViewCenterYConstraint = indicatedView.centerYAnchor.constraint(equalTo: bottomAnchor, constant: 0)
indicatedViewCenterXConstraint.isActive = true
indicatedViewCenterYConstraint.isActive = true
}
private func updateUI() {
indicatedViewCenterXConstraint.constant = localPitchCursorOffsetX
indicatedView.image = localPitchCursorImage ?? Bundle.currentBundle.image(name: "icon_trangle")
}
///
/// - Parameter y: topbottom
func setIndicatedViewY(y: CGFloat) {
let constant = (bounds.height - y) * -1
let duration: TimeInterval = indicatedCenterYConstant < constant ? 0.15 : 0.05
indicatedCenterYConstant = constant
indicatedViewCenterYConstraint.constant = constant
UIView.animate(withDuration: duration, delay: 0, options: []) { [weak self] in
self?.layoutIfNeeded()
}
emitter.setupEmitterPoint(point: .init(x: defaultPitchCursorX-3, y: y))
}
func startEmitter() {
if particleEffectHidden { return }
emitter.start()
}
func stopEmitter() {
emitter.stop()
}
func reset() {
setIndicatedViewY(y: bounds.height)
stopEmitter()
emitter.reset()
}
}
class Emitter {
var layer = CAEmitterLayer()
var images: [UIImage]? {
didSet {
updateLayer()
}
}
private var count = 0
private var lastPoint: CGPoint = .zero
private let logTag = "Emitter"
var defaultImages: [UIImage] {
var list = [UIImage]()
for i in 1...8 {
if let image = Bundle.currentBundle.image(name: "star\(i)") {
list.append(image)
}
else {
Log.error(error: "image == nil", tag: logTag)
}
}
return list
}
init() {
updateLayer()
}
func updateLayer() {
let superLayer = layer.superlayer
layer.removeFromSuperlayer()
layer = CAEmitterLayer()
superLayer?.addSublayer(layer)
layer.emitterPosition = .zero
layer.preservesDepth = true
layer.renderMode = .oldestLast
layer.masksToBounds = false
layer.emitterMode = .points
layer.emitterShape = .circle
layer.birthRate = 0
layer.emitterPosition = lastPoint
let imgs = (images != nil) ? images! : defaultImages
let count = imgs.count
layer.emitterCells = imgs.enumerated().map({ Emitter.createEmitterCell(name: "cell", image: $0.1, birthRate: count) })
}
func setCount() {
count += 1
if count >= 150 {
count = 0
updateLayer()
}
}
func setupEmitterPoint(point: CGPoint) {
lastPoint = point
layer.emitterPosition = point
}
func start() {
setCount()
layer.birthRate = 1
}
func stop() {
setCount()
layer.birthRate = 0
}
func reset(){
count = 0
updateLayer()
}
static func createEmitterCell(name: String, image: UIImage, birthRate: Int) -> CAEmitterCell {
/// ,
let cell = CAEmitterCell()
///
cell.velocity = 1
cell.velocityRange = 1
///
cell.scale = 1
cell.scaleRange = 0.5
///
cell.emissionLongitude = CGFloat.pi * 3
cell.emissionRange = CGFloat.pi / 6
///
cell.lifetime = 100
cell.lifetimeRange = 0
///
cell.spin = CGFloat.pi / 2
cell.spinRange = CGFloat.pi / 4
///
cell.birthRate = 4
cell.alphaRange = 0.75
cell.alphaSpeed = -0.35
///
cell.velocity = 90
cell.name = name
cell.isEnabled = true
cell.contents = image.cgImage
return cell
}
}

View File

@@ -0,0 +1,104 @@
//
// ScoringCanvasView.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/3.
//
import UIKit
class ScoringCanvasView: UIView {
///
var defaultPitchCursorX: CGFloat = 100
/// 线
var standardPitchStickViewHeight: CGFloat = 3
/// 线
var movingSpeedFactor: CGFloat = 120
/// 线
var standardPitchStickViewColor: UIColor = .gray
/// 线
var standardPitchStickViewHighlightColor: UIColor = .orange
fileprivate var standardInfos = [DrawInfo]()
fileprivate var highlightInfos = [DrawInfo]()
fileprivate var widthPreMs: CGFloat { movingSpeedFactor / 1000 }
override func draw(_ rect: CGRect) {
drawStaff()
drawStandardInfos()
drawHighlightInfos()
}
func draw(standardInfos: [DrawInfo],
highlightInfos: [DrawInfo]) {
self.standardInfos = standardInfos
self.highlightInfos = highlightInfos
setNeedsDisplay()
}
func reset() {
self.standardInfos = []
self.highlightInfos = []
setNeedsDisplay()
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Draw
extension ScoringCanvasView {
/// 线
fileprivate func drawStaff() {
let height = bounds.height
let width = bounds.width
let lineHeight: CGFloat = 1
let spaceY = (height - lineHeight * 5) / 4
for i in 0...5 {
let y = CGFloat(i) * (spaceY + lineHeight)
let rect = CGRect(x: 0, y: y, width: width, height: lineHeight)
let linePath = UIBezierPath(rect: rect)
UIColor.white.withAlphaComponent(0.08).setFill()
linePath.fill()
}
}
fileprivate func drawStandardInfos() {
drawInfosStandrad(infos: standardInfos, fillColor: standardPitchStickViewColor)
}
fileprivate func drawHighlightInfos() {
drawInfosStandrad(infos: highlightInfos, fillColor: standardPitchStickViewHighlightColor)
}
private func drawInfosHighlight(infos: [DrawInfo], fillColor: UIColor) {
for info in infos {
let rect = info.rect
let gradient = CAGradientLayer()
gradient.frame = rect
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
layer.addSublayer(gradient)
}
}
private func drawInfosStandrad(infos: [DrawInfo], fillColor: UIColor) {
for info in infos {
let rect = info.rect
let path = UIBezierPath(roundedRect: rect, cornerRadius: standardPitchStickViewHeight/2)
fillColor.setFill()
path.fill()
}
}
}
extension ScoringCanvasView {
typealias DrawInfo = ScoringMachine.DrawInfo
}

View File

@@ -0,0 +1,21 @@
//
// ScoringView+Events.swift
// AgoraLyricsScore
//
// Created by ZYP on 2023/1/13.
//
import Foundation
protocol ScoringViewDelegate: NSObjectProtocol {
///
func scoringView(_ view: ScoringView,
didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int)
/// UI
func scoringViewShouldUpdateViewLayout(view: ScoringView)
}

View File

@@ -0,0 +1,206 @@
//
// ScoringView.swift
// NewApi
//
// Created by ZYP on 2022/11/22.
//
import UIKit
public class ScoringView: UIView {
///
@objc public var viewHeight: CGFloat = 120 { didSet { updateUI() } }
///
@objc public var topSpaces: CGFloat = 0 { didSet { updateUI() } }
///
@objc public var defaultPitchCursorX: CGFloat = 100 { didSet { updateUI() } }
/// 线
@objc public var standardPitchStickViewHeight: CGFloat = 3 { didSet { updateUI() } }
/// 线
@objc public var movingSpeedFactor: CGFloat = 120 { didSet { updateUI() } }
/// 线
@objc public var standardPitchStickViewColor: UIColor = .gray { didSet { updateUI() } }
/// 线
@objc public var standardPitchStickViewHighlightColor: UIColor = .colorWithHex(hexStr: "#FF8AB4") { didSet { updateUI() } }
/** (X) 线
- 0线
- 0:
- 0 **/
@objc public var localPitchCursorOffsetX: CGFloat = -3 { didSet { updateUI() } }
///
@objc public var localPitchCursorImage: UIImage? = nil { didSet { updateUI() } }
///
@objc public var particleEffectHidden: Bool = false { didSet { updateUI() } }
/// 使
@objc public var emitterImages: [UIImage]? { didSet { updateUI() } }
/// 0-1
@objc public var hitScoreThreshold: Float = 0.7 { didSet { updateUI() } }
/// use for debug only
@objc public var showDebugView = false { didSet { updateUI() } }
var scoreLevel = 15 { didSet { updateUI() } }
var scoreCompensationOffset = 0 { didSet { updateUI() } }
var progress: Int = 0 { didSet { updateProgress() } }
fileprivate let localPitchView = LocalPitchView()
fileprivate let canvasView = ScoringCanvasView()
/// use for debug only
fileprivate let consoleView = ConsoleView()
private var canvasViewHeightConstraint, localPitchViewWidthConstraint: NSLayoutConstraint!
fileprivate let scoringMachine = ScoringMachine()
weak var delegate: ScoringViewDelegate?
public override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
updateUI()
scoringMachine.delegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///
@objc public func getCumulativeScore() -> Int {
scoringMachine.getCumulativeScore()
}
/// stop Animation and reset position of Cursor
@objc public func forceStopIndicatorAnimationWhenReachingContinuousZeros() {
localPitchView.reset()
}
func setLyricData(data: LyricModel?) {
scoringMachine.setLyricData(data: data)
}
func setPitch(pitch: Double) {
scoringMachine.setPitch(pitch: pitch)
}
func setScoreAlgorithm(algorithm: IScoreAlgorithm) {
scoringMachine.scoreAlgorithm = algorithm
}
func dragBegain() {
scoringMachine.dragBegain()
}
func dragDidEnd(position: Int) {
scoringMachine.dragDidEnd(position: position)
}
func reset() {
scoringMachine.reset()
localPitchView.reset()
canvasView.reset()
}
private func updateProgress() {
scoringMachine.setProgress(progress: progress)
}
private func setupUI() {
addSubview(canvasView)
addSubview(localPitchView)
canvasView.translatesAutoresizingMaskIntoConstraints = false
localPitchView.translatesAutoresizingMaskIntoConstraints = false
canvasView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
canvasView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
canvasView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
canvasViewHeightConstraint = canvasView.heightAnchor.constraint(equalToConstant: viewHeight)
canvasViewHeightConstraint.isActive = true
localPitchView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
localPitchView.topAnchor.constraint(equalTo: canvasView.topAnchor).isActive = true
localPitchView.bottomAnchor.constraint(equalTo: canvasView.bottomAnchor).isActive = true
let width = defaultPitchCursorX + LocalPitchView.scoreAnimateWidth /** 线1 **/
localPitchViewWidthConstraint = localPitchView.widthAnchor.constraint(equalToConstant: width)
localPitchViewWidthConstraint.isActive = true
}
private func updateUI() {
canvasView.defaultPitchCursorX = defaultPitchCursorX
canvasView.standardPitchStickViewHeight = standardPitchStickViewHeight
canvasView.movingSpeedFactor = movingSpeedFactor
canvasView.standardPitchStickViewColor = standardPitchStickViewColor
canvasView.standardPitchStickViewHighlightColor = standardPitchStickViewHighlightColor
localPitchView.particleEffectHidden = particleEffectHidden
localPitchView.emitterImages = emitterImages
localPitchView.defaultPitchCursorX = defaultPitchCursorX
localPitchView.localPitchCursorOffsetX = localPitchCursorOffsetX
localPitchView.localPitchCursorImage = localPitchCursorImage
let width = defaultPitchCursorX + LocalPitchView.scoreAnimateWidth /** 线1 **/
localPitchViewWidthConstraint.constant = width
canvasViewHeightConstraint.constant = viewHeight
scoringMachine.defaultPitchCursorX = defaultPitchCursorX
scoringMachine.standardPitchStickViewHeight = standardPitchStickViewHeight
scoringMachine.movingSpeedFactor = movingSpeedFactor
scoringMachine.hitScoreThreshold = hitScoreThreshold
scoringMachine.scoreLevel = scoreLevel
scoringMachine.scoreCompensationOffset = scoreCompensationOffset
delegate?.scoringViewShouldUpdateViewLayout(view: self)
if showDebugView {
if !subviews.contains(consoleView) {
addSubview(consoleView)
consoleView.translatesAutoresizingMaskIntoConstraints = false
consoleView.widthAnchor.constraint(equalToConstant: 80).isActive = true
consoleView.heightAnchor.constraint(equalToConstant: 80).isActive = true
consoleView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
consoleView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
else {
consoleView.removeFromSuperview()
}
}
}
// MARK: - ScoringMachineDelegate
extension ScoringView: ScoringMachineDelegate {
func sizeOfCanvasView(_ scoringMachine: ScoringMachine) -> CGSize {
return canvasView.bounds.size
}
func scoringMachine(_ scoringMachine: ScoringMachine,
didUpdateDraw standardInfos: [ScoringMachine.DrawInfo],
highlightInfos: [ScoringMachine.DrawInfo]) {
canvasView.draw(standardInfos: standardInfos,
highlightInfos: highlightInfos)
}
func scoringMachine(_ scoringMachine: ScoringMachine,
didUpdateCursor centerY: CGFloat,
showAnimation: Bool,
debugInfo: ScoringMachine.DebugInfo) {
localPitchView.setIndicatedViewY(y: centerY)
showAnimation ? localPitchView.startEmitter() : localPitchView.stopEmitter()
if showDebugView {
let text = "y: \(Float(centerY)) \npitch: \(debugInfo.pitch.keep2) \nani: \(showAnimation) \nw:\(debugInfo.hitedInfo?.word ?? "") \nstd:\(debugInfo.hitedInfo?.pitch ?? 0) progress: \(debugInfo.progress)"
consoleView.set(text: text)
}
}
func scoringMachine(_ scoringMachine: ScoringMachine,
didFinishLineWith model: LyricLineModel,
score: Int,
cumulativeScore: Int,
lineIndex: Int,
lineCount: Int) {
delegate?.scoringView(self,
didFinishLineWith: model,
score: score,
cumulativeScore: cumulativeScore,
lineIndex: lineIndex,
lineCount: lineCount)
}
}

View File

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "bg_scoring_left@2X.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "bg_scoring_left@3X.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

View File

@@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "icon_trangle@2X.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "icon_trangle@3X.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 B

View File

@@ -0,0 +1,22 @@
{
"images" : [
{
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "icon_vertical_line@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "icon_vertical_line@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 B

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "star1.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "star1@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "star1@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 550 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 838 B

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "star2.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "star2@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "star2@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 828 B

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "star3.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "star3@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "star3@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 537 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 849 B

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "star4.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "star4@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "star4@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 534 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 882 B

View File

@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "star5.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "star5@2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "star5@3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 B

Some files were not shown because too many files have changed in this diff Show More