├── README.md
├── jfc.dmg
├── jj.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ └── IDEWorkspaceChecks.plist
├── xcshareddata
│ └── xcschemes
│ │ └── jj.xcscheme
└── xcuserdata
│ └── fancl.xcuserdatad
│ ├── xcdebugger
│ └── Breakpoints_v2.xcbkptlist
│ └── xcschemes
│ └── xcschememanagement.plist
├── jj
├── AFNetworking
│ ├── AFNetworking
│ │ ├── AFCompatibilityMacros.h
│ │ ├── AFHTTPSessionManager.h
│ │ ├── AFHTTPSessionManager.m
│ │ ├── AFNetworkReachabilityManager.h
│ │ ├── AFNetworkReachabilityManager.m
│ │ ├── AFNetworking.h
│ │ ├── AFSecurityPolicy.h
│ │ ├── AFSecurityPolicy.m
│ │ ├── AFURLRequestSerialization.h
│ │ ├── AFURLRequestSerialization.m
│ │ ├── AFURLResponseSerialization.h
│ │ ├── AFURLResponseSerialization.m
│ │ ├── AFURLSessionManager.h
│ │ └── AFURLSessionManager.m
│ ├── LICENSE
│ ├── README.md
│ └── UIKit+AFNetworking
│ │ ├── AFAutoPurgingImageCache.h
│ │ ├── AFAutoPurgingImageCache.m
│ │ ├── AFImageDownloader.h
│ │ ├── AFImageDownloader.m
│ │ ├── AFNetworkActivityIndicatorManager.h
│ │ ├── AFNetworkActivityIndicatorManager.m
│ │ ├── UIActivityIndicatorView+AFNetworking.h
│ │ ├── UIActivityIndicatorView+AFNetworking.m
│ │ ├── UIButton+AFNetworking.h
│ │ ├── UIButton+AFNetworking.m
│ │ ├── UIImageView+AFNetworking.h
│ │ ├── UIImageView+AFNetworking.m
│ │ ├── UIKit+AFNetworking.h
│ │ ├── UIProgressView+AFNetworking.h
│ │ ├── UIProgressView+AFNetworking.m
│ │ ├── UIRefreshControl+AFNetworking.h
│ │ ├── UIRefreshControl+AFNetworking.m
│ │ ├── WKWebView+AFNetworking.h
│ │ └── WKWebView+AFNetworking.m
├── AppDelegate.h
├── AppDelegate.m
├── Assets.xcassets
│ ├── AppIcon.appiconset
│ │ ├── 20200722182459_29940_128.png
│ │ ├── 20200722182459_29940_16.png
│ │ ├── 20200722182459_29940_256-1.png
│ │ ├── 20200722182459_29940_256.png
│ │ ├── 20200722182459_29940_32-1.png
│ │ ├── 20200722182459_29940_32.png
│ │ ├── 20200722182459_29940_64.png
│ │ ├── Contents.json
│ │ ├── icon-512.png
│ │ ├── icon-512@2x.png
│ │ └── icon-513.png
│ ├── Contents.json
│ ├── down.imageset
│ │ ├── Contents.json
│ │ ├── icon_下降箭头 (1).png
│ │ └── icon_下降箭头.png
│ ├── eey.imageset
│ │ ├── Contents.json
│ │ └── eey.png
│ ├── eye.imageset
│ │ ├── Contents.json
│ │ └── eye.png
│ └── up.imageset
│ │ ├── Contents.json
│ │ ├── 上升箭头 (1).png
│ │ └── 上升箭头.png
├── Base.lproj
│ └── Main.storyboard
├── FundJZWC.h
├── FundJZWC.m
├── FundJZWC.xib
├── FundModel.h
├── FundModel.m
├── Info.plist
├── InfoPlist.strings
├── NSMenuTableView.h
├── NSMenuTableView.m
├── ViewController.h
├── ViewController.m
├── jj.entitlements
├── main.m
└── tool
│ ├── AlertTool.h
│ ├── AlertTool.m
│ ├── DataManager.h
│ ├── DataManager.m
│ ├── JTool.h
│ ├── JTool.m
│ ├── NetClient.h
│ ├── NetClient.m
│ ├── NetTool.h
│ ├── NetTool.m
│ ├── TimeTool.h
│ └── TimeTool.m
├── resource
├── kuoluo.png
├── 删除.png
├── 持有.png
├── 排序.png
├── 榜单.png
├── 热心基民.jpg
└── 观察.png
└── 基富贵.zip
/README.md:
--------------------------------------------------------------------------------
1 | # jfc
2 | 苹果Mac端基金管理查看平台(数据来源天天基金)
3 |
4 | ## 基金小大湿
5 | #### 榜单区
6 | 
7 | #### 观察区
8 | 
9 | #### 持仓区
10 | 
11 |
12 |
13 | ### 都有啥功能啊
14 |
15 | * 天天基金月收益榜三十全览
16 | * 待考察基金一览
17 | * 已买入基金一览
18 | * 三大指数一览
19 | * 添加自选基金
20 | * 删除自选基金
21 | * 拖拽排序
22 | * 计算上日持仓净值
23 | * 手动/自动刷新
24 | * 最后你以为我是闲的?不,因为目前还没发现哪个Mac端软件有此类功能
25 |
26 | ### 安装
27 |
28 | **1. 普通安装**
29 |
30 | * 直接安dmg或双击'基富贵'
31 |
32 | **2. 非普通安装**
33 |
34 | * 直接跑代码
35 |
36 | ---
37 |
38 | ### 使用说明书
39 |
40 | 本luer设计了三套数据源模式:
41 | #### 榜单区:数据源自天天基金月收益榜单前三十位,供大家分析整体基市趋势行情
42 | #### 观察区:想买入但是未买入的基金,可以放在这里相机而行
43 | #### 持有区:自己已经买入的基金,可输入持仓金额(是钱不是份额)查看实时预估收益
44 | * 注:三套数据源相互隔离,互不影响
45 |
46 | ---
47 |
48 | ### 好饿,早知道不做iOS了.jpg
49 |
50 | 各位小老板如果觉得好用,麻烦用你发财的小手手点颗✨✨✨✨✨✨吧 ,你的star是我持续更新的不懈动力!
51 |
52 | ---
53 |
54 | ### Other
55 |
56 | #### 热心基民交流群
57 |
58 | 
59 |
60 | ---
61 |
62 | #### 啥?听说大涨了??请作者喝杯阔落😏
63 | 
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/jfc.dmg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jfc.dmg
--------------------------------------------------------------------------------
/jj.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/jj.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/jj.xcodeproj/xcshareddata/xcschemes/jj.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
33 |
44 |
46 |
52 |
53 |
54 |
55 |
61 |
63 |
69 |
70 |
71 |
72 |
74 |
75 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/jj.xcodeproj/xcuserdata/fancl.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
9 |
21 |
22 |
23 |
25 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/jj.xcodeproj/xcuserdata/fancl.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | jj.xcscheme_^#shared#^_
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 80A1282324C144BF008BD87E
16 |
17 | primary
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFCompatibilityMacros.h:
--------------------------------------------------------------------------------
1 | // AFCompatibilityMacros.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #ifndef AFCompatibilityMacros_h
23 | #define AFCompatibilityMacros_h
24 |
25 | #ifdef API_AVAILABLE
26 | #define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__)
27 | #else
28 | #define AF_API_AVAILABLE(...)
29 | #endif // API_AVAILABLE
30 |
31 | #ifdef API_UNAVAILABLE
32 | #define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__)
33 | #else
34 | #define AF_API_UNAVAILABLE(...)
35 | #endif // API_UNAVAILABLE
36 |
37 | #if __has_warning("-Wunguarded-availability-new")
38 | #define AF_CAN_USE_AT_AVAILABLE 1
39 | #else
40 | #define AF_CAN_USE_AT_AVAILABLE 0
41 | #endif
42 |
43 | #if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000))
44 | #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0
45 | #else
46 | #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1
47 | #endif
48 |
49 | #endif /* AFCompatibilityMacros_h */
50 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h:
--------------------------------------------------------------------------------
1 | // AFNetworkReachabilityManager.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #if !TARGET_OS_WATCH
25 | #import
26 |
27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
28 | AFNetworkReachabilityStatusUnknown = -1,
29 | AFNetworkReachabilityStatusNotReachable = 0,
30 | AFNetworkReachabilityStatusReachableViaWWAN = 1,
31 | AFNetworkReachabilityStatusReachableViaWiFi = 2,
32 | };
33 |
34 | NS_ASSUME_NONNULL_BEGIN
35 |
36 | /**
37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
38 |
39 | 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.
40 |
41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
42 |
43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
44 | */
45 | @interface AFNetworkReachabilityManager : NSObject
46 |
47 | /**
48 | The current network reachability status.
49 | */
50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
51 |
52 | /**
53 | Whether or not the network is currently reachable.
54 | */
55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
56 |
57 | /**
58 | Whether or not the network is currently reachable via WWAN.
59 | */
60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
61 |
62 | /**
63 | Whether or not the network is currently reachable via WiFi.
64 | */
65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
66 |
67 | ///---------------------
68 | /// @name Initialization
69 | ///---------------------
70 |
71 | /**
72 | Returns the shared network reachability manager.
73 | */
74 | + (instancetype)sharedManager;
75 |
76 | /**
77 | Creates and returns a network reachability manager with the default socket address.
78 |
79 | @return An initialized network reachability manager, actively monitoring the default socket address.
80 | */
81 | + (instancetype)manager;
82 |
83 | /**
84 | Creates and returns a network reachability manager for the specified domain.
85 |
86 | @param domain The domain used to evaluate network reachability.
87 |
88 | @return An initialized network reachability manager, actively monitoring the specified domain.
89 | */
90 | + (instancetype)managerForDomain:(NSString *)domain;
91 |
92 | /**
93 | Creates and returns a network reachability manager for the socket address.
94 |
95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
96 |
97 | @return An initialized network reachability manager, actively monitoring the specified socket address.
98 | */
99 | + (instancetype)managerForAddress:(const void *)address;
100 |
101 | /**
102 | Initializes an instance of a network reachability manager from the specified reachability object.
103 |
104 | @param reachability The reachability object to monitor.
105 |
106 | @return An initialized network reachability manager, actively monitoring the specified reachability.
107 | */
108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
109 |
110 | /**
111 | * Unavailable initializer
112 | */
113 | + (instancetype)new NS_UNAVAILABLE;
114 |
115 | /**
116 | * Unavailable initializer
117 | */
118 | - (instancetype)init NS_UNAVAILABLE;
119 |
120 | ///--------------------------------------------------
121 | /// @name Starting & Stopping Reachability Monitoring
122 | ///--------------------------------------------------
123 |
124 | /**
125 | Starts monitoring for changes in network reachability status.
126 | */
127 | - (void)startMonitoring;
128 |
129 | /**
130 | Stops monitoring for changes in network reachability status.
131 | */
132 | - (void)stopMonitoring;
133 |
134 | ///-------------------------------------------------
135 | /// @name Getting Localized Reachability Description
136 | ///-------------------------------------------------
137 |
138 | /**
139 | Returns a localized string representation of the current network reachability status.
140 | */
141 | - (NSString *)localizedNetworkReachabilityStatusString;
142 |
143 | ///---------------------------------------------------
144 | /// @name Setting Network Reachability Change Callback
145 | ///---------------------------------------------------
146 |
147 | /**
148 | Sets a callback to be executed when the network availability of the `baseURL` host changes.
149 |
150 | @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`.
151 | */
152 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
153 |
154 | @end
155 |
156 | ///----------------
157 | /// @name Constants
158 | ///----------------
159 |
160 | /**
161 | ## Network Reachability
162 |
163 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
164 |
165 | enum {
166 | AFNetworkReachabilityStatusUnknown,
167 | AFNetworkReachabilityStatusNotReachable,
168 | AFNetworkReachabilityStatusReachableViaWWAN,
169 | AFNetworkReachabilityStatusReachableViaWiFi,
170 | }
171 |
172 | `AFNetworkReachabilityStatusUnknown`
173 | The `baseURL` host reachability is not known.
174 |
175 | `AFNetworkReachabilityStatusNotReachable`
176 | The `baseURL` host cannot be reached.
177 |
178 | `AFNetworkReachabilityStatusReachableViaWWAN`
179 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
180 |
181 | `AFNetworkReachabilityStatusReachableViaWiFi`
182 | The `baseURL` host can be reached via a Wi-Fi connection.
183 |
184 | ### Keys for Notification UserInfo Dictionary
185 |
186 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
187 |
188 | `AFNetworkingReachabilityNotificationStatusItem`
189 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
190 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
191 | */
192 |
193 | ///--------------------
194 | /// @name Notifications
195 | ///--------------------
196 |
197 | /**
198 | Posted when network reachability changes.
199 | 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.
200 |
201 | @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 ` to the header prefix of the project (`Prefix.pch`).
202 | */
203 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
204 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
205 |
206 | ///--------------------
207 | /// @name Functions
208 | ///--------------------
209 |
210 | /**
211 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
212 | */
213 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
214 |
215 | NS_ASSUME_NONNULL_END
216 | #endif
217 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m:
--------------------------------------------------------------------------------
1 | // AFNetworkReachabilityManager.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "AFNetworkReachabilityManager.h"
23 | #if !TARGET_OS_WATCH
24 |
25 | #import
26 | #import
27 | #import
28 | #import
29 | #import
30 |
31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
33 |
34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
35 | typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status);
36 |
37 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) {
38 | switch (status) {
39 | case AFNetworkReachabilityStatusNotReachable:
40 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil);
41 | case AFNetworkReachabilityStatusReachableViaWWAN:
42 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil);
43 | case AFNetworkReachabilityStatusReachableViaWiFi:
44 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil);
45 | case AFNetworkReachabilityStatusUnknown:
46 | default:
47 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil);
48 | }
49 | }
50 |
51 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
52 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
53 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
54 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
55 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
56 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
57 |
58 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
59 | if (isNetworkReachable == NO) {
60 | status = AFNetworkReachabilityStatusNotReachable;
61 | }
62 | #if TARGET_OS_IPHONE
63 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
64 | status = AFNetworkReachabilityStatusReachableViaWWAN;
65 | }
66 | #endif
67 | else {
68 | status = AFNetworkReachabilityStatusReachableViaWiFi;
69 | }
70 |
71 | return status;
72 | }
73 |
74 | /**
75 | * Queue a status change notification for the main thread.
76 | *
77 | * This is done to ensure that the notifications are received in the same order
78 | * as they are sent. If notifications are sent directly, it is possible that
79 | * a queued notification (for an earlier status condition) is processed after
80 | * the later update, resulting in the listener being left in the wrong state.
81 | */
82 | static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) {
83 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
84 | dispatch_async(dispatch_get_main_queue(), ^{
85 | AFNetworkReachabilityManager *manager = nil;
86 | if (block) {
87 | manager = block(status);
88 | }
89 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
90 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) };
91 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo];
92 | });
93 | }
94 |
95 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
96 | AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info);
97 | }
98 |
99 |
100 | static const void * AFNetworkReachabilityRetainCallback(const void *info) {
101 | return Block_copy(info);
102 | }
103 |
104 | static void AFNetworkReachabilityReleaseCallback(const void *info) {
105 | if (info) {
106 | Block_release(info);
107 | }
108 | }
109 |
110 | @interface AFNetworkReachabilityManager ()
111 | @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
112 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
113 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
114 | @end
115 |
116 | @implementation AFNetworkReachabilityManager
117 |
118 | + (instancetype)sharedManager {
119 | static AFNetworkReachabilityManager *_sharedManager = nil;
120 | static dispatch_once_t onceToken;
121 | dispatch_once(&onceToken, ^{
122 | _sharedManager = [self manager];
123 | });
124 |
125 | return _sharedManager;
126 | }
127 |
128 | + (instancetype)managerForDomain:(NSString *)domain {
129 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
130 |
131 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
132 |
133 | CFRelease(reachability);
134 |
135 | return manager;
136 | }
137 |
138 | + (instancetype)managerForAddress:(const void *)address {
139 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
140 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
141 |
142 | CFRelease(reachability);
143 |
144 | return manager;
145 | }
146 |
147 | + (instancetype)manager
148 | {
149 | #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)
150 | struct sockaddr_in6 address;
151 | bzero(&address, sizeof(address));
152 | address.sin6_len = sizeof(address);
153 | address.sin6_family = AF_INET6;
154 | #else
155 | struct sockaddr_in address;
156 | bzero(&address, sizeof(address));
157 | address.sin_len = sizeof(address);
158 | address.sin_family = AF_INET;
159 | #endif
160 | return [self managerForAddress:&address];
161 | }
162 |
163 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
164 | self = [super init];
165 | if (!self) {
166 | return nil;
167 | }
168 |
169 | _networkReachability = CFRetain(reachability);
170 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
171 |
172 | return self;
173 | }
174 |
175 | - (instancetype)init
176 | {
177 | @throw [NSException exceptionWithName:NSGenericException
178 | reason:@"`-init` unavailable. Use `-initWithReachability:` instead"
179 | userInfo:nil];
180 | return nil;
181 | }
182 |
183 | - (void)dealloc {
184 | [self stopMonitoring];
185 |
186 | if (_networkReachability != NULL) {
187 | CFRelease(_networkReachability);
188 | }
189 | }
190 |
191 | #pragma mark -
192 |
193 | - (BOOL)isReachable {
194 | return [self isReachableViaWWAN] || [self isReachableViaWiFi];
195 | }
196 |
197 | - (BOOL)isReachableViaWWAN {
198 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN;
199 | }
200 |
201 | - (BOOL)isReachableViaWiFi {
202 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi;
203 | }
204 |
205 | #pragma mark -
206 |
207 | - (void)startMonitoring {
208 | [self stopMonitoring];
209 |
210 | if (!self.networkReachability) {
211 | return;
212 | }
213 |
214 | __weak __typeof(self)weakSelf = self;
215 | AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) {
216 | __strong __typeof(weakSelf)strongSelf = weakSelf;
217 |
218 | strongSelf.networkReachabilityStatus = status;
219 | if (strongSelf.networkReachabilityStatusBlock) {
220 | strongSelf.networkReachabilityStatusBlock(status);
221 | }
222 |
223 | return strongSelf;
224 | };
225 |
226 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
227 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
228 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
229 |
230 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
231 | SCNetworkReachabilityFlags flags;
232 | if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) {
233 | AFPostReachabilityStatusChange(flags, callback);
234 | }
235 | });
236 | }
237 |
238 | - (void)stopMonitoring {
239 | if (!self.networkReachability) {
240 | return;
241 | }
242 |
243 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
244 | }
245 |
246 | #pragma mark -
247 |
248 | - (NSString *)localizedNetworkReachabilityStatusString {
249 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
250 | }
251 |
252 | #pragma mark -
253 |
254 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
255 | self.networkReachabilityStatusBlock = block;
256 | }
257 |
258 | #pragma mark - NSKeyValueObserving
259 |
260 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
261 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
262 | return [NSSet setWithObject:@"networkReachabilityStatus"];
263 | }
264 |
265 | return [super keyPathsForValuesAffectingValueForKey:key];
266 | }
267 |
268 | @end
269 | #endif
270 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFNetworking.h:
--------------------------------------------------------------------------------
1 | // AFNetworking.h
2 | //
3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/)
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy
6 | // of this software and associated documentation files (the "Software"), to deal
7 | // in the Software without restriction, including without limitation the rights
8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | // copies of the Software, and to permit persons to whom the Software is
10 | // furnished to do so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in
13 | // all copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | // THE SOFTWARE.
22 |
23 | #import
24 | #import
25 | #import
26 |
27 | #ifndef _AFNETWORKING_
28 | #define _AFNETWORKING_
29 |
30 | #import "AFURLRequestSerialization.h"
31 | #import "AFURLResponseSerialization.h"
32 | #import "AFSecurityPolicy.h"
33 |
34 | #if !TARGET_OS_WATCH
35 | #import "AFNetworkReachabilityManager.h"
36 | #endif
37 |
38 | #import "AFURLSessionManager.h"
39 | #import "AFHTTPSessionManager.h"
40 |
41 | #endif /* _AFNETWORKING_ */
42 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFSecurityPolicy.h:
--------------------------------------------------------------------------------
1 | // AFSecurityPolicy.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 | #import
24 |
25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
26 | AFSSLPinningModeNone,
27 | AFSSLPinningModePublicKey,
28 | AFSSLPinningModeCertificate,
29 | };
30 |
31 | /**
32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
33 |
34 | 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.
35 | */
36 |
37 | NS_ASSUME_NONNULL_BEGIN
38 |
39 | @interface AFSecurityPolicy : NSObject
40 |
41 | /**
42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
43 | */
44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
45 |
46 | /**
47 | The certificates used to evaluate server trust according to the SSL pinning mode.
48 |
49 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
50 |
51 | @see policyWithPinningMode:withPinnedCertificates:
52 | */
53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates;
54 |
55 | /**
56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
57 | */
58 | @property (nonatomic, assign) BOOL allowInvalidCertificates;
59 |
60 | /**
61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
62 | */
63 | @property (nonatomic, assign) BOOL validatesDomainName;
64 |
65 | ///-----------------------------------------
66 | /// @name Getting Certificates from the Bundle
67 | ///-----------------------------------------
68 |
69 | /**
70 | 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`.
71 |
72 | @return The certificates included in the given bundle.
73 | */
74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle;
75 |
76 | ///-----------------------------------------
77 | /// @name Getting Specific Security Policies
78 | ///-----------------------------------------
79 |
80 | /**
81 | 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.
82 |
83 | @return The default security policy.
84 | */
85 | + (instancetype)defaultPolicy;
86 |
87 | ///---------------------
88 | /// @name Initialization
89 | ///---------------------
90 |
91 | /**
92 | Creates and returns a security policy with the specified pinning mode.
93 |
94 | Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead.
95 |
96 | @param pinningMode The SSL pinning mode.
97 |
98 | @return A new security policy.
99 |
100 | @see -policyWithPinningMode:withPinnedCertificates:
101 | */
102 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
103 |
104 | /**
105 | Creates and returns a security policy with the specified pinning mode.
106 |
107 | @param pinningMode The SSL pinning mode.
108 | @param pinnedCertificates The certificates to pin against.
109 |
110 | @return A new security policy.
111 |
112 | @see +certificatesInBundle:
113 | @see -pinnedCertificates
114 | */
115 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates;
116 |
117 | ///------------------------------
118 | /// @name Evaluating Server Trust
119 | ///------------------------------
120 |
121 | /**
122 | Whether or not the specified server trust should be accepted, based on the security policy.
123 |
124 | This method should be used when responding to an authentication challenge from a server.
125 |
126 | @param serverTrust The X.509 certificate trust of the server.
127 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated.
128 |
129 | @return Whether or not to trust the server.
130 | */
131 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
132 | forDomain:(nullable NSString *)domain;
133 |
134 | @end
135 |
136 | NS_ASSUME_NONNULL_END
137 |
138 | ///----------------
139 | /// @name Constants
140 | ///----------------
141 |
142 | /**
143 | ## SSL Pinning Modes
144 |
145 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
146 |
147 | enum {
148 | AFSSLPinningModeNone,
149 | AFSSLPinningModePublicKey,
150 | AFSSLPinningModeCertificate,
151 | }
152 |
153 | `AFSSLPinningModeNone`
154 | Do not used pinned certificates to validate servers.
155 |
156 | `AFSSLPinningModePublicKey`
157 | Validate host certificates against public keys of pinned certificates.
158 |
159 | `AFSSLPinningModeCertificate`
160 | Validate host certificates against pinned certificates.
161 | */
162 |
--------------------------------------------------------------------------------
/jj/AFNetworking/AFNetworking/AFURLResponseSerialization.h:
--------------------------------------------------------------------------------
1 | // AFURLResponseSerialization.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 | #import
24 |
25 | NS_ASSUME_NONNULL_BEGIN
26 |
27 | /**
28 | Recursively removes `NSNull` values from a JSON object.
29 | */
30 | FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions);
31 |
32 | /**
33 | 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.
34 |
35 | 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.
36 | */
37 | @protocol AFURLResponseSerialization
38 |
39 | /**
40 | The response object decoded from the data associated with a specified response.
41 |
42 | @param response The response to be processed.
43 | @param data The response data to be decoded.
44 | @param error The error that occurred while attempting to decode the response data.
45 |
46 | @return The object decoded from the specified response data.
47 | */
48 | - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
49 | data:(nullable NSData *)data
50 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
51 |
52 | @end
53 |
54 | #pragma mark -
55 |
56 | /**
57 | `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.
58 |
59 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior.
60 | */
61 | @interface AFHTTPResponseSerializer : NSObject
62 |
63 | - (instancetype)init;
64 |
65 | /**
66 | Creates and returns a serializer with default configuration.
67 | */
68 | + (instancetype)serializer;
69 |
70 | ///-----------------------------------------
71 | /// @name Configuring Response Serialization
72 | ///-----------------------------------------
73 |
74 | /**
75 | 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.
76 |
77 | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
78 | */
79 | @property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes;
80 |
81 | /**
82 | 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.
83 | */
84 | @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes;
85 |
86 | /**
87 | Validates the specified response and data.
88 |
89 | In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
90 |
91 | @param response The response to be validated.
92 | @param data The data associated with the response.
93 | @param error The error that occurred while attempting to validate the response.
94 |
95 | @return `YES` if the response is valid, otherwise `NO`.
96 | */
97 | - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response
98 | data:(nullable NSData *)data
99 | error:(NSError * _Nullable __autoreleasing *)error;
100 |
101 | @end
102 |
103 | #pragma mark -
104 |
105 |
106 | /**
107 | `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses.
108 |
109 | By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
110 |
111 | - `application/json`
112 | - `text/json`
113 | - `text/javascript`
114 |
115 | In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details.
116 | */
117 | @interface AFJSONResponseSerializer : AFHTTPResponseSerializer
118 |
119 | - (instancetype)init;
120 |
121 | /**
122 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
123 | */
124 | @property (nonatomic, assign) NSJSONReadingOptions readingOptions;
125 |
126 | /**
127 | Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
128 | */
129 | @property (nonatomic, assign) BOOL removesKeysWithNullValues;
130 |
131 | /**
132 | Creates and returns a JSON serializer with specified reading and writing options.
133 |
134 | @param readingOptions The specified JSON reading options.
135 | */
136 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
137 |
138 | @end
139 |
140 | #pragma mark -
141 |
142 | /**
143 | `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
144 |
145 | By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
146 |
147 | - `application/xml`
148 | - `text/xml`
149 | */
150 | @interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer
151 |
152 | @end
153 |
154 | #pragma mark -
155 |
156 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
157 |
158 | /**
159 | `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
160 |
161 | By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
162 |
163 | - `application/xml`
164 | - `text/xml`
165 | */
166 | @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer
167 |
168 | - (instancetype)init;
169 |
170 | /**
171 | Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default.
172 | */
173 | @property (nonatomic, assign) NSUInteger options;
174 |
175 | /**
176 | Creates and returns an XML document serializer with the specified options.
177 |
178 | @param mask The XML document options.
179 | */
180 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
181 |
182 | @end
183 |
184 | #endif
185 |
186 | #pragma mark -
187 |
188 | /**
189 | `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
190 |
191 | By default, `AFPropertyListResponseSerializer` accepts the following MIME types:
192 |
193 | - `application/x-plist`
194 | */
195 | @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer
196 |
197 | - (instancetype)init;
198 |
199 | /**
200 | The property list format. Possible values are described in "NSPropertyListFormat".
201 | */
202 | @property (nonatomic, assign) NSPropertyListFormat format;
203 |
204 | /**
205 | The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
206 | */
207 | @property (nonatomic, assign) NSPropertyListReadOptions readOptions;
208 |
209 | /**
210 | Creates and returns a property list serializer with a specified format, read options, and write options.
211 |
212 | @param format The property list format.
213 | @param readOptions The property list reading options.
214 | */
215 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
216 | readOptions:(NSPropertyListReadOptions)readOptions;
217 |
218 | @end
219 |
220 | #pragma mark -
221 |
222 | /**
223 | `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses.
224 |
225 | By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
226 |
227 | - `image/tiff`
228 | - `image/jpeg`
229 | - `image/gif`
230 | - `image/png`
231 | - `image/ico`
232 | - `image/x-icon`
233 | - `image/bmp`
234 | - `image/x-bmp`
235 | - `image/x-xbitmap`
236 | - `image/x-win-bitmap`
237 | */
238 | @interface AFImageResponseSerializer : AFHTTPResponseSerializer
239 |
240 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
241 | /**
242 | 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.
243 | */
244 | @property (nonatomic, assign) CGFloat imageScale;
245 |
246 | /**
247 | 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.
248 | */
249 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
250 | #endif
251 |
252 | @end
253 |
254 | #pragma mark -
255 |
256 | /**
257 | `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.
258 | */
259 | @interface AFCompoundResponseSerializer : AFHTTPResponseSerializer
260 |
261 | /**
262 | The component response serializers.
263 | */
264 | @property (readonly, nonatomic, copy) NSArray > *responseSerializers;
265 |
266 | /**
267 | Creates and returns a compound serializer comprised of the specified response serializers.
268 |
269 | @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
270 | */
271 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers;
272 |
273 | @end
274 |
275 | ///----------------
276 | /// @name Constants
277 | ///----------------
278 |
279 | /**
280 | ## Error Domains
281 |
282 | The following error domain is predefined.
283 |
284 | - `NSString * const AFURLResponseSerializationErrorDomain`
285 |
286 | ### Constants
287 |
288 | `AFURLResponseSerializationErrorDomain`
289 | AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
290 | */
291 | FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain;
292 |
293 | /**
294 | ## User info dictionary keys
295 |
296 | These keys may exist in the user info dictionary, in addition to those defined for NSError.
297 |
298 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
299 | - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
300 |
301 | ### Constants
302 |
303 | `AFNetworkingOperationFailingURLResponseErrorKey`
304 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
305 |
306 | `AFNetworkingOperationFailingURLResponseDataErrorKey`
307 | 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`.
308 | */
309 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
310 |
311 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey;
312 |
313 | NS_ASSUME_NONNULL_END
314 |
--------------------------------------------------------------------------------
/jj/AFNetworking/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/)
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h:
--------------------------------------------------------------------------------
1 | // AFAutoPurgingImageCache.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 | #import
24 |
25 | #if TARGET_OS_IOS || TARGET_OS_TV
26 | #import
27 |
28 | NS_ASSUME_NONNULL_BEGIN
29 |
30 | /**
31 | The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
32 | */
33 | @protocol AFImageCache
34 |
35 | /**
36 | Adds the image to the cache with the given identifier.
37 |
38 | @param image The image to cache.
39 | @param identifier The unique identifier for the image in the cache.
40 | */
41 | - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
42 |
43 | /**
44 | Removes the image from the cache matching the given identifier.
45 |
46 | @param identifier The unique identifier for the image in the cache.
47 |
48 | @return A BOOL indicating whether or not the image was removed from the cache.
49 | */
50 | - (BOOL)removeImageWithIdentifier:(NSString *)identifier;
51 |
52 | /**
53 | Removes all images from the cache.
54 |
55 | @return A BOOL indicating whether or not all images were removed from the cache.
56 | */
57 | - (BOOL)removeAllImages;
58 |
59 | /**
60 | Returns the image in the cache associated with the given identifier.
61 |
62 | @param identifier The unique identifier for the image in the cache.
63 |
64 | @return An image for the matching identifier, or nil.
65 | */
66 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
67 | @end
68 |
69 |
70 | /**
71 | The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
72 | */
73 | @protocol AFImageRequestCache
74 |
75 | /**
76 | Asks if the image should be cached using an identifier created from the request and additional identifier.
77 |
78 | @param image The image to be cached.
79 | @param request The unique URL request identifing the image asset.
80 | @param identifier The additional identifier to apply to the URL request to identify the image.
81 |
82 | @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching.
83 | */
84 | - (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
85 |
86 | /**
87 | Adds the image to the cache using an identifier created from the request and additional identifier.
88 |
89 | @param image The image to cache.
90 | @param request The unique URL request identifing the image asset.
91 | @param identifier The additional identifier to apply to the URL request to identify the image.
92 | */
93 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
94 |
95 | /**
96 | Removes the image from the cache using an identifier created from the request and additional identifier.
97 |
98 | @param request The unique URL request identifing the image asset.
99 | @param identifier The additional identifier to apply to the URL request to identify the image.
100 |
101 | @return A BOOL indicating whether or not all images were removed from the cache.
102 | */
103 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
104 |
105 | /**
106 | Returns the image from the cache associated with an identifier created from the request and additional identifier.
107 |
108 | @param request The unique URL request identifing the image asset.
109 | @param identifier The additional identifier to apply to the URL request to identify the image.
110 |
111 | @return An image for the matching request and identifier, or nil.
112 | */
113 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
114 |
115 | @end
116 |
117 | /**
118 | The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
119 | */
120 | @interface AFAutoPurgingImageCache : NSObject
121 |
122 | /**
123 | The total memory capacity of the cache in bytes.
124 | */
125 | @property (nonatomic, assign) UInt64 memoryCapacity;
126 |
127 | /**
128 | The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
129 | */
130 | @property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
131 |
132 | /**
133 | The current total memory usage in bytes of all images stored within the cache.
134 | */
135 | @property (nonatomic, assign, readonly) UInt64 memoryUsage;
136 |
137 | /**
138 | Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
139 |
140 | @return The new `AutoPurgingImageCache` instance.
141 | */
142 | - (instancetype)init;
143 |
144 | /**
145 | Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
146 | after purge limit.
147 |
148 | @param memoryCapacity The total memory capacity of the cache in bytes.
149 | @param preferredMemoryCapacity The preferred memory usage after purge in bytes.
150 |
151 | @return The new `AutoPurgingImageCache` instance.
152 | */
153 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
154 |
155 | @end
156 |
157 | NS_ASSUME_NONNULL_END
158 |
159 | #endif
160 |
161 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m:
--------------------------------------------------------------------------------
1 | // AFAutoPurgingImageCache.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #if TARGET_OS_IOS || TARGET_OS_TV
25 |
26 | #import "AFAutoPurgingImageCache.h"
27 |
28 | @interface AFCachedImage : NSObject
29 |
30 | @property (nonatomic, strong) UIImage *image;
31 | @property (nonatomic, copy) NSString *identifier;
32 | @property (nonatomic, assign) UInt64 totalBytes;
33 | @property (nonatomic, strong) NSDate *lastAccessDate;
34 | @property (nonatomic, assign) UInt64 currentMemoryUsage;
35 |
36 | @end
37 |
38 | @implementation AFCachedImage
39 |
40 | - (instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
41 | if (self = [self init]) {
42 | self.image = image;
43 | self.identifier = identifier;
44 |
45 | CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
46 | CGFloat bytesPerPixel = 4.0;
47 | CGFloat bytesPerSize = imageSize.width * imageSize.height;
48 | self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
49 | self.lastAccessDate = [NSDate date];
50 | }
51 | return self;
52 | }
53 |
54 | - (UIImage *)accessImage {
55 | self.lastAccessDate = [NSDate date];
56 | return self.image;
57 | }
58 |
59 | - (NSString *)description {
60 | NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
61 | return descriptionString;
62 |
63 | }
64 |
65 | @end
66 |
67 | @interface AFAutoPurgingImageCache ()
68 | @property (nonatomic, strong) NSMutableDictionary *cachedImages;
69 | @property (nonatomic, assign) UInt64 currentMemoryUsage;
70 | @property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
71 | @end
72 |
73 | @implementation AFAutoPurgingImageCache
74 |
75 | - (instancetype)init {
76 | return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
77 | }
78 |
79 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
80 | if (self = [super init]) {
81 | self.memoryCapacity = memoryCapacity;
82 | self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
83 | self.cachedImages = [[NSMutableDictionary alloc] init];
84 |
85 | NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
86 | self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
87 |
88 | [[NSNotificationCenter defaultCenter]
89 | addObserver:self
90 | selector:@selector(removeAllImages)
91 | name:UIApplicationDidReceiveMemoryWarningNotification
92 | object:nil];
93 |
94 | }
95 | return self;
96 | }
97 |
98 | - (void)dealloc {
99 | [[NSNotificationCenter defaultCenter] removeObserver:self];
100 | }
101 |
102 | - (UInt64)memoryUsage {
103 | __block UInt64 result = 0;
104 | dispatch_sync(self.synchronizationQueue, ^{
105 | result = self.currentMemoryUsage;
106 | });
107 | return result;
108 | }
109 |
110 | - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
111 | dispatch_barrier_async(self.synchronizationQueue, ^{
112 | AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
113 |
114 | AFCachedImage *previousCachedImage = self.cachedImages[identifier];
115 | if (previousCachedImage != nil) {
116 | self.currentMemoryUsage -= previousCachedImage.totalBytes;
117 | }
118 |
119 | self.cachedImages[identifier] = cacheImage;
120 | self.currentMemoryUsage += cacheImage.totalBytes;
121 | });
122 |
123 | dispatch_barrier_async(self.synchronizationQueue, ^{
124 | if (self.currentMemoryUsage > self.memoryCapacity) {
125 | UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
126 | NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
127 | NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
128 | ascending:YES];
129 | [sortedImages sortUsingDescriptors:@[sortDescriptor]];
130 |
131 | UInt64 bytesPurged = 0;
132 |
133 | for (AFCachedImage *cachedImage in sortedImages) {
134 | [self.cachedImages removeObjectForKey:cachedImage.identifier];
135 | bytesPurged += cachedImage.totalBytes;
136 | if (bytesPurged >= bytesToPurge) {
137 | break;
138 | }
139 | }
140 | self.currentMemoryUsage -= bytesPurged;
141 | }
142 | });
143 | }
144 |
145 | - (BOOL)removeImageWithIdentifier:(NSString *)identifier {
146 | __block BOOL removed = NO;
147 | dispatch_barrier_sync(self.synchronizationQueue, ^{
148 | AFCachedImage *cachedImage = self.cachedImages[identifier];
149 | if (cachedImage != nil) {
150 | [self.cachedImages removeObjectForKey:identifier];
151 | self.currentMemoryUsage -= cachedImage.totalBytes;
152 | removed = YES;
153 | }
154 | });
155 | return removed;
156 | }
157 |
158 | - (BOOL)removeAllImages {
159 | __block BOOL removed = NO;
160 | dispatch_barrier_sync(self.synchronizationQueue, ^{
161 | if (self.cachedImages.count > 0) {
162 | [self.cachedImages removeAllObjects];
163 | self.currentMemoryUsage = 0;
164 | removed = YES;
165 | }
166 | });
167 | return removed;
168 | }
169 |
170 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
171 | __block UIImage *image = nil;
172 | dispatch_sync(self.synchronizationQueue, ^{
173 | AFCachedImage *cachedImage = self.cachedImages[identifier];
174 | image = [cachedImage accessImage];
175 | });
176 | return image;
177 | }
178 |
179 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
180 | [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
181 | }
182 |
183 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
184 | return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
185 | }
186 |
187 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
188 | return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
189 | }
190 |
191 | - (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
192 | NSString *key = request.URL.absoluteString;
193 | if (additionalIdentifier != nil) {
194 | key = [key stringByAppendingString:additionalIdentifier];
195 | }
196 | return key;
197 | }
198 |
199 | - (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
200 | return YES;
201 | }
202 |
203 | @end
204 |
205 | #endif
206 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h:
--------------------------------------------------------------------------------
1 | // AFImageDownloader.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #if TARGET_OS_IOS || TARGET_OS_TV
25 |
26 | #import
27 | #import "AFAutoPurgingImageCache.h"
28 | #import "AFHTTPSessionManager.h"
29 |
30 | NS_ASSUME_NONNULL_BEGIN
31 |
32 | typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
33 | AFImageDownloadPrioritizationFIFO,
34 | AFImageDownloadPrioritizationLIFO
35 | };
36 |
37 | /**
38 | The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
39 | */
40 | @interface AFImageDownloadReceipt : NSObject
41 |
42 | /**
43 | The data task created by the `AFImageDownloader`.
44 | */
45 | @property (nonatomic, strong) NSURLSessionDataTask *task;
46 |
47 | /**
48 | The unique identifier for the success and failure blocks when duplicate requests are made.
49 | */
50 | @property (nonatomic, strong) NSUUID *receiptID;
51 | @end
52 |
53 | /** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
54 | */
55 | @interface AFImageDownloader : NSObject
56 |
57 | /**
58 | The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
59 | */
60 | @property (nonatomic, strong, nullable) id imageCache;
61 |
62 | /**
63 | The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
64 | */
65 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
66 |
67 | /**
68 | Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
69 | */
70 | @property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization;
71 |
72 | /**
73 | The shared default instance of `AFImageDownloader` initialized with default values.
74 | */
75 | + (instancetype)defaultInstance;
76 |
77 | /**
78 | Creates a default `NSURLCache` with common usage parameter values.
79 |
80 | @returns The default `NSURLCache` instance.
81 | */
82 | + (NSURLCache *)defaultURLCache;
83 |
84 | /**
85 | The default `NSURLSessionConfiguration` with common usage parameter values.
86 | */
87 | + (NSURLSessionConfiguration *)defaultURLSessionConfiguration;
88 |
89 | /**
90 | Default initializer
91 |
92 | @return An instance of `AFImageDownloader` initialized with default values.
93 | */
94 | - (instancetype)init;
95 |
96 | /**
97 | Initializer with specific `URLSessionConfiguration`
98 |
99 | @param configuration The `NSURLSessionConfiguration` to be be used
100 |
101 | @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration`
102 | */
103 | - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
104 |
105 | /**
106 | Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
107 |
108 | @param sessionManager The session manager to use to download images.
109 | @param downloadPrioritization The download prioritization of the download queue.
110 | @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
111 | @param imageCache The image cache used to store all downloaded images in.
112 |
113 | @return The new `AFImageDownloader` instance.
114 | */
115 | - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
116 | downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
117 | maximumActiveDownloads:(NSInteger)maximumActiveDownloads
118 | imageCache:(nullable id )imageCache;
119 |
120 | /**
121 | Creates a data task using the `sessionManager` instance for the specified URL request.
122 |
123 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
124 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the
125 | task are executed in the order they were added.
126 |
127 | @param request The URL request.
128 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
129 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
130 |
131 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
132 | cache and the URL request cache policy allows the cache to be used.
133 | */
134 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
135 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
136 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
137 |
138 | /**
139 | Creates a data task using the `sessionManager` instance for the specified URL request.
140 |
141 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
142 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the
143 | task are executed in the order they were added.
144 |
145 | @param request The URL request.
146 | @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
147 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
148 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
149 |
150 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
151 | cache and the URL request cache policy allows the cache to be used.
152 | */
153 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
154 | withReceiptID:(NSUUID *)receiptID
155 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
156 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
157 |
158 | /**
159 | Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
160 |
161 | If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
162 |
163 | @param imageDownloadReceipt The image download receipt to cancel.
164 | */
165 | - (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
166 |
167 | @end
168 |
169 | #endif
170 |
171 | NS_ASSUME_NONNULL_END
172 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h:
--------------------------------------------------------------------------------
1 | // AFNetworkActivityIndicatorManager.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS
27 |
28 | #import
29 |
30 | NS_ASSUME_NONNULL_BEGIN
31 |
32 | /**
33 | `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
34 |
35 | You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
36 |
37 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
38 |
39 | By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
40 |
41 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
42 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
43 | */
44 | NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
45 | @interface AFNetworkActivityIndicatorManager : NSObject
46 |
47 | /**
48 | A Boolean value indicating whether the manager is enabled.
49 |
50 | If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
51 | */
52 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled;
53 |
54 | /**
55 | A Boolean value indicating whether the network activity indicator manager is currently active.
56 | */
57 | @property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
58 |
59 | /**
60 | A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
61 |
62 | Apple's HIG describes the following:
63 |
64 | > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
65 |
66 | */
67 | @property (nonatomic, assign) NSTimeInterval activationDelay;
68 |
69 | /**
70 | A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
71 | */
72 |
73 | @property (nonatomic, assign) NSTimeInterval completionDelay;
74 |
75 | /**
76 | Returns the shared network activity indicator manager object for the system.
77 |
78 | @return The systemwide network activity indicator manager.
79 | */
80 | + (instancetype)sharedManager;
81 |
82 | /**
83 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
84 | */
85 | - (void)incrementActivityCount;
86 |
87 | /**
88 | Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
89 | */
90 | - (void)decrementActivityCount;
91 |
92 | /**
93 | Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
94 |
95 | @param block A block to be executed when the network activity indicator status changes.
96 | */
97 | - (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
98 |
99 | @end
100 |
101 | NS_ASSUME_NONNULL_END
102 |
103 | #endif
104 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m:
--------------------------------------------------------------------------------
1 | // AFNetworkActivityIndicatorManager.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "AFNetworkActivityIndicatorManager.h"
23 |
24 | #if TARGET_OS_IOS
25 | #import "AFURLSessionManager.h"
26 |
27 | typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
28 | AFNetworkActivityManagerStateNotActive,
29 | AFNetworkActivityManagerStateDelayingStart,
30 | AFNetworkActivityManagerStateActive,
31 | AFNetworkActivityManagerStateDelayingEnd
32 | };
33 |
34 | static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
35 | static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
36 |
37 | static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
38 | if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
39 | return [(NSURLSessionTask *)[notification object] originalRequest];
40 | } else {
41 | return nil;
42 | }
43 | }
44 |
45 | typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
46 |
47 | @interface AFNetworkActivityIndicatorManager ()
48 | @property (readwrite, nonatomic, assign) NSInteger activityCount;
49 | @property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
50 | @property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
51 | @property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
52 | @property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
53 | @property (nonatomic, assign) AFNetworkActivityManagerState currentState;
54 | @property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
55 |
56 | - (void)updateCurrentStateForNetworkActivityChange;
57 | @end
58 |
59 | @implementation AFNetworkActivityIndicatorManager
60 |
61 | + (instancetype)sharedManager {
62 | static AFNetworkActivityIndicatorManager *_sharedManager = nil;
63 | static dispatch_once_t oncePredicate;
64 | dispatch_once(&oncePredicate, ^{
65 | _sharedManager = [[self alloc] init];
66 | });
67 |
68 | return _sharedManager;
69 | }
70 |
71 | - (instancetype)init {
72 | self = [super init];
73 | if (!self) {
74 | return nil;
75 | }
76 | self.currentState = AFNetworkActivityManagerStateNotActive;
77 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
78 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
79 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
80 | self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
81 | self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
82 |
83 | return self;
84 | }
85 |
86 | - (void)dealloc {
87 | [[NSNotificationCenter defaultCenter] removeObserver:self];
88 |
89 | [_activationDelayTimer invalidate];
90 | [_completionDelayTimer invalidate];
91 | }
92 |
93 | - (void)setEnabled:(BOOL)enabled {
94 | _enabled = enabled;
95 | if (enabled == NO) {
96 | [self setCurrentState:AFNetworkActivityManagerStateNotActive];
97 | }
98 | }
99 |
100 | - (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
101 | self.networkActivityActionBlock = block;
102 | }
103 |
104 | - (BOOL)isNetworkActivityOccurring {
105 | @synchronized(self) {
106 | return self.activityCount > 0;
107 | }
108 | }
109 |
110 | - (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
111 | if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
112 | @synchronized(self) {
113 | _networkActivityIndicatorVisible = networkActivityIndicatorVisible;
114 | }
115 | if (self.networkActivityActionBlock) {
116 | self.networkActivityActionBlock(networkActivityIndicatorVisible);
117 | } else {
118 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
119 | }
120 | }
121 | }
122 |
123 |
124 | - (void)incrementActivityCount {
125 | @synchronized(self) {
126 | self.activityCount++;
127 | }
128 | dispatch_async(dispatch_get_main_queue(), ^{
129 | [self updateCurrentStateForNetworkActivityChange];
130 | });
131 | }
132 |
133 | - (void)decrementActivityCount {
134 | @synchronized(self) {
135 | self.activityCount = MAX(_activityCount - 1, 0);
136 | }
137 | dispatch_async(dispatch_get_main_queue(), ^{
138 | [self updateCurrentStateForNetworkActivityChange];
139 | });
140 | }
141 |
142 | - (void)networkRequestDidStart:(NSNotification *)notification {
143 | if ([AFNetworkRequestFromNotification(notification) URL]) {
144 | [self incrementActivityCount];
145 | }
146 | }
147 |
148 | - (void)networkRequestDidFinish:(NSNotification *)notification {
149 | if ([AFNetworkRequestFromNotification(notification) URL]) {
150 | [self decrementActivityCount];
151 | }
152 | }
153 |
154 | #pragma mark - Internal State Management
155 | - (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
156 | @synchronized(self) {
157 | if (_currentState != currentState) {
158 | _currentState = currentState;
159 | switch (currentState) {
160 | case AFNetworkActivityManagerStateNotActive:
161 | [self cancelActivationDelayTimer];
162 | [self cancelCompletionDelayTimer];
163 | [self setNetworkActivityIndicatorVisible:NO];
164 | break;
165 | case AFNetworkActivityManagerStateDelayingStart:
166 | [self startActivationDelayTimer];
167 | break;
168 | case AFNetworkActivityManagerStateActive:
169 | [self cancelCompletionDelayTimer];
170 | [self setNetworkActivityIndicatorVisible:YES];
171 | break;
172 | case AFNetworkActivityManagerStateDelayingEnd:
173 | [self startCompletionDelayTimer];
174 | break;
175 | }
176 | }
177 | }
178 | }
179 |
180 | - (void)updateCurrentStateForNetworkActivityChange {
181 | if (self.enabled) {
182 | switch (self.currentState) {
183 | case AFNetworkActivityManagerStateNotActive:
184 | if (self.isNetworkActivityOccurring) {
185 | [self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
186 | }
187 | break;
188 | case AFNetworkActivityManagerStateDelayingStart:
189 | //No op. Let the delay timer finish out.
190 | break;
191 | case AFNetworkActivityManagerStateActive:
192 | if (!self.isNetworkActivityOccurring) {
193 | [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
194 | }
195 | break;
196 | case AFNetworkActivityManagerStateDelayingEnd:
197 | if (self.isNetworkActivityOccurring) {
198 | [self setCurrentState:AFNetworkActivityManagerStateActive];
199 | }
200 | break;
201 | }
202 | }
203 | }
204 |
205 | - (void)startActivationDelayTimer {
206 | self.activationDelayTimer = [NSTimer
207 | timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
208 | [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
209 | }
210 |
211 | - (void)activationDelayTimerFired {
212 | if (self.networkActivityOccurring) {
213 | [self setCurrentState:AFNetworkActivityManagerStateActive];
214 | } else {
215 | [self setCurrentState:AFNetworkActivityManagerStateNotActive];
216 | }
217 | }
218 |
219 | - (void)startCompletionDelayTimer {
220 | [self.completionDelayTimer invalidate];
221 | self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
222 | [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
223 | }
224 |
225 | - (void)completionDelayTimerFired {
226 | [self setCurrentState:AFNetworkActivityManagerStateNotActive];
227 | }
228 |
229 | - (void)cancelActivationDelayTimer {
230 | [self.activationDelayTimer invalidate];
231 | }
232 |
233 | - (void)cancelCompletionDelayTimer {
234 | [self.completionDelayTimer invalidate];
235 | }
236 |
237 | @end
238 |
239 | #endif
240 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIActivityIndicatorView+AFNetworking.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import
29 |
30 | /**
31 | This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task.
32 | */
33 | @interface UIActivityIndicatorView (AFNetworking)
34 |
35 | ///----------------------------------
36 | /// @name Animating for Session Tasks
37 | ///----------------------------------
38 |
39 | /**
40 | Binds the animating state to the state of the specified task.
41 |
42 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
43 | */
44 | - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
45 |
46 | @end
47 |
48 | #endif
49 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // UIActivityIndicatorView+AFNetworking.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "UIActivityIndicatorView+AFNetworking.h"
23 | #import
24 |
25 | #if TARGET_OS_IOS || TARGET_OS_TV
26 |
27 | #import "AFURLSessionManager.h"
28 |
29 | @interface AFActivityIndicatorViewNotificationObserver : NSObject
30 | @property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
31 | - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
32 |
33 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
34 |
35 | @end
36 |
37 | @implementation UIActivityIndicatorView (AFNetworking)
38 |
39 | - (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
40 | AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
41 | if (notificationObserver == nil) {
42 | notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
43 | objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 | }
45 | return notificationObserver;
46 | }
47 |
48 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
49 | [[self af_notificationObserver] setAnimatingWithStateOfTask:task];
50 | }
51 |
52 | @end
53 |
54 | @implementation AFActivityIndicatorViewNotificationObserver
55 |
56 | - (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
57 | {
58 | self = [super init];
59 | if (self) {
60 | _activityIndicatorView = activityIndicatorView;
61 | }
62 | return self;
63 | }
64 |
65 | - (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
66 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
67 |
68 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
69 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
70 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
71 |
72 | if (task) {
73 | if (task.state != NSURLSessionTaskStateCompleted) {
74 | UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
75 | if (task.state == NSURLSessionTaskStateRunning) {
76 | [activityIndicatorView startAnimating];
77 | } else {
78 | [activityIndicatorView stopAnimating];
79 | }
80 |
81 | [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
82 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
83 | [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
84 | }
85 | }
86 | }
87 |
88 | #pragma mark -
89 |
90 | - (void)af_startAnimating {
91 | dispatch_async(dispatch_get_main_queue(), ^{
92 | [self.activityIndicatorView startAnimating];
93 | });
94 | }
95 |
96 | - (void)af_stopAnimating {
97 | dispatch_async(dispatch_get_main_queue(), ^{
98 | [self.activityIndicatorView stopAnimating];
99 | });
100 | }
101 |
102 | #pragma mark -
103 |
104 | - (void)dealloc {
105 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
106 |
107 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
108 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
109 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
110 | }
111 |
112 | @end
113 |
114 | #endif
115 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIButton+AFNetworking.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import
29 |
30 | NS_ASSUME_NONNULL_BEGIN
31 |
32 | @class AFImageDownloader;
33 |
34 | /**
35 | This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
36 |
37 | @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
38 | */
39 | @interface UIButton (AFNetworking)
40 |
41 | ///------------------------------------
42 | /// @name Accessing the Image Downloader
43 | ///------------------------------------
44 |
45 | /**
46 | Set the shared image downloader used to download images.
47 |
48 | @param imageDownloader The shared image downloader used to download images.
49 | */
50 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
51 |
52 | /**
53 | The shared image downloader used to download images.
54 | */
55 | + (AFImageDownloader *)sharedImageDownloader;
56 |
57 | ///--------------------
58 | /// @name Setting Image
59 | ///--------------------
60 |
61 | /**
62 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
63 |
64 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
65 |
66 | @param state The control state.
67 | @param url The URL used for the image request.
68 | */
69 | - (void)setImageForState:(UIControlState)state
70 | withURL:(NSURL *)url;
71 |
72 | /**
73 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
74 |
75 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
76 |
77 | @param state The control state.
78 | @param url The URL used for the image request.
79 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
80 | */
81 | - (void)setImageForState:(UIControlState)state
82 | withURL:(NSURL *)url
83 | placeholderImage:(nullable UIImage *)placeholderImage;
84 |
85 | /**
86 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
87 |
88 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
89 |
90 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
91 |
92 | @param state The control state.
93 | @param urlRequest The URL request used for the image request.
94 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
95 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
96 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
97 | */
98 | - (void)setImageForState:(UIControlState)state
99 | withURLRequest:(NSURLRequest *)urlRequest
100 | placeholderImage:(nullable UIImage *)placeholderImage
101 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
102 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
103 |
104 |
105 | ///-------------------------------
106 | /// @name Setting Background Image
107 | ///-------------------------------
108 |
109 | /**
110 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
111 |
112 | If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
113 |
114 | @param state The control state.
115 | @param url The URL used for the background image request.
116 | */
117 | - (void)setBackgroundImageForState:(UIControlState)state
118 | withURL:(NSURL *)url;
119 |
120 | /**
121 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
122 |
123 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
124 |
125 | @param state The control state.
126 | @param url The URL used for the background image request.
127 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
128 | */
129 | - (void)setBackgroundImageForState:(UIControlState)state
130 | withURL:(NSURL *)url
131 | placeholderImage:(nullable UIImage *)placeholderImage;
132 |
133 | /**
134 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
135 |
136 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
137 |
138 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
139 |
140 | @param state The control state.
141 | @param urlRequest The URL request used for the image request.
142 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
143 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
144 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
145 | */
146 | - (void)setBackgroundImageForState:(UIControlState)state
147 | withURLRequest:(NSURLRequest *)urlRequest
148 | placeholderImage:(nullable UIImage *)placeholderImage
149 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
150 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
151 |
152 |
153 | ///------------------------------
154 | /// @name Canceling Image Loading
155 | ///------------------------------
156 |
157 | /**
158 | Cancels any executing image task for the specified control state of the receiver, if one exists.
159 |
160 | @param state The control state.
161 | */
162 | - (void)cancelImageDownloadTaskForState:(UIControlState)state;
163 |
164 | /**
165 | Cancels any executing background image task for the specified control state of the receiver, if one exists.
166 |
167 | @param state The control state.
168 | */
169 | - (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state;
170 |
171 | @end
172 |
173 | NS_ASSUME_NONNULL_END
174 |
175 | #endif
176 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIImageView+AFNetworking.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import
29 |
30 | NS_ASSUME_NONNULL_BEGIN
31 |
32 | @class AFImageDownloader;
33 |
34 | /**
35 | This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
36 | */
37 | @interface UIImageView (AFNetworking)
38 |
39 | ///------------------------------------
40 | /// @name Accessing the Image Downloader
41 | ///------------------------------------
42 |
43 | /**
44 | Set the shared image downloader used to download images.
45 |
46 | @param imageDownloader The shared image downloader used to download images.
47 | */
48 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
49 |
50 | /**
51 | The shared image downloader used to download images.
52 | */
53 | + (AFImageDownloader *)sharedImageDownloader;
54 |
55 | ///--------------------
56 | /// @name Setting Image
57 | ///--------------------
58 |
59 | /**
60 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
61 |
62 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
63 |
64 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
65 |
66 | @param url The URL used for the image request.
67 | */
68 | - (void)setImageWithURL:(NSURL *)url;
69 |
70 | /**
71 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
72 |
73 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
74 |
75 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
76 |
77 | @param url The URL used for the image request.
78 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
79 | */
80 | - (void)setImageWithURL:(NSURL *)url
81 | placeholderImage:(nullable UIImage *)placeholderImage;
82 |
83 | /**
84 | Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
85 |
86 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
87 |
88 | If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
89 |
90 | @param urlRequest The URL request used for the image request.
91 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
92 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
93 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
94 | */
95 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
96 | placeholderImage:(nullable UIImage *)placeholderImage
97 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
98 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
99 |
100 | /**
101 | Cancels any executing image operation for the receiver, if one exists.
102 | */
103 | - (void)cancelImageDownloadTask;
104 |
105 | @end
106 |
107 | NS_ASSUME_NONNULL_END
108 |
109 | #endif
110 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // UIImageView+AFNetworking.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "UIImageView+AFNetworking.h"
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import "AFImageDownloader.h"
29 |
30 | @interface UIImageView (_AFNetworking)
31 | @property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
32 | @end
33 |
34 | @implementation UIImageView (_AFNetworking)
35 |
36 | - (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
37 | return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
38 | }
39 |
40 | - (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
41 | objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
42 | }
43 |
44 | @end
45 |
46 | #pragma mark -
47 |
48 | @implementation UIImageView (AFNetworking)
49 |
50 | + (AFImageDownloader *)sharedImageDownloader {
51 | return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
52 | }
53 |
54 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
55 | objc_setAssociatedObject([UIImageView class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
56 | }
57 |
58 | #pragma mark -
59 |
60 | - (void)setImageWithURL:(NSURL *)url {
61 | [self setImageWithURL:url placeholderImage:nil];
62 | }
63 |
64 | - (void)setImageWithURL:(NSURL *)url
65 | placeholderImage:(UIImage *)placeholderImage
66 | {
67 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
68 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
69 |
70 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
71 | }
72 |
73 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
74 | placeholderImage:(UIImage *)placeholderImage
75 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
76 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
77 | {
78 | if ([urlRequest URL] == nil) {
79 | self.image = placeholderImage;
80 | if (failure) {
81 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
82 | failure(urlRequest, nil, error);
83 | }
84 | return;
85 | }
86 |
87 | if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) {
88 | return;
89 | }
90 |
91 | [self cancelImageDownloadTask];
92 |
93 | AFImageDownloader *downloader = [[self class] sharedImageDownloader];
94 | id imageCache = downloader.imageCache;
95 |
96 | //Use the image from the image cache if it exists
97 | UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
98 | if (cachedImage) {
99 | if (success) {
100 | success(urlRequest, nil, cachedImage);
101 | } else {
102 | self.image = cachedImage;
103 | }
104 | [self clearActiveDownloadInformation];
105 | } else {
106 | if (placeholderImage) {
107 | self.image = placeholderImage;
108 | }
109 |
110 | __weak __typeof(self)weakSelf = self;
111 | NSUUID *downloadID = [NSUUID UUID];
112 | AFImageDownloadReceipt *receipt;
113 | receipt = [downloader
114 | downloadImageForURLRequest:urlRequest
115 | withReceiptID:downloadID
116 | success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
117 | __strong __typeof(weakSelf)strongSelf = weakSelf;
118 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
119 | if (success) {
120 | success(request, response, responseObject);
121 | } else if (responseObject) {
122 | strongSelf.image = responseObject;
123 | }
124 | [strongSelf clearActiveDownloadInformation];
125 | }
126 |
127 | }
128 | failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
129 | __strong __typeof(weakSelf)strongSelf = weakSelf;
130 | if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
131 | if (failure) {
132 | failure(request, response, error);
133 | }
134 | [strongSelf clearActiveDownloadInformation];
135 | }
136 | }];
137 |
138 | self.af_activeImageDownloadReceipt = receipt;
139 | }
140 | }
141 |
142 | - (void)cancelImageDownloadTask {
143 | if (self.af_activeImageDownloadReceipt != nil) {
144 | [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
145 | [self clearActiveDownloadInformation];
146 | }
147 | }
148 |
149 | - (void)clearActiveDownloadInformation {
150 | self.af_activeImageDownloadReceipt = nil;
151 | }
152 |
153 | - (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
154 | return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
155 | }
156 |
157 | @end
158 |
159 | #endif
160 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIKit+AFNetworking.h
2 | //
3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy
6 | // of this software and associated documentation files (the "Software"), to deal
7 | // in the Software without restriction, including without limitation the rights
8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | // copies of the Software, and to permit persons to whom the Software is
10 | // furnished to do so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in
13 | // all copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | // THE SOFTWARE.
22 |
23 | #import
24 |
25 | #ifndef _UIKIT_AFNETWORKING_
26 | #define _UIKIT_AFNETWORKING_
27 |
28 | #if TARGET_OS_IOS || TARGET_OS_TV
29 | #import "AFAutoPurgingImageCache.h"
30 | #import "AFImageDownloader.h"
31 | #import "UIActivityIndicatorView+AFNetworking.h"
32 | #import "UIButton+AFNetworking.h"
33 | #import "UIImageView+AFNetworking.h"
34 | #import "UIProgressView+AFNetworking.h"
35 | #endif
36 |
37 | #if TARGET_OS_IOS
38 | #import "AFNetworkActivityIndicatorManager.h"
39 | #import "UIRefreshControl+AFNetworking.h"
40 | #import "WKWebView+AFNetworking.h"
41 | #endif
42 |
43 | #endif /* _UIKIT_AFNETWORKING_ */
44 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIProgressView+AFNetworking.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import
29 |
30 | NS_ASSUME_NONNULL_BEGIN
31 |
32 |
33 | /**
34 | This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task.
35 | */
36 | @interface UIProgressView (AFNetworking)
37 |
38 | ///------------------------------------
39 | /// @name Setting Session Task Progress
40 | ///------------------------------------
41 |
42 | /**
43 | Binds the progress to the upload progress of the specified session task.
44 |
45 | @param task The session task.
46 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
47 | */
48 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
49 | animated:(BOOL)animated;
50 |
51 | /**
52 | Binds the progress to the download progress of the specified session task.
53 |
54 | @param task The session task.
55 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
56 | */
57 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
58 | animated:(BOOL)animated;
59 |
60 | @end
61 |
62 | NS_ASSUME_NONNULL_END
63 |
64 | #endif
65 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // UIProgressView+AFNetworking.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "UIProgressView+AFNetworking.h"
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS || TARGET_OS_TV
27 |
28 | #import "AFURLSessionManager.h"
29 |
30 | static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
31 | static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
32 |
33 | #pragma mark -
34 |
35 | @implementation UIProgressView (AFNetworking)
36 |
37 | - (BOOL)af_uploadProgressAnimated {
38 | return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
39 | }
40 |
41 | - (void)af_setUploadProgressAnimated:(BOOL)animated {
42 | objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
43 | }
44 |
45 | - (BOOL)af_downloadProgressAnimated {
46 | return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
47 | }
48 |
49 | - (void)af_setDownloadProgressAnimated:(BOOL)animated {
50 | objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
51 | }
52 |
53 | #pragma mark -
54 |
55 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
56 | animated:(BOOL)animated
57 | {
58 | if (task.state == NSURLSessionTaskStateCompleted) {
59 | return;
60 | }
61 |
62 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
63 | [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
64 |
65 | [self af_setUploadProgressAnimated:animated];
66 | }
67 |
68 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
69 | animated:(BOOL)animated
70 | {
71 | if (task.state == NSURLSessionTaskStateCompleted) {
72 | return;
73 | }
74 |
75 | [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
76 | [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
77 |
78 | [self af_setDownloadProgressAnimated:animated];
79 | }
80 |
81 | #pragma mark - NSKeyValueObserving
82 |
83 | - (void)observeValueForKeyPath:(NSString *)keyPath
84 | ofObject:(id)object
85 | change:(__unused NSDictionary *)change
86 | context:(void *)context
87 | {
88 | if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
89 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
90 | if ([object countOfBytesExpectedToSend] > 0) {
91 | dispatch_async(dispatch_get_main_queue(), ^{
92 | [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
93 | });
94 | }
95 | }
96 |
97 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
98 | if ([object countOfBytesExpectedToReceive] > 0) {
99 | dispatch_async(dispatch_get_main_queue(), ^{
100 | [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
101 | });
102 | }
103 | }
104 |
105 | if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
106 | if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
107 | @try {
108 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
109 |
110 | if (context == AFTaskCountOfBytesSentContext) {
111 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
112 | }
113 |
114 | if (context == AFTaskCountOfBytesReceivedContext) {
115 | [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
116 | }
117 | }
118 | @catch (NSException * __unused exception) {}
119 | }
120 | }
121 | }
122 | }
123 |
124 | @end
125 |
126 | #endif
127 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIRefreshControl+AFNetworking.m
2 | //
3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy
6 | // of this software and associated documentation files (the "Software"), to deal
7 | // in the Software without restriction, including without limitation the rights
8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | // copies of the Software, and to permit persons to whom the Software is
10 | // furnished to do so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in
13 | // all copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | // THE SOFTWARE.
22 |
23 | #import
24 |
25 | #import
26 |
27 | #if TARGET_OS_IOS
28 |
29 | #import
30 |
31 | NS_ASSUME_NONNULL_BEGIN
32 |
33 | /**
34 | This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task.
35 | */
36 | @interface UIRefreshControl (AFNetworking)
37 |
38 | ///-----------------------------------
39 | /// @name Refreshing for Session Tasks
40 | ///-----------------------------------
41 |
42 | /**
43 | Binds the refreshing state to the state of the specified task.
44 |
45 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
46 | */
47 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
48 |
49 | @end
50 |
51 | NS_ASSUME_NONNULL_END
52 |
53 | #endif
54 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // UIRefreshControl+AFNetworking.m
2 | //
3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy
6 | // of this software and associated documentation files (the "Software"), to deal
7 | // in the Software without restriction, including without limitation the rights
8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | // copies of the Software, and to permit persons to whom the Software is
10 | // furnished to do so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in
13 | // all copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | // THE SOFTWARE.
22 |
23 | #import "UIRefreshControl+AFNetworking.h"
24 | #import
25 |
26 | #if TARGET_OS_IOS
27 |
28 | #import "AFURLSessionManager.h"
29 |
30 | @interface AFRefreshControlNotificationObserver : NSObject
31 | @property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
32 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
33 |
34 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
35 |
36 | @end
37 |
38 | @implementation UIRefreshControl (AFNetworking)
39 |
40 | - (AFRefreshControlNotificationObserver *)af_notificationObserver {
41 | AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
42 | if (notificationObserver == nil) {
43 | notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
44 | objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
45 | }
46 | return notificationObserver;
47 | }
48 |
49 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
50 | [[self af_notificationObserver] setRefreshingWithStateOfTask:task];
51 | }
52 |
53 | @end
54 |
55 | @implementation AFRefreshControlNotificationObserver
56 |
57 | - (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
58 | {
59 | self = [super init];
60 | if (self) {
61 | _refreshControl = refreshControl;
62 | }
63 | return self;
64 | }
65 |
66 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
67 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
68 |
69 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
70 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
71 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
72 |
73 | if (task) {
74 | UIRefreshControl *refreshControl = self.refreshControl;
75 | if (task.state == NSURLSessionTaskStateRunning) {
76 | [refreshControl beginRefreshing];
77 |
78 | [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
79 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
80 | [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
81 | } else {
82 | [refreshControl endRefreshing];
83 | }
84 | }
85 | }
86 |
87 | #pragma mark -
88 |
89 | - (void)af_beginRefreshing {
90 | dispatch_async(dispatch_get_main_queue(), ^{
91 | [self.refreshControl beginRefreshing];
92 | });
93 | }
94 |
95 | - (void)af_endRefreshing {
96 | dispatch_async(dispatch_get_main_queue(), ^{
97 | [self.refreshControl endRefreshing];
98 | });
99 | }
100 |
101 | #pragma mark -
102 |
103 | - (void)dealloc {
104 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
105 |
106 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
107 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
108 | [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
109 | }
110 |
111 | @end
112 |
113 | #endif
114 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // WkWebView+AFNetworking.h
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS
27 |
28 | #import
29 | #import
30 |
31 | NS_ASSUME_NONNULL_BEGIN
32 |
33 | @class AFHTTPSessionManager;
34 |
35 | @interface WKWebView (AFNetworking)
36 |
37 | /**
38 | The session manager used to download all request
39 | */
40 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
41 |
42 | /**
43 | Asynchronously loads the specified request.
44 |
45 | @param request A URL request identifying the location of the content to load. This must not be `nil`.
46 | @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
47 | @param progress A progress object monitoring the current download progress.
48 | @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
49 | @param failure A block object to be executed when the data 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 single argument: the error that occurred.
50 | */
51 | - (void)loadRequest:(NSURLRequest *)request
52 | navigation:(WKNavigation * _Nonnull)navigation
53 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
54 | success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
55 | failure:(nullable void (^)(NSError *error))failure;
56 |
57 | /**
58 | Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
59 |
60 | @param request A URL request identifying the location of the content to load. This must not be `nil`.
61 | @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
62 | @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
63 | @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
64 | @param progress A progress object monitoring the current download progress.
65 | @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
66 | @param failure A block object to be executed when the data 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 single argument: the error that occurred.
67 | */
68 | - (void)loadRequest:(NSURLRequest *)request
69 | navigation:(WKNavigation * _Nonnull)navigation
70 | MIMEType:(nullable NSString *)MIMEType
71 | textEncodingName:(nullable NSString *)textEncodingName
72 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
73 | success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
74 | failure:(nullable void (^)(NSError *error))failure;
75 |
76 | @end
77 |
78 | NS_ASSUME_NONNULL_END
79 |
80 | #endif
81 |
--------------------------------------------------------------------------------
/jj/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // WkWebView+AFNetworking.m
2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
3 | //
4 | // Permission is hereby granted, free of charge, to any person obtaining a copy
5 | // of this software and associated documentation files (the "Software"), to deal
6 | // in the Software without restriction, including without limitation the rights
7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | // copies of the Software, and to permit persons to whom the Software is
9 | // furnished to do so, subject to the following conditions:
10 | //
11 | // The above copyright notice and this permission notice shall be included in
12 | // all copies or substantial portions of the Software.
13 | //
14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 | // THE SOFTWARE.
21 |
22 | #import "WKWebView+AFNetworking.h"
23 |
24 | #import
25 |
26 | #if TARGET_OS_IOS
27 |
28 | #import "AFHTTPSessionManager.h"
29 | #import "AFURLResponseSerialization.h"
30 | #import "AFURLRequestSerialization.h"
31 |
32 | @interface WKWebView (_AFNetworking)
33 | @property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
34 | @end
35 |
36 | @implementation WKWebView (_AFNetworking)
37 |
38 | - (NSURLSessionDataTask *)af_URLSessionTask {
39 | return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
40 | }
41 |
42 | - (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
43 | objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 | }
45 |
46 | @end
47 |
48 | #pragma mark -
49 |
50 | @implementation WKWebView (AFNetworking)
51 |
52 | - (AFHTTPSessionManager *)sessionManager {
53 | static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
54 | static dispatch_once_t onceToken;
55 | dispatch_once(&onceToken, ^{
56 | _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
57 | _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
58 | _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
59 | });
60 |
61 | return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
62 | }
63 |
64 | - (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
65 | objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
66 | }
67 |
68 | - (AFHTTPResponseSerializer *)responseSerializer {
69 | static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil;
70 | static dispatch_once_t onceToken;
71 | dispatch_once(&onceToken, ^{
72 | _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
73 | });
74 |
75 | return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
76 | }
77 |
78 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer {
79 | objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
80 | }
81 |
82 | #pragma mark -
83 |
84 | - (void)loadRequest:(NSURLRequest *)request
85 | navigation:(WKNavigation * _Nonnull)navigation
86 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
87 | success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
88 | failure:(nullable void (^)(NSError *error))failure {
89 | [self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) {
90 | NSStringEncoding stringEncoding = NSUTF8StringEncoding;
91 | if (response.textEncodingName) {
92 | CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
93 | if (encoding != kCFStringEncodingInvalidId) {
94 | stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
95 | }
96 | }
97 |
98 | NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
99 | if (success) {
100 | string = success(response, string);
101 | }
102 |
103 | return [string dataUsingEncoding:stringEncoding];
104 | } failure:failure];
105 | }
106 |
107 | - (void)loadRequest:(NSURLRequest *)request
108 | navigation:(WKNavigation * _Nonnull)navigation
109 | MIMEType:(nullable NSString *)MIMEType
110 | textEncodingName:(nullable NSString *)textEncodingName
111 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
112 | success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
113 | failure:(nullable void (^)(NSError *error))failure {
114 | NSParameterAssert(request);
115 |
116 | if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
117 | [self.af_URLSessionTask cancel];
118 | }
119 | self.af_URLSessionTask = nil;
120 |
121 | __weak __typeof(self)weakSelf = self;
122 | __block NSURLSessionDataTask *dataTask;
123 | __strong __typeof(weakSelf) strongSelf = weakSelf;
124 | __strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate;
125 | dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
126 | if (error) {
127 | if (failure) {
128 | failure(error);
129 | }
130 | } else {
131 | if (success) {
132 | success((NSHTTPURLResponse *)response, responseObject);
133 | }
134 | [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
135 |
136 | if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
137 | [strongSelfDelegate webView:strongSelf didFinishNavigation:navigation];
138 | }
139 | }
140 | }];
141 | self.af_URLSessionTask = dataTask;
142 | if (progress != nil) {
143 | *progress = [self.sessionManager downloadProgressForTask:dataTask];
144 | }
145 | [self.af_URLSessionTask resume];
146 |
147 | if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
148 | [strongSelfDelegate webView:self didStartProvisionalNavigation:navigation];
149 | }
150 | }
151 |
152 | @end
153 |
154 | #endif
155 |
--------------------------------------------------------------------------------
/jj/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface AppDelegate : NSObject
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/jj/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "AppDelegate.h"
10 |
11 | @interface AppDelegate ()
12 |
13 | @end
14 |
15 | @implementation AppDelegate
16 |
17 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
18 | // Insert code here to initialize your application
19 | }
20 | - (void)applicationWillTerminate:(NSNotification *)aNotification {
21 | // Insert code here to tear down your application
22 | }
23 | - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender{
24 | return YES;
25 | }
26 |
27 | @end
28 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_128.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_16.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_256-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_256-1.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_256.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_32-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_32-1.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_32.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_64.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/20200722182459_29940_64.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "filename" : "20200722182459_29940_16.png",
5 | "idiom" : "mac",
6 | "scale" : "1x",
7 | "size" : "16x16"
8 | },
9 | {
10 | "filename" : "20200722182459_29940_32-1.png",
11 | "idiom" : "mac",
12 | "scale" : "2x",
13 | "size" : "16x16"
14 | },
15 | {
16 | "filename" : "20200722182459_29940_32.png",
17 | "idiom" : "mac",
18 | "scale" : "1x",
19 | "size" : "32x32"
20 | },
21 | {
22 | "filename" : "20200722182459_29940_64.png",
23 | "idiom" : "mac",
24 | "scale" : "2x",
25 | "size" : "32x32"
26 | },
27 | {
28 | "filename" : "20200722182459_29940_128.png",
29 | "idiom" : "mac",
30 | "scale" : "1x",
31 | "size" : "128x128"
32 | },
33 | {
34 | "filename" : "20200722182459_29940_256.png",
35 | "idiom" : "mac",
36 | "scale" : "2x",
37 | "size" : "128x128"
38 | },
39 | {
40 | "filename" : "20200722182459_29940_256-1.png",
41 | "idiom" : "mac",
42 | "scale" : "1x",
43 | "size" : "256x256"
44 | },
45 | {
46 | "filename" : "icon-512.png",
47 | "idiom" : "mac",
48 | "scale" : "2x",
49 | "size" : "256x256"
50 | },
51 | {
52 | "filename" : "icon-513.png",
53 | "idiom" : "mac",
54 | "scale" : "1x",
55 | "size" : "512x512"
56 | },
57 | {
58 | "filename" : "icon-512@2x.png",
59 | "idiom" : "mac",
60 | "scale" : "2x",
61 | "size" : "512x512"
62 | }
63 | ],
64 | "info" : {
65 | "author" : "xcode",
66 | "version" : 1
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/icon-512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/icon-512.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/icon-512@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/icon-512@2x.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/AppIcon.appiconset/icon-513.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/AppIcon.appiconset/icon-513.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/down.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "scale" : "1x"
6 | },
7 | {
8 | "filename" : "icon_下降箭头.png",
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "filename" : "icon_下降箭头 (1).png",
14 | "idiom" : "universal",
15 | "scale" : "3x"
16 | }
17 | ],
18 | "info" : {
19 | "author" : "xcode",
20 | "version" : 1
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/down.imageset/icon_下降箭头 (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/down.imageset/icon_下降箭头 (1).png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/down.imageset/icon_下降箭头.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/down.imageset/icon_下降箭头.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/eey.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "scale" : "1x"
6 | },
7 | {
8 | "filename" : "eey.png",
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "author" : "xcode",
19 | "version" : 1
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/eey.imageset/eey.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/eey.imageset/eey.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/eye.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "scale" : "1x"
6 | },
7 | {
8 | "filename" : "eye.png",
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "author" : "xcode",
19 | "version" : 1
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/eye.imageset/eye.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/eye.imageset/eye.png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/up.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "universal",
5 | "scale" : "1x"
6 | },
7 | {
8 | "filename" : "上升箭头 (1).png",
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "filename" : "上升箭头.png",
14 | "idiom" : "universal",
15 | "scale" : "3x"
16 | }
17 | ],
18 | "info" : {
19 | "author" : "xcode",
20 | "version" : 1
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/jj/Assets.xcassets/up.imageset/上升箭头 (1).png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/up.imageset/上升箭头 (1).png
--------------------------------------------------------------------------------
/jj/Assets.xcassets/up.imageset/上升箭头.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/jj/Assets.xcassets/up.imageset/上升箭头.png
--------------------------------------------------------------------------------
/jj/FundJZWC.h:
--------------------------------------------------------------------------------
1 | //
2 | // FundJZWC.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/8/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | NS_ASSUME_NONNULL_BEGIN
12 |
13 | @interface FundJZWC : NSWindowController
14 | @property(nonatomic,copy)NSString *fundCode;
15 | @property(nonatomic,copy)NSString *fundName;
16 |
17 | @end
18 |
19 | NS_ASSUME_NONNULL_END
20 |
--------------------------------------------------------------------------------
/jj/FundJZWC.m:
--------------------------------------------------------------------------------
1 | //
2 | // FundJZWC.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/8/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "FundJZWC.h"
10 | #import
11 | @interface FundJZWC ()
12 |
13 | @property (weak) IBOutlet WKWebView *webV;
14 |
15 | @end
16 |
17 | @implementation FundJZWC
18 | - (void)windowDidLoad {
19 | [super windowDidLoad];
20 | self.window.title = _fundName;
21 | // self.webV.UIDelegate = self;
22 | // self.webV.navigationDelegate = self;
23 | [self.webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://fund.eastmoney.com/%@.html",_fundCode]]]];
24 | }
25 | -(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
26 | {
27 | NSLog(@"createWebViewWithConfiguration");
28 | if (!navigationAction.targetFrame.isMainFrame) {
29 | [webView loadRequest:navigationAction.request];
30 | }
31 | return nil;
32 | }
33 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
34 |
35 | // 如果是跳转一个新页面
36 | if (navigationAction.targetFrame == nil) {
37 | [webView loadRequest:navigationAction.request];
38 | }
39 |
40 | decisionHandler(WKNavigationActionPolicyAllow);
41 | }
42 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction preferences:(WKWebpagePreferences *)preferences decisionHandler:(void (^)(WKNavigationActionPolicy, WKWebpagePreferences *))decisionHandler{
43 |
44 | }
45 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
46 |
47 | /*! @abstract Invoked when a main frame navigation starts.
48 | @param webView The web view invoking the delegate method.
49 | @param navigation The navigation.
50 | */}
51 | - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
52 |
53 | /*! @abstract Invoked when a server redirect is received for the main
54 | frame.
55 | @param webView The web view invoking the delegate method.
56 | @param navigation The navigation.
57 | */}
58 | - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
59 |
60 | /*! @abstract Invoked when an error occurs while starting to load data for
61 | the main frame.
62 | @param webView The web view invoking the delegate method.
63 | @param navigation The navigation.
64 | @param error The error that occurred.
65 | */}
66 | - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
67 |
68 | /*! @abstract Invoked when content starts arriving for the main frame.
69 | @param webView The web view invoking the delegate method.
70 | @param navigation The navigation.
71 | */}
72 | - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{
73 |
74 | /*! @abstract Invoked when a main frame navigation completes.
75 | @param webView The web view invoking the delegate method.
76 | @param navigation The navigation.
77 | */}
78 | - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;{
79 |
80 | /*! @abstract Invoked when an error occurs during a committed main frame
81 | navigation.
82 | @param webView The web view invoking the delegate method.
83 | @param navigation The navigation.
84 | @param error The error that occurred.
85 | */}
86 | - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
87 |
88 | /*! @abstract Invoked when the web view needs to respond to an authentication challenge.
89 | @param webView The web view that received the authentication challenge.
90 | @param challenge The authentication challenge.
91 | @param completionHandler The completion handler you must invoke to respond to the challenge. The
92 | disposition argument is one of the constants of the enumerated type
93 | NSURLSessionAuthChallengeDisposition. When disposition is NSURLSessionAuthChallengeUseCredential,
94 | the credential argument is the credential to use, or nil to indicate continuing without a
95 | credential.
96 | @discussion If you do not implement this method, the web view will respond to the authentication challenge with the NSURLSessionAuthChallengeRejectProtectionSpace disposition.
97 | */}
98 | - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
99 |
100 | /*! @abstract Invoked when the web view's web content process is terminated.
101 | @param webView The web view whose underlying web content process was terminated.
102 | */}
103 | - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macos(10.11), ios(9.0)){
104 |
105 | }
106 |
107 | @end
108 |
--------------------------------------------------------------------------------
/jj/FundJZWC.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/jj/FundModel.h:
--------------------------------------------------------------------------------
1 | //
2 | // FundModel.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | NS_ASSUME_NONNULL_BEGIN
12 |
13 | @interface FundModel : NSObject
14 |
15 | /// 基码
16 | @property(nonatomic,copy)NSString *fundcode;
17 | /// 基幅
18 | @property(nonatomic,copy)NSString *gszzl;
19 | /// 基止
20 | @property(nonatomic,copy)NSString *gztime;
21 | /// 基刷
22 | @property(nonatomic,copy)NSString *refreshtime;
23 | /// 基时
24 | @property(nonatomic,copy)NSString *jzrq;
25 | /// 基净
26 | @property(nonatomic,copy)NSString *dwjz;
27 | /// 基估
28 | @property(nonatomic,copy)NSString *gsz;
29 | /// 基名
30 | @property(nonatomic,copy)NSString *name;
31 | /// 基序
32 | @property(nonatomic,assign)NSInteger sort;
33 | /// 基持
34 | @property(nonatomic,copy)NSString *jc;
35 | /// 规模
36 | @property(nonatomic,copy)NSString *ENDNAV;
37 | /// 周涨幅
38 | @property(nonatomic,copy)NSString *SYL_Z;
39 | /// 月涨幅
40 | @property(nonatomic,copy)NSString *SYL_Y;
41 | /// 年涨幅
42 | @property(nonatomic,copy)NSString *SYL_1N;
43 | /// 日涨幅
44 | @property(nonatomic,copy)NSString *RZDF;
45 | /// 上日
46 | @property(nonatomic,copy)NSString *FSRQ;
47 | /// 区类型 2====>榜单
48 | @property(nonatomic,assign)NSInteger zoneType;
49 |
50 | /// 指数
51 | @property(nonatomic,copy)NSString *f2;
52 | @property(nonatomic,copy)NSString *f3;
53 | @property(nonatomic,copy)NSString *f4;
54 |
55 |
56 | - (instancetype)initWithDic:(NSDictionary *)dic;
57 |
58 | /// 榜单区
59 | /// @param dic <#dic description#>
60 | - (instancetype)initWithRankDic:(NSDictionary *)dic;
61 |
62 | @end
63 |
64 | NS_ASSUME_NONNULL_END
65 |
--------------------------------------------------------------------------------
/jj/FundModel.m:
--------------------------------------------------------------------------------
1 | //
2 | // FundModel.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "FundModel.h"
10 |
11 | @implementation FundModel
12 |
13 | - (instancetype)initWithDic:(NSDictionary *)dic{
14 |
15 | if (self = [super init]) {
16 |
17 | self.name = dic[@"name"];
18 | self.gztime = dic[@"gztime"];
19 | self.fundcode = dic[@"fundcode"];
20 | self.gsz = dic[@"gsz"];
21 | self.dwjz = dic[@"dwjz"];
22 | self.zoneType = 1;
23 |
24 | self.f2 = [NSString stringWithFormat:@"%@",dic[@"f2"]];
25 | CGFloat ff3 = [[NSString stringWithFormat:@"%@",dic[@"f3"]] floatValue];
26 | CGFloat ff4 = [[NSString stringWithFormat:@"%@",dic[@"f4"]] floatValue];
27 |
28 | self.f3 = [[NSString stringWithFormat:@"%.2f",ff3]stringByAppendingString:@"%"];
29 | self.f4 = [NSString stringWithFormat:@"%.2f",ff4];
30 | CGFloat gz = [dic[@"gszzl"] floatValue];
31 | self.gszzl = [[NSString stringWithFormat:@"%.2f",gz]stringByAppendingString:@"%"];
32 |
33 | }
34 |
35 | return self;
36 | }
37 | - (instancetype)initWithRankDic:(NSDictionary *)dic{
38 |
39 | if (self = [super init]) {
40 |
41 | self.name = dic[@"SHORTNAME"];
42 | self.ENDNAV = dic[@"ENDNAV"];
43 | self.RZDF = dic[@"RZDF"];
44 | self.SYL_Y = dic[@"SYL_Y"];
45 | self.SYL_1N = dic[@"SYL_1N"];
46 | self.FSRQ = dic[@"FSRQ"];
47 | self.fundcode = dic[@"FCODE"];
48 | self.zoneType = 2;
49 |
50 | }
51 |
52 | return self;
53 | }
54 | @end
55 |
--------------------------------------------------------------------------------
/jj/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleDisplayName
8 | $(PRODUCT_NAME)
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIconFile
12 |
13 | CFBundleIdentifier
14 | $(PRODUCT_BUNDLE_IDENTIFIER)
15 | CFBundleInfoDictionaryVersion
16 | 6.0
17 | CFBundleName
18 | $(PRODUCT_NAME)
19 | CFBundlePackageType
20 | $(PRODUCT_BUNDLE_PACKAGE_TYPE)
21 | CFBundleShortVersionString
22 | 1.0
23 | CFBundleVersion
24 | 1
25 | LSApplicationCategoryType
26 | public.app-category.finance
27 | LSMinimumSystemVersion
28 | $(MACOSX_DEPLOYMENT_TARGET)
29 | NSAppTransportSecurity
30 |
31 | NSAllowsArbitraryLoads
32 |
33 |
34 | NSHumanReadableCopyright
35 | Copyright © 2020 LY_MD. All rights reserved.
36 | NSMainStoryboardFile
37 | Main
38 | NSPrincipalClass
39 | NSApplication
40 | NSSupportsAutomaticTermination
41 |
42 | NSSupportsSuddenTermination
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/jj/InfoPlist.strings:
--------------------------------------------------------------------------------
1 | /*
2 | InfoPlist.strings
3 | jj
4 |
5 | Created by LY_MD on 2020/7/22.
6 | Copyright © 2020 LY_MD. All rights reserved.
7 | */
8 | CFBundleName = "基富贵";// 在状态栏中显示
9 |
10 | CFBundleDisplayName = "基富贵";// 在 docker 栏及应用中显示
11 |
--------------------------------------------------------------------------------
/jj/NSMenuTableView.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSMenuTableView.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/23.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @protocol MenuHandleDelegate
12 |
13 | - (void)tableView:(NSTableView *)tableView didClickMenuDelete:(NSInteger)row;
14 | - (void)tableView:(NSTableView *)tableView didClickMenuDetail:(NSInteger)row;
15 |
16 | @end
17 |
18 | @interface NSMenuTableView : NSTableView
19 | @property(nonatomic,weak)id mhdelegate;
20 | @end
21 |
22 |
--------------------------------------------------------------------------------
/jj/NSMenuTableView.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSMenuTableView.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/23.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "NSMenuTableView.h"
10 |
11 | @implementation NSMenuTableView
12 |
13 | - (void)drawRect:(NSRect)dirtyRect {
14 | [super drawRect:dirtyRect];
15 | }
16 |
17 | /// 设置右键菜单
18 | /// @param event <#event description#>
19 | - (NSMenu *)menuForEvent:(NSEvent *)event{
20 |
21 | if (event.type == NSEventTypeRightMouseDown) {
22 | NSPoint menuPoint = [self convertPoint:[event locationInWindow] fromView:nil];
23 | NSInteger row = [self rowAtPoint:menuPoint];
24 | if (row >= 0) {
25 | NSMenu * menu = [[NSMenu alloc]initWithTitle:@"Menu"];
26 | NSMenuItem * item1 = [[NSMenuItem alloc]initWithTitle:@"删除" action:@selector(menuDelete:) keyEquivalent:@""];
27 | NSMenuItem * item2 = [[NSMenuItem alloc]initWithTitle:@"查看详情>" action:@selector(menuDetail:) keyEquivalent:@""];
28 | item1.tag = row;
29 | item2.tag = row;
30 | item1.target = self;
31 | item2.target = self;
32 | [menu addItem:item1];
33 | [menu addItem:item2];
34 |
35 | return menu;
36 | }
37 |
38 | }
39 |
40 | return nil;
41 |
42 | }
43 | - (void)menuDelete:(NSMenuItem *)item {
44 |
45 | if ([self.mhdelegate respondsToSelector:@selector(tableView:didClickMenuDelete:)]) {
46 | [self.mhdelegate tableView:self didClickMenuDelete:item.tag];
47 | }
48 |
49 | }
50 | - (void)menuDetail:(NSMenuItem *)item {
51 |
52 | if ([self.mhdelegate respondsToSelector:@selector(tableView:didClickMenuDetail:)]) {
53 | [self.mhdelegate tableView:self didClickMenuDetail:item.tag];
54 | }
55 |
56 | }
57 | @end
58 |
--------------------------------------------------------------------------------
/jj/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "DataManager.h"
11 | #import "NSMenuTableView.h"
12 |
13 | @interface ViewController : NSViewController
14 |
15 | @property (weak) IBOutlet NSTextField *codeTf;
16 | @property (weak) IBOutlet NSButton *addBtn;
17 | @property (weak) IBOutlet NSMenuTableView *codeTableV;
18 | @property (weak) IBOutlet NSButton *autoRefreshBtn;
19 | @property (weak) IBOutlet NSTextField *huLabel;
20 | @property (weak) IBOutlet NSTextField *shangLabel;
21 | @property (weak) IBOutlet NSTextField *shenLabel;
22 | @property (weak) IBOutlet NSTextField *hu1Label;
23 | @property (weak) IBOutlet NSTextField *shang1Label;
24 | @property (weak) IBOutlet NSTextField *shen1Label;
25 | @property (weak) IBOutlet NSImageView *huImage;
26 | @property (weak) IBOutlet NSImageView *shangImage;
27 | @property (weak) IBOutlet NSImageView *shenImage;
28 | @property (weak) IBOutlet NSTextField *totolLabel;
29 | @property (weak) IBOutlet NSTextField *allMoneyLabel;
30 | @property (weak) IBOutlet NSButton *eyeBtn;
31 | @property (weak) IBOutlet NSButton *updateBtn;
32 |
33 | @property(nonatomic,assign) NSInteger sourceIndex;
34 |
35 | @property(nonatomic,assign) SourceType st;
36 | /// 总收益
37 | @property(nonatomic,copy) NSString *zsyStr;
38 | /// 总投资
39 | @property(nonatomic,copy) NSString *ztzStr;
40 | /// 存放持仓数据
41 | @property (nonatomic, strong) NSMutableDictionary *ccDic;
42 |
43 | /// 自动刷新
44 | @property (nonatomic, strong) dispatch_source_t timer;
45 | /// 数据
46 | @property(nonatomic,strong)NSMutableArray *modelsAry;
47 |
48 | @property(nonatomic,strong)NSProgressIndicator *indicator;
49 | @end
50 |
51 |
--------------------------------------------------------------------------------
/jj/jj.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.files.user-selected.read-only
8 |
9 | com.apple.security.network.client
10 |
11 | com.apple.security.network.server
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/jj/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | int main(int argc, const char * argv[]) {
12 | @autoreleasepool {
13 | // Setup code that might create autoreleased objects goes here.
14 | }
15 | return NSApplicationMain(argc, argv);
16 | }
17 |
--------------------------------------------------------------------------------
/jj/tool/AlertTool.h:
--------------------------------------------------------------------------------
1 | //
2 | // AlertTool.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/22.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 | #import
11 |
12 | typedef NS_ENUM(NSUInteger, AlertResponse) {
13 | FirstResp = 0,
14 | SecondResp = 1,
15 | ThirdResp = 2
16 | };
17 |
18 | @interface AlertTool : NSObject
19 | +(void)showAlert:(NSString *)msg actionTitle1:(NSString *)actionTitle1 actionTitle2:(NSString *)actionTitle2 window:(NSWindow *)window action:(void(^)(AlertResponse resp))action;
20 | @end
21 |
22 |
--------------------------------------------------------------------------------
/jj/tool/AlertTool.m:
--------------------------------------------------------------------------------
1 | //
2 | // AlertTool.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/22.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "AlertTool.h"
10 |
11 | @implementation AlertTool
12 |
13 | +(void)showAlert:(NSString *)msg actionTitle1:(NSString *)actionTitle1 actionTitle2:(NSString *)actionTitle2 window:(NSWindow *)window action:(void(^)(AlertResponse resp))action {
14 |
15 | NSAlert * alert = [[NSAlert alloc]init];
16 | alert.messageText = @"入基有风险,买卖需谨慎";
17 | [alert addButtonWithTitle:actionTitle1];
18 | if (actionTitle2.length > 1) {
19 | [alert addButtonWithTitle:@"取消"];
20 | }
21 | [alert setInformativeText:msg];
22 | [alert beginSheetModalForWindow:window completionHandler:^(NSModalResponse returnCode) {
23 | if (returnCode == NSModalResponseOK){
24 | NSLog(@"(returnCode == NSOKButton)");
25 | }else if (returnCode == NSModalResponseCancel){
26 | NSLog(@"(returnCode == NSCancelButton)");
27 | }else if(returnCode == NSAlertFirstButtonReturn){
28 | if (action) {action(FirstResp);}
29 | }else if (returnCode == NSAlertSecondButtonReturn){
30 | if (action) {action(SecondResp);}
31 | }else if (returnCode == NSAlertThirdButtonReturn){
32 | if (action) {action(ThirdResp);}
33 | }else{
34 | NSLog(@"All Other return code %ld",(long)returnCode);
35 | }
36 | }];
37 | }
38 |
39 | @end
40 |
--------------------------------------------------------------------------------
/jj/tool/DataManager.h:
--------------------------------------------------------------------------------
1 | //
2 | // DataManager.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/22.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "NetTool.h"
11 |
12 | typedef enum : NSUInteger {
13 | AlertEmpty,
14 | AlertRepeat,
15 | AlertNull,
16 | } AlertType;
17 |
18 | typedef enum : NSUInteger {
19 | RankType, // 榜单前三十数据
20 | ObType, // 观察的数据
21 | OwnType, // 拥有的数据
22 | } SourceType;
23 |
24 | /// <#Description#>
25 | @interface DataManager : NSObject
26 |
27 | /// 模型数据
28 | @property(nonatomic,strong)NSMutableArray *modelsAry;
29 |
30 | /// 获取实例
31 | + (instancetype)manger;
32 |
33 | /// 加载数据
34 | /// @param resp <#resp description#>
35 | - (void)loadData:(SourceType)st resp:(void(^)(id resp))resp;
36 |
37 | /// 添加数据
38 | /// @param codeStr <#codeStr description#>
39 | /// @param result <#result description#>
40 | - (void)addData:(NSString *)codeStr source:(SourceType)st resp:(void(^)(id result,AlertType at))result;
41 |
42 | /// 删除数据
43 | /// @param resp <#resp description#>
44 | - (void)deleteData:(NSInteger)row source:(SourceType)st resp:(void(^)(id resp))resp;
45 |
46 | /// 获取某行基码
47 | /// @param row <#row description#>
48 | /// @param st <#st description#>
49 | - (NSString *)getCode:(NSInteger)row source:(SourceType)st;
50 |
51 | /// 清楚数据
52 | - (void)clearData;
53 |
54 | /// 重置数据
55 | - (void)resetDefaultData:(SourceType)st resp:(void(^)(id resp))resp;
56 |
57 | /// 拖拽后,重排数据
58 | /// @param st <#st description#>
59 | /// @param modelsAry <#modelsAry description#>
60 | - (void)dragReset:(SourceType)st modelsAry:(NSArray *)modelsAry;
61 |
62 | /// 保存持仓数
63 | /// @param mdic <#mdic description#>
64 | - (void)saveInvestedMoney:(NSMutableDictionary *)mdic;
65 |
66 | /// 获取持仓数
67 | - (NSDictionary *)getInvestedMoney;
68 | @end
69 |
70 |
--------------------------------------------------------------------------------
/jj/tool/DataManager.m:
--------------------------------------------------------------------------------
1 | //
2 | // DataManager.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/22.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "DataManager.h"
10 | /// 观察区基金
11 | #define jjKey @"jjkey"
12 | /// 持有基金
13 | #define jjMyKey @"jjMyKey"
14 | /// 持仓金额
15 | #define jcKey @"jcKey"
16 |
17 | @implementation DataManager
18 |
19 | + (instancetype)manger {
20 |
21 | static DataManager *manager = nil;
22 | static dispatch_once_t onceToken;
23 | dispatch_once(&onceToken, ^{
24 | manager = [[DataManager alloc]init];
25 | });
26 | return manager;
27 |
28 | }
29 |
30 | - (void)loadData:(SourceType)st resp:(void(^)(id resp))resp {
31 |
32 | NSArray *sourceA;
33 | if (st == ObType) {
34 |
35 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjKey];
36 |
37 | if (sourceA.count < 1) {
38 | NSArray *jjA = @[@"003834",@"005968",@"006299",@"002190",@"540008",@"090018",@"001644",@"006049",@"161725",@"001951"];
39 | [[NSUserDefaults standardUserDefaults]setObject:jjA forKey:jjKey];
40 |
41 | sourceA = jjA;
42 | } else {
43 | NSMutableArray *resultArrM = [NSMutableArray array];
44 | NSArray *originalArr = sourceA;
45 |
46 | for (NSString *item in originalArr) {
47 | if (![resultArrM containsObject:item]) {
48 | [resultArrM addObject:item];
49 | }
50 | }
51 |
52 | sourceA = [NSArray arrayWithArray:resultArrM];
53 | }
54 |
55 |
56 | } else if (st == OwnType) {
57 | // 去重
58 | NSMutableArray *resultArrM = [NSMutableArray array];
59 | NSArray *originalArr = [[NSUserDefaults standardUserDefaults]objectForKey:jjMyKey];
60 |
61 | for (NSString *item in originalArr) {
62 | if (![resultArrM containsObject:item]) {
63 | [resultArrM addObject:item];
64 | }
65 | }
66 |
67 | sourceA = [NSArray arrayWithArray:resultArrM];
68 | } else {
69 |
70 | [NetTool getFundRank:^(id _Nonnull rankA) {
71 | resp(rankA);
72 | }];
73 | return;
74 | }
75 |
76 | self.modelsAry = [NSMutableArray array];
77 | NSMutableArray *tempA = [NSMutableArray array];
78 | NSMutableArray *tempB = [NSMutableArray array];
79 | dispatch_group_t group = dispatch_group_create();
80 | dispatch_queue_t jjqueue = dispatch_get_global_queue(0, 0);
81 |
82 | [sourceA enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
83 |
84 | dispatch_group_enter(group);
85 | dispatch_group_async(group, jjqueue, ^{
86 | [NetTool getFundInfo:obj complete:^(id _Nonnull resp) {
87 | [tempA addObject:resp];
88 | dispatch_group_leave(group);
89 |
90 | } fail:^(id _Nonnull resp) {
91 | dispatch_group_leave(group);
92 | }];
93 | });
94 |
95 | }];
96 |
97 | dispatch_group_notify(group, dispatch_get_main_queue(), ^{
98 | // 请求完成后排序
99 | [tempA enumerateObjectsUsingBlock:^(FundModel * _Nonnull jjModel, NSUInteger idx, BOOL * _Nonnull stop) {
100 |
101 | [sourceA enumerateObjectsUsingBlock:^(id _Nonnull code, NSUInteger idx, BOOL * _Nonnull stop) {
102 | if ([code isEqualToString:jjModel.fundcode]) {
103 | jjModel.sort = idx;
104 | [tempB addObject:jjModel];
105 | }
106 | }];
107 |
108 | }];
109 | [self.modelsAry addObjectsFromArray:[self sortHomeModelArray:tempB]];
110 | // NSLog(@"请求完成");
111 | if (resp) {
112 |
113 | // 可能有的基金未能查询到相关信息,请求完成之后更新本地数据,保持数据同步
114 | NSMutableArray *tempC = [NSMutableArray array];
115 | [self.modelsAry enumerateObjectsUsingBlock:^(FundModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
116 | [tempC addObject:obj.fundcode];
117 | }];
118 | if (st == ObType) {
119 |
120 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempC] forKey:jjKey];
121 |
122 | } else if (st == OwnType) {
123 |
124 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempC] forKey:jjMyKey];
125 |
126 | }
127 |
128 | resp(self.modelsAry);
129 | }
130 |
131 | });
132 |
133 |
134 | }
135 | - (void)addData:(NSString *)codeStr source:(SourceType)st resp:(void(^)(id result,AlertType at))result {
136 |
137 | NSArray *sourceA;
138 | if (st == ObType) {
139 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjKey];
140 | } else if (st == OwnType) {
141 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjMyKey];
142 | }
143 |
144 | if (codeStr.length < 1) {
145 | result(nil,AlertEmpty);
146 | return;
147 | }
148 |
149 | if ([sourceA containsObject:codeStr]) {
150 | result(nil,AlertRepeat);
151 | return;
152 | }
153 |
154 | NSMutableArray *tempA = [NSMutableArray arrayWithArray:sourceA];
155 |
156 | [NetTool getFundInfo:codeStr complete:^(id _Nonnull resp) {
157 |
158 | if (![resp isKindOfClass:[NSError class]]) {
159 |
160 | [self.modelsAry addObject:resp];
161 | [tempA insertObject:codeStr atIndex:0];
162 | if (st == ObType) {
163 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempA] forKey:jjKey];
164 | } else if (st == OwnType) {
165 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempA] forKey:jjMyKey];
166 | }
167 |
168 | if (result) {
169 | result(self.modelsAry,-100);
170 | }
171 |
172 | }else {
173 | result(nil,AlertNull);
174 | }
175 |
176 | } fail:^(id _Nonnull resp) {
177 |
178 | }];
179 |
180 | }
181 | - (void)deleteData:(NSInteger)row source:(SourceType)st resp:(void(^)(id resp))resp {
182 |
183 | if(st == RankType) return;;
184 |
185 | NSArray *sourceA;
186 | if (st == ObType) {
187 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjKey];
188 | } else if (st == OwnType) {
189 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjMyKey];
190 | }
191 |
192 | NSMutableArray *mjja = [NSMutableArray arrayWithArray:sourceA];
193 | [mjja removeObjectAtIndex:row];
194 |
195 | if (st == ObType) {
196 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:mjja] forKey:jjKey];
197 | } else if (st == OwnType) {
198 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:mjja] forKey:jjMyKey];
199 | }
200 | [[NSUserDefaults standardUserDefaults]synchronize];
201 |
202 | resp(@"delete");
203 |
204 | }
205 | - (NSString *)getCode:(NSInteger)row source:(SourceType)st{
206 |
207 | NSArray *sourceA;
208 | if (st == ObType) {
209 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjKey];
210 | } else if (st == OwnType) {
211 | sourceA = [[NSUserDefaults standardUserDefaults]objectForKey:jjMyKey];
212 | }
213 | return [sourceA objectAtIndex:row];
214 |
215 | }
216 | - (void)clearData{
217 | [[NSUserDefaults standardUserDefaults]removeObjectForKey:jjKey];
218 |
219 | }
220 | /// 默认天天基金榜十
221 | /// @param resp <#resp description#>
222 | - (void)resetDefaultData:(SourceType)st resp:(void(^)(id resp))resp {
223 |
224 | if (st == ObType) {
225 | NSArray *jjA = @[@"003834",@"005968",@"006299",@"002190",@"540008",@"090018",@"001644",@"006049",@"161725",@"001951"];
226 | [[NSUserDefaults standardUserDefaults]setObject:jjA forKey:jjKey];
227 |
228 | resp(@"reset");
229 | } else if (st == OwnType) {
230 | [[NSUserDefaults standardUserDefaults]removeObjectForKey:jjMyKey];
231 |
232 | resp(@"reset");
233 | }
234 |
235 | }
236 | - (NSArray *)sortHomeModelArray:(NSArray *)tempAry {
237 |
238 | NSArray *sortedArray = [tempAry sortedArrayUsingComparator:^NSComparisonResult(FundModel *obj1, FundModel *obj2) {
239 |
240 | if (obj1.sort < obj2.sort) {
241 | return NSOrderedAscending;
242 | } else {
243 | return NSOrderedDescending;
244 | }
245 | }];
246 |
247 | return sortedArray;
248 | }
249 | - (void)dragReset:(SourceType)st modelsAry:(NSArray *)modelsAry {
250 |
251 | NSMutableArray *tempAry = [NSMutableArray arrayWithCapacity:modelsAry.count];
252 |
253 | [modelsAry enumerateObjectsUsingBlock:^(FundModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
254 |
255 | [tempAry addObject:obj.fundcode];
256 |
257 | }];
258 |
259 | if (st == ObType) {
260 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempAry] forKey:jjKey];
261 | } else if (st == OwnType){
262 | [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:tempAry] forKey:jjMyKey];
263 | }
264 |
265 | }
266 | - (void)saveInvestedMoney:(NSMutableDictionary *)mdic {
267 | [[NSUserDefaults standardUserDefaults]setObject:[NSDictionary dictionaryWithDictionary:mdic] forKey:jcKey];
268 | }
269 | - (NSDictionary *)getInvestedMoney {
270 | return [[NSUserDefaults standardUserDefaults]objectForKey:jcKey];
271 | }
272 |
273 | @end
274 |
--------------------------------------------------------------------------------
/jj/tool/JTool.h:
--------------------------------------------------------------------------------
1 | //
2 | // JTool.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | NS_ASSUME_NONNULL_BEGIN
12 |
13 | @interface JTool : NSObject
14 | + (BOOL)isPureFloat:(NSString*)string;
15 | + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString;
16 | @end
17 |
18 | NS_ASSUME_NONNULL_END
19 |
--------------------------------------------------------------------------------
/jj/tool/JTool.m:
--------------------------------------------------------------------------------
1 | //
2 | // JTool.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "JTool.h"
10 |
11 | @implementation JTool
12 |
13 | + (BOOL)isPureFloat:(NSString*)string {
14 | NSScanner *scan = [NSScanner scannerWithString:string];
15 | float val;
16 | return [scan scanFloat:&val] && [scan isAtEnd];
17 | }
18 |
19 | + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
20 | {
21 | if (jsonString == nil ||[jsonString length] < 1) {
22 | return nil;
23 | }
24 | NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
25 | NSError *err;
26 | NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
27 | options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
28 | error:&err];
29 | if(err)
30 | {
31 | NSLog(@"json解析失败:%@=====%@",err,jsonString);
32 | return nil;
33 | }
34 | return dic;
35 | }
36 | @end
37 |
--------------------------------------------------------------------------------
/jj/tool/NetClient.h:
--------------------------------------------------------------------------------
1 | //
2 | // NetClient.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "AFNetworking.h"
11 |
12 | NS_ASSUME_NONNULL_BEGIN
13 |
14 | @interface NetClient : AFHTTPSessionManager
15 | + (instancetype)shareHttpInstance;
16 | + (instancetype)shareJsonInstance;
17 | @end
18 |
19 | NS_ASSUME_NONNULL_END
20 |
--------------------------------------------------------------------------------
/jj/tool/NetClient.m:
--------------------------------------------------------------------------------
1 | //
2 | // NetClient.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "NetClient.h"
10 |
11 | @implementation NetClient
12 | + (instancetype)shareHttpInstance {
13 |
14 | static NetClient *manager = nil;
15 | static dispatch_once_t onceToken;
16 | dispatch_once(&onceToken, ^{
17 | manager = [[self alloc] init];
18 | manager.requestSerializer = [AFHTTPRequestSerializer serializer];
19 | manager.responseSerializer = [AFHTTPResponseSerializer serializer];
20 | [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/x-javascript",nil]];
21 | });
22 | return manager;
23 |
24 | }
25 | + (instancetype)shareJsonInstance {
26 |
27 | static NetClient *manager = nil;
28 | static dispatch_once_t onceToken;
29 | dispatch_once(&onceToken, ^{
30 | manager = [[self alloc] init];
31 | manager.requestSerializer = [AFHTTPRequestSerializer serializer];
32 | manager.responseSerializer = [AFJSONResponseSerializer serializer];
33 | [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/x-javascript",nil]];
34 | });
35 | return manager;
36 |
37 | }
38 | @end
39 |
--------------------------------------------------------------------------------
/jj/tool/NetTool.h:
--------------------------------------------------------------------------------
1 | //
2 | // NetTool.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "FundModel.h"
11 | #import "TimeTool.h"
12 | #import "JTool.h"
13 | #import "AFNetworking.h"
14 | #import "NetClient.h"
15 |
16 | NS_ASSUME_NONNULL_BEGIN
17 |
18 | @interface NetTool : NSObject
19 |
20 |
21 | /// 加载基金信息
22 | /// @param code <#code description#>
23 | /// @param resp <#resp description#>
24 | /// @param failBlock <#failBlock description#>
25 | + (void)getFundInfo:(NSString *)code complete:(void(^)(id resp))resp fail:(void(^)(id resp))failBlock ;
26 |
27 |
28 | /// 加载指数信息
29 | /// @param resp <#resp description#>
30 | + (void)getIndexInfo:(void(^)(id resp))resp;
31 |
32 | /// 获取上天净值
33 | /// @param code <#code description#>
34 | + (void)getFundLastJZ:(NSString *)code resp:(void(^)(id resp))resp;
35 |
36 | + (void)getFundRank:(void(^)(id resp))resp;
37 |
38 | @end
39 |
40 | NS_ASSUME_NONNULL_END
41 |
--------------------------------------------------------------------------------
/jj/tool/NetTool.m:
--------------------------------------------------------------------------------
1 | //
2 | // NetTool.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/7/17.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "NetTool.h"
10 | #import "AlertTool.h"
11 | /// 数据来源天天基金
12 | #define tturl @"http://fundgz.1234567.com.cn/js/"
13 | #define ttjzurl @"http://fund.eastmoney.com/f10/F10DataApi.aspx?"
14 |
15 | @implementation NetTool
16 |
17 | + (void)getFundInfo:(NSString *)code complete:(void(^)(id resp))resp fail:(void(^)(id resp))failBlock {
18 |
19 | NSString *requestUrl = [NSString stringWithFormat:@"%@%@.js",tturl,code];
20 | [[NetClient shareHttpInstance] GET:requestUrl parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
21 |
22 | NSString *string = [[[[[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"(" withString:@""]stringByReplacingOccurrencesOfString:@")" withString:@""]stringByReplacingOccurrencesOfString:@"jsonpgz" withString:@""]stringByReplacingOccurrencesOfString:@";" withString:@""];
23 |
24 | NSDictionary *dic = [JTool dictionaryWithJsonString:string];
25 |
26 | if (dic) {
27 | FundModel *fm = [[FundModel alloc]initWithDic:dic];
28 | resp(fm);
29 | }else {
30 | NSLog(@"查询基金:%@ 相关信息为空:",code);
31 | failBlock(@"error");
32 | }
33 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
34 | NSLog(@"NSError===%@",error);
35 | [AlertTool showAlert:@"哎呀,搜寻基码出错了" actionTitle1:@"换个基码" actionTitle2:@"" window:[NSApplication sharedApplication].keyWindow action:nil];
36 | }];
37 |
38 | }
39 |
40 | + (void)getFundLastJZ:(NSString *)code resp:(void(^)(id resp))resp {
41 |
42 | NSString *timeStr ;
43 | NSString *curWeek = [TimeTool weekdayString];
44 | if ([curWeek isEqualToString:@"周一"]) {
45 | timeStr = [TimeTool getbeforebeforeyesterday];
46 | }else{
47 | timeStr = [TimeTool getLastday];
48 | }
49 |
50 | /**
51 | 一定时间内好像只能查三十个,气人?!
52 |
53 | */
54 | [[NetClient shareHttpInstance] GET:[NSString stringWithFormat:@"http://fund.eastmoney.com/f10/F10DataApi.aspx?type=lsjz&code=%@&&sdate=%@",code,timeStr] parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
55 |
56 | NSString *jzStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
57 |
58 | if ([jzStr containsString:@"%"]) {
59 |
60 | NSRange range = [jzStr rangeOfString:@"%"];
61 | jzStr = [[jzStr substringWithRange:NSMakeRange(range.location - 5, 5)]stringByReplacingOccurrencesOfString:@">" withString:@""];
62 | resp(jzStr);
63 | }
64 |
65 |
66 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
67 | NSLog(@"NSError===%@",error);
68 | [AlertTool showAlert:@"哎呀呀,获取净值出错了" actionTitle1:@"稍后再试" actionTitle2:@"" window:[NSApplication sharedApplication].keyWindow action:nil];
69 | }];
70 | }
71 |
72 | + (void)getIndexInfo:(void(^)(id resp))resp {
73 |
74 | [[NetClient shareJsonInstance] GET:@"https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&fields=f2,f3,f4,f12,f14&secids=1.000001,1.000300,0.399006" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
75 |
76 | NSArray *diffA = responseObject[@"data"][@"diff"];
77 | NSMutableArray *diffM = [NSMutableArray array];
78 | [diffA enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
79 | FundModel *fm = [[FundModel alloc]initWithDic:obj];
80 | [diffM addObject:fm];
81 | }];
82 | resp(diffM);
83 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
84 | NSLog(@"NSError===%@",error);
85 | [AlertTool showAlert:@"哎呀呀,出错了" actionTitle1:@"换个基码" actionTitle2:@"" window:[NSApplication sharedApplication].keyWindow action:nil];
86 | }];
87 |
88 | }
89 |
90 | + (void)getFundRank:(void(^)(id resp))resp {
91 |
92 | [[NetClient shareJsonInstance] GET:[NSString stringWithFormat:@"https://fundmobapi.eastmoney.com/FundMNewApi/FundMNRank?FundType=0&SortColumn=SYL_Y&Sort=desc&pageIndex=1&pageSize=30&BUY=true&CompanyId=&LevelOne=&LevelTwo=&ISABNORMAL=true&DISCOUNT=&RISKLEVEL=&ENDNAV=&RLEVEL_SZ=&ESTABDATE=&TOPICAL=&CLTYPE=&DataConstraintType=0>OKEN=&product=EFund&passportutoken=&deviceid=%@&plat=Iphone&passportctoken=&version=6.4.7",[NSUUID UUID].UUIDString] parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
93 |
94 | NSMutableArray *rankM = [NSMutableArray array];
95 | NSArray *Datas = responseObject[@"Datas"];
96 | [Datas enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
97 | FundModel *fm = [[FundModel alloc]initWithRankDic:obj];
98 | [rankM addObject:fm];
99 | }];
100 | resp(rankM);
101 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
102 | NSLog(@"NSError===%@",error);
103 | [AlertTool showAlert:@"哎呀呀,出错了" actionTitle1:@"换个基码" actionTitle2:@"" window:[NSApplication sharedApplication].keyWindow action:nil];
104 | }];
105 |
106 | }
107 |
108 | @end
109 |
--------------------------------------------------------------------------------
/jj/tool/TimeTool.h:
--------------------------------------------------------------------------------
1 | //
2 | // TimeTool.h
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/8/18.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | NS_ASSUME_NONNULL_BEGIN
12 |
13 | @interface TimeTool : NSObject
14 |
15 | + (NSString*)getCurrentymdhms;
16 | + (NSString *)getbeforebeforeyesterday;
17 | + (NSString *)getLastday;
18 | + (NSString*)weekdayString;
19 |
20 | @end
21 |
22 | NS_ASSUME_NONNULL_END
23 |
--------------------------------------------------------------------------------
/jj/tool/TimeTool.m:
--------------------------------------------------------------------------------
1 | //
2 | // TimeTool.m
3 | // jj
4 | //
5 | // Created by LY_MD on 2020/8/18.
6 | // Copyright © 2020 LY_MD. All rights reserved.
7 | //
8 |
9 | #import "TimeTool.h"
10 |
11 | @implementation TimeTool
12 |
13 | + (NSString*)getCurrentymdhms{
14 |
15 | NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
16 | [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
17 | NSDate *datenow = [NSDate date];
18 | NSString *currentTimeString = [formatter stringFromDate:datenow];
19 | return currentTimeString;
20 |
21 | }
22 |
23 | + (NSString*)getCurrentymd{
24 |
25 | NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
26 | [formatter setDateFormat:@"YYYY-MM-dd"];
27 | NSDate *datenow = [NSDate date];
28 | NSString *currentTimeString = [formatter stringFromDate:datenow];
29 | return currentTimeString;
30 |
31 | }
32 | + (NSString *)getLastday {
33 |
34 | NSTimeInterval secondsPerDay1 = 24*60*60;
35 | NSDate *now = [NSDate date];
36 | NSDate *yesterDay = [now dateByAddingTimeInterval:-secondsPerDay1];
37 | NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
38 | [formatter setDateFormat:@"yyyy-MM-dd"];
39 | NSString *yd=[formatter stringFromDate:yesterDay];
40 | return yd;
41 |
42 | }
43 | + (NSString *)getbeforebeforeyesterday {
44 |
45 | NSTimeInterval secondsPerDay1 = 72*60*60;
46 | NSDate *now = [NSDate date];
47 | NSDate *yesterDay = [now dateByAddingTimeInterval:-secondsPerDay1];
48 | NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
49 | [formatter setDateFormat:@"yyyy-MM-dd"];
50 | NSString *yd=[formatter stringFromDate:yesterDay];
51 | return yd;
52 |
53 | }
54 | + (NSString*)weekdayString {
55 |
56 | NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周末", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
57 |
58 | NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
59 |
60 | NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
61 |
62 | [calendar setTimeZone: timeZone];
63 |
64 | NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
65 |
66 | NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:[NSDate date]];
67 |
68 | return [weekdays objectAtIndex:theComponents.weekday];
69 |
70 | }
71 |
72 | @end
73 |
--------------------------------------------------------------------------------
/resource/kuoluo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/kuoluo.png
--------------------------------------------------------------------------------
/resource/删除.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/删除.png
--------------------------------------------------------------------------------
/resource/持有.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/持有.png
--------------------------------------------------------------------------------
/resource/排序.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/排序.png
--------------------------------------------------------------------------------
/resource/榜单.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/榜单.png
--------------------------------------------------------------------------------
/resource/热心基民.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/热心基民.jpg
--------------------------------------------------------------------------------
/resource/观察.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/resource/观察.png
--------------------------------------------------------------------------------
/基富贵.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Hurdery/jfc/fd3ab8adb585b45a4ad2a95b9609afd350fcc06b/基富贵.zip
--------------------------------------------------------------------------------