├── CYLHttpTest.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── chenyilong.xcuserdatad
│ │ └── WorkspaceSettings.xcsettings
└── xcuserdata
│ └── chenyilong.xcuserdatad
│ └── xcschemes
│ ├── CYLHttpTest.xcscheme
│ └── xcschememanagement.plist
├── CYLHttpTest
├── AppDelegate.h
├── AppDelegate.m
├── Base.lproj
│ ├── LaunchScreen.xib
│ └── Main.storyboard
├── Images.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
├── Info.plist
├── Tool(工具类)
│ ├── AFNetworking
│ │ ├── AFHTTPClient.h
│ │ ├── AFHTTPClient.m
│ │ ├── AFHTTPRequestOperation.h
│ │ ├── AFHTTPRequestOperation.m
│ │ ├── AFImageRequestOperation.h
│ │ ├── AFImageRequestOperation.m
│ │ ├── AFJSONRequestOperation.h
│ │ ├── AFJSONRequestOperation.m
│ │ ├── AFNetworkActivityIndicatorManager.h
│ │ ├── AFNetworkActivityIndicatorManager.m
│ │ ├── AFNetworking.h
│ │ ├── AFPropertyListRequestOperation.h
│ │ ├── AFPropertyListRequestOperation.m
│ │ ├── AFURLConnectionOperation.h
│ │ ├── AFURLConnectionOperation.m
│ │ ├── AFXMLRequestOperation.h
│ │ ├── AFXMLRequestOperation.m
│ │ ├── UIImageView+AFNetworking.h
│ │ └── UIImageView+AFNetworking.m
│ ├── CYLHttpTool
│ │ ├── CYLHttpTestParam.h
│ │ ├── CYLHttpTestParam.m
│ │ ├── CYLHttpTestResult.h
│ │ ├── CYLHttpTestResult.m
│ │ ├── CYLHttpTestTool.h
│ │ ├── CYLHttpTestTool.m
│ │ ├── Category
│ │ │ ├── NSArray+log.h
│ │ │ ├── NSArray+log.m
│ │ │ ├── NSDictionary+log.h
│ │ │ └── NSDictionary+log.m
│ │ └── RequestTool
│ │ │ ├── CYLHttpTool.h
│ │ │ ├── CYLHttpTool.m
│ │ │ ├── NSDictionary+SwitchKeyLowercase.h
│ │ │ ├── NSDictionary+SwitchKeyLowercase.m
│ │ │ ├── XMLReader
│ │ │ ├── README.md
│ │ │ ├── XMLReader.h
│ │ │ └── XMLReader.m
│ │ │ └── xmlwriter
│ │ │ ├── XMLWriter.h
│ │ │ └── XMLWriter.m
│ └── MJExtension
│ │ ├── MJConst.h
│ │ ├── MJConst.m
│ │ ├── MJExtension.h
│ │ ├── MJFoundation.h
│ │ ├── MJFoundation.m
│ │ ├── MJIvar.h
│ │ ├── MJIvar.m
│ │ ├── MJType.h
│ │ ├── MJType.m
│ │ ├── NSObject+MJCoding.h
│ │ ├── NSObject+MJCoding.m
│ │ ├── NSObject+MJIvar.h
│ │ ├── NSObject+MJIvar.m
│ │ ├── NSObject+MJKeyValue.h
│ │ └── NSObject+MJKeyValue.m
├── ViewController.h
├── ViewController.m
└── main.m
└── CYLHttpTestTests
├── CYLHttpTestTests.m
└── Info.plist
/CYLHttpTest.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/CYLHttpTest.xcodeproj/project.xcworkspace/xcuserdata/chenyilong.xcuserdatad/WorkspaceSettings.xcsettings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | HasAskedToTakeAutomaticSnapshotBeforeSignificantChanges
6 |
7 | SnapshotAutomaticallyBeforeSignificantChanges
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/CYLHttpTest.xcodeproj/xcuserdata/chenyilong.xcuserdatad/xcschemes/CYLHttpTest.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
38 |
39 |
44 |
45 |
47 |
53 |
54 |
55 |
56 |
57 |
63 |
64 |
65 |
66 |
75 |
77 |
83 |
84 |
85 |
86 |
87 |
88 |
94 |
96 |
102 |
103 |
104 |
105 |
107 |
108 |
111 |
112 |
113 |
--------------------------------------------------------------------------------
/CYLHttpTest.xcodeproj/xcuserdata/chenyilong.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | CYLHttpTest.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 9AB1F0B31AD3B53E00A0E610
16 |
17 | primary
18 |
19 |
20 | 9AB1F0CC1AD3B53E00A0E610
21 |
22 | primary
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/CYLHttpTest/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface AppDelegate : UIResponder
12 |
13 | @property (strong, nonatomic) UIWindow *window;
14 |
15 |
16 | @end
17 |
18 |
--------------------------------------------------------------------------------
/CYLHttpTest/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import "AppDelegate.h"
10 |
11 | @interface AppDelegate ()
12 |
13 | @end
14 |
15 | @implementation AppDelegate
16 |
17 |
18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
19 | // Override point for customization after application launch.
20 | return YES;
21 | }
22 |
23 | - (void)applicationWillResignActive:(UIApplication *)application {
24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
26 | }
27 |
28 | - (void)applicationDidEnterBackground:(UIApplication *)application {
29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
31 | }
32 |
33 | - (void)applicationWillEnterForeground:(UIApplication *)application {
34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
35 | }
36 |
37 | - (void)applicationDidBecomeActive:(UIApplication *)application {
38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
39 | }
40 |
41 | - (void)applicationWillTerminate:(UIApplication *)application {
42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
43 | }
44 |
45 | @end
46 |
--------------------------------------------------------------------------------
/CYLHttpTest/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
20 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/CYLHttpTest/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/CYLHttpTest/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/CYLHttpTest/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | CYL.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIMainStoryboardFile
28 | Main
29 | UIRequiredDeviceCapabilities
30 |
31 | armv7
32 |
33 | UISupportedInterfaceOrientations
34 |
35 | UIInterfaceOrientationPortrait
36 | UIInterfaceOrientationLandscapeLeft
37 | UIInterfaceOrientationLandscapeRight
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFHTTPRequestOperation.h:
--------------------------------------------------------------------------------
1 | // AFHTTPRequestOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFURLConnectionOperation.h"
25 |
26 | /**
27 | `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
28 | */
29 | @interface AFHTTPRequestOperation : AFURLConnectionOperation
30 |
31 | ///----------------------------------------------
32 | /// @name Getting HTTP URL Connection Information
33 | ///----------------------------------------------
34 |
35 | /**
36 | The last HTTP response received by the operation's connection.
37 | */
38 | @property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
39 |
40 | ///----------------------------------------------------------
41 | /// @name Managing And Checking For Acceptable HTTP Responses
42 | ///----------------------------------------------------------
43 |
44 | /**
45 | A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
46 | */
47 | @property (nonatomic, readonly) BOOL hasAcceptableStatusCode;
48 |
49 | /**
50 | A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
51 | */
52 | @property (nonatomic, readonly) BOOL hasAcceptableContentType;
53 |
54 | /**
55 | The callback dispatch queue on success. If `NULL` (default), the main queue is used.
56 | */
57 | @property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
58 |
59 | /**
60 | The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
61 | */
62 | @property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
63 |
64 | ///------------------------------------------------------------
65 | /// @name Managing Acceptable HTTP Status Codes & Content Types
66 | ///------------------------------------------------------------
67 |
68 | /**
69 | Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
70 |
71 | By default, this is the range 200 to 299, inclusive.
72 | */
73 | + (NSIndexSet *)acceptableStatusCodes;
74 |
75 | /**
76 | Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
77 |
78 | @param statusCodes The status codes to be added to the set of acceptable HTTP status codes
79 | */
80 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
81 |
82 | /**
83 | Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
84 |
85 | By default, this is `nil`.
86 | */
87 | + (NSSet *)acceptableContentTypes;
88 |
89 | /**
90 | Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants.
91 |
92 | @param contentTypes The content types to be added to the set of acceptable MIME types
93 | */
94 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes;
95 |
96 |
97 | ///-----------------------------------------------------
98 | /// @name Determining Whether A Request Can Be Processed
99 | ///-----------------------------------------------------
100 |
101 | /**
102 | A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
103 |
104 | @param urlRequest The request that is determined to be supported or not supported for this class.
105 | */
106 | + (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
107 |
108 | ///-----------------------------------------------------------
109 | /// @name Setting Completion Block Success / Failure Callbacks
110 | ///-----------------------------------------------------------
111 |
112 | /**
113 | Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
114 |
115 | This method should be overridden in subclasses in order to specify the response object passed into the success block.
116 |
117 | @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
118 | @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
119 | */
120 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
121 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
122 |
123 | @end
124 |
125 | ///----------------
126 | /// @name Functions
127 | ///----------------
128 |
129 | /**
130 | Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
131 | */
132 | extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
133 |
134 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFHTTPRequestOperation.m:
--------------------------------------------------------------------------------
1 | // AFHTTPRequestOperation.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h"
24 | #import
25 |
26 | // Workaround for change in imp_implementationWithBlock() with Xcode 4.5
27 | #if defined(__IPHONE_6_0) || defined(__MAC_10_8)
28 | #define AF_CAST_TO_BLOCK id
29 | #else
30 | #define AF_CAST_TO_BLOCK __bridge void *
31 | #endif
32 |
33 | #pragma clang diagnostic push
34 | #pragma clang diagnostic ignored "-Wstrict-selector-match"
35 |
36 | NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
37 | if (!string) {
38 | return nil;
39 | }
40 |
41 | NSArray *mediaRanges = [string componentsSeparatedByString:@","];
42 | NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count];
43 |
44 | [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) {
45 | NSRange parametersRange = [mediaRange rangeOfString:@";"];
46 | if (parametersRange.location != NSNotFound) {
47 | mediaRange = [mediaRange substringToIndex:parametersRange.location];
48 | }
49 |
50 | mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
51 |
52 | if (mediaRange.length > 0) {
53 | [mutableContentTypes addObject:mediaRange];
54 | }
55 | }];
56 |
57 | return [NSSet setWithSet:mutableContentTypes];
58 | }
59 |
60 | static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) {
61 | if (!string) {
62 | return;
63 | }
64 |
65 | NSScanner *scanner = [NSScanner scannerWithString:string];
66 | [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
67 | [scanner scanUpToString:@"/" intoString:type];
68 | [scanner scanString:@"/" intoString:nil];
69 | [scanner scanUpToString:@";" intoString:subtype];
70 | }
71 |
72 | static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
73 | NSMutableString *string = [NSMutableString string];
74 |
75 | NSRange range = NSMakeRange([indexSet firstIndex], 1);
76 | while (range.location != NSNotFound) {
77 | NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
78 | while (nextIndex == range.location + range.length) {
79 | range.length++;
80 | nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
81 | }
82 |
83 | if (string.length) {
84 | [string appendString:@","];
85 | }
86 |
87 | if (range.length == 1) {
88 | [string appendFormat:@"%lu", (long)range.location];
89 | } else {
90 | NSUInteger firstIndex = range.location;
91 | NSUInteger lastIndex = firstIndex + range.length - 1;
92 | [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
93 | }
94 |
95 | range.location = nextIndex;
96 | range.length = 1;
97 | }
98 |
99 | return string;
100 | }
101 |
102 | static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
103 | Method originalMethod = class_getClassMethod(klass, selector);
104 | IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
105 | class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
106 | }
107 |
108 | #pragma mark -
109 |
110 | @interface AFHTTPRequestOperation ()
111 | @property (readwrite, nonatomic, strong) NSURLRequest *request;
112 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
113 | @property (readwrite, nonatomic, strong) NSError *HTTPError;
114 | @end
115 |
116 | @implementation AFHTTPRequestOperation
117 | @synthesize HTTPError = _HTTPError;
118 | @synthesize successCallbackQueue = _successCallbackQueue;
119 | @synthesize failureCallbackQueue = _failureCallbackQueue;
120 | @dynamic request;
121 | @dynamic response;
122 |
123 | - (void)dealloc {
124 | if (_successCallbackQueue) {
125 | #if !OS_OBJECT_USE_OBJC
126 | dispatch_release(_successCallbackQueue);
127 | #endif
128 | _successCallbackQueue = NULL;
129 | }
130 |
131 | if (_failureCallbackQueue) {
132 | #if !OS_OBJECT_USE_OBJC
133 | dispatch_release(_failureCallbackQueue);
134 | #endif
135 | _failureCallbackQueue = NULL;
136 | }
137 | }
138 |
139 | - (NSError *)error {
140 | if (!self.HTTPError && self.response) {
141 | if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
142 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
143 | [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
144 | [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
145 | [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
146 | [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
147 |
148 | if (![self hasAcceptableStatusCode]) {
149 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
150 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
151 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
152 | } else if (![self hasAcceptableContentType]) {
153 | // Don't invalidate content type if there is no content
154 | if ([self.responseData length] > 0) {
155 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
156 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
157 | }
158 | }
159 | }
160 | }
161 |
162 | if (self.HTTPError) {
163 | return self.HTTPError;
164 | } else {
165 | return [super error];
166 | }
167 | }
168 |
169 | - (NSStringEncoding)responseStringEncoding {
170 | // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value.
171 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1
172 | if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) {
173 | NSString *type = nil;
174 | AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil);
175 |
176 | if ([type isEqualToString:@"text"]) {
177 | return NSISOLatin1StringEncoding;
178 | }
179 | }
180 |
181 | return [super responseStringEncoding];
182 | }
183 |
184 | - (void)pause {
185 | unsigned long long offset = 0;
186 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
187 | offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
188 | } else {
189 | offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
190 | }
191 |
192 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
193 | if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
194 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
195 | }
196 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
197 | self.request = mutableURLRequest;
198 |
199 | [super pause];
200 | }
201 |
202 | - (BOOL)hasAcceptableStatusCode {
203 | if (!self.response) {
204 | return NO;
205 | }
206 |
207 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
208 | return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
209 | }
210 |
211 | - (BOOL)hasAcceptableContentType {
212 | if (!self.response) {
213 | return NO;
214 | }
215 |
216 | // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
217 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
218 | NSString *contentType = [self.response MIMEType];
219 | if (!contentType) {
220 | contentType = @"application/octet-stream";
221 | }
222 |
223 | return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
224 | }
225 |
226 | - (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
227 | if (successCallbackQueue != _successCallbackQueue) {
228 | if (_successCallbackQueue) {
229 | #if !OS_OBJECT_USE_OBJC
230 | dispatch_release(_successCallbackQueue);
231 | #endif
232 | _successCallbackQueue = NULL;
233 | }
234 |
235 | if (successCallbackQueue) {
236 | #if !OS_OBJECT_USE_OBJC
237 | dispatch_retain(successCallbackQueue);
238 | #endif
239 | _successCallbackQueue = successCallbackQueue;
240 | }
241 | }
242 | }
243 |
244 | - (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
245 | if (failureCallbackQueue != _failureCallbackQueue) {
246 | if (_failureCallbackQueue) {
247 | #if !OS_OBJECT_USE_OBJC
248 | dispatch_release(_failureCallbackQueue);
249 | #endif
250 | _failureCallbackQueue = NULL;
251 | }
252 |
253 | if (failureCallbackQueue) {
254 | #if !OS_OBJECT_USE_OBJC
255 | dispatch_retain(failureCallbackQueue);
256 | #endif
257 | _failureCallbackQueue = failureCallbackQueue;
258 | }
259 | }
260 | }
261 |
262 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
263 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
264 | {
265 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
266 | #pragma clang diagnostic push
267 | #pragma clang diagnostic ignored "-Warc-retain-cycles"
268 | #pragma clang diagnostic ignored "-Wgnu"
269 | self.completionBlock = ^{
270 | if (self.error) {
271 | if (failure) {
272 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
273 | failure(self, self.error);
274 | });
275 | }
276 | } else {
277 | if (success) {
278 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
279 | success(self, self.responseData);
280 | });
281 | }
282 | }
283 | };
284 | #pragma clang diagnostic pop
285 | }
286 |
287 | #pragma mark - AFHTTPRequestOperation
288 |
289 | + (NSIndexSet *)acceptableStatusCodes {
290 | return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
291 | }
292 |
293 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
294 | NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
295 | [mutableStatusCodes addIndexes:statusCodes];
296 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) {
297 | return mutableStatusCodes;
298 | });
299 | }
300 |
301 | + (NSSet *)acceptableContentTypes {
302 | return nil;
303 | }
304 |
305 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes {
306 | NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
307 | [mutableContentTypes unionSet:contentTypes];
308 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) {
309 | return mutableContentTypes;
310 | });
311 | }
312 |
313 | + (BOOL)canProcessRequest:(NSURLRequest *)request {
314 | if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
315 | return YES;
316 | }
317 |
318 | return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
319 | }
320 |
321 | @end
322 |
323 | #pragma clang diagnostic pop
324 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFImageRequestOperation.h:
--------------------------------------------------------------------------------
1 | // AFImageRequestOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h"
25 |
26 | #import
27 |
28 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
29 | #import
30 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
31 | #import
32 | #endif
33 |
34 | /**
35 | `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images.
36 |
37 | ## Acceptable Content Types
38 |
39 | By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
40 |
41 | - `image/tiff`
42 | - `image/jpeg`
43 | - `image/gif`
44 | - `image/png`
45 | - `image/ico`
46 | - `image/x-icon`
47 | - `image/bmp`
48 | - `image/x-bmp`
49 | - `image/x-xbitmap`
50 | - `image/x-win-bitmap`
51 | */
52 | @interface AFImageRequestOperation : AFHTTPRequestOperation
53 |
54 | /**
55 | An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
56 | */
57 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
58 | @property (readonly, nonatomic, strong) UIImage *responseImage;
59 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
60 | @property (readonly, nonatomic, strong) NSImage *responseImage;
61 | #endif
62 |
63 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
64 | /**
65 | 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.
66 | */
67 | @property (nonatomic, assign) CGFloat imageScale;
68 |
69 | /**
70 | 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.
71 | */
72 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
73 | #endif
74 |
75 | /**
76 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
77 |
78 | @param urlRequest The request object to be loaded asynchronously during execution of the operation.
79 | @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request.
80 |
81 | @return A new image request operation
82 | */
83 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
84 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
85 | success:(void (^)(UIImage *image))success;
86 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
87 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
88 | success:(void (^)(NSImage *image))success;
89 | #endif
90 |
91 | /**
92 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
93 |
94 | @param urlRequest The request object to be loaded asynchronously during execution of the operation.
95 | @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
96 | @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
97 | @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
98 |
99 | @return A new image request operation
100 | */
101 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
102 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
103 | imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
104 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
105 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
106 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
107 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
108 | imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
109 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
110 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
111 | #endif
112 |
113 | @end
114 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFImageRequestOperation.m:
--------------------------------------------------------------------------------
1 | // AFImageRequestOperation.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFImageRequestOperation.h"
24 |
25 | static dispatch_queue_t image_request_operation_processing_queue() {
26 | static dispatch_queue_t af_image_request_operation_processing_queue;
27 | static dispatch_once_t onceToken;
28 | dispatch_once(&onceToken, ^{
29 | af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT);
30 | });
31 |
32 | return af_image_request_operation_processing_queue;
33 | }
34 |
35 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
36 | #import
37 |
38 | static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
39 | if ([UIImage instancesRespondToSelector:@selector(initWithData:scale:)]) {
40 | return [[UIImage alloc] initWithData:data scale:scale];
41 | } else {
42 | UIImage *image = [[UIImage alloc] initWithData:data];
43 | return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
44 | }
45 | }
46 |
47 | static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
48 | if (!data || [data length] == 0) {
49 | return nil;
50 | }
51 |
52 | UIImage *image = AFImageWithDataAtScale(data, scale);
53 | if (image.images) {
54 | return image;
55 | }
56 |
57 | CGImageRef imageRef = nil;
58 | CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
59 |
60 | if ([response.MIMEType isEqualToString:@"image/png"]) {
61 | imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
62 | } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
63 | imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
64 | }
65 |
66 | if (!imageRef) {
67 | imageRef = CGImageCreateCopy([image CGImage]);
68 |
69 | if (!imageRef) {
70 | return image;
71 | }
72 | }
73 |
74 | CGDataProviderRelease(dataProvider);
75 |
76 | size_t width = CGImageGetWidth(imageRef);
77 | size_t height = CGImageGetHeight(imageRef);
78 | size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
79 | size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate()
80 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
81 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
82 |
83 | if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
84 | int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
85 | if (alpha == kCGImageAlphaNone) {
86 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
87 | bitmapInfo |= kCGImageAlphaNoneSkipFirst;
88 | } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
89 | bitmapInfo &= ~kCGBitmapAlphaInfoMask;
90 | bitmapInfo |= kCGImageAlphaPremultipliedFirst;
91 | }
92 | }
93 |
94 | CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
95 |
96 | CGColorSpaceRelease(colorSpace);
97 |
98 | if (!context) {
99 | CGImageRelease(imageRef);
100 |
101 | return image;
102 | }
103 |
104 | CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
105 | CGContextDrawImage(context, rect, imageRef);
106 | CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
107 | CGContextRelease(context);
108 |
109 | UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
110 | CGImageRelease(inflatedImageRef);
111 | CGImageRelease(imageRef);
112 |
113 | return inflatedImage;
114 | }
115 | #endif
116 |
117 | @interface AFImageRequestOperation ()
118 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
119 | @property (readwrite, nonatomic, strong) UIImage *responseImage;
120 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
121 | @property (readwrite, nonatomic, strong) NSImage *responseImage;
122 | #endif
123 | @end
124 |
125 | @implementation AFImageRequestOperation
126 | @synthesize responseImage = _responseImage;
127 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
128 | @synthesize imageScale = _imageScale;
129 | #endif
130 |
131 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
132 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
133 | success:(void (^)(UIImage *image))success
134 | {
135 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
136 | if (success) {
137 | success(image);
138 | }
139 | } failure:nil];
140 | }
141 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
142 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
143 | success:(void (^)(NSImage *image))success
144 | {
145 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
146 | if (success) {
147 | success(image);
148 | }
149 | } failure:nil];
150 | }
151 | #endif
152 |
153 |
154 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
155 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
156 | imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
157 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
158 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
159 | {
160 | AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
161 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
162 | if (success) {
163 | UIImage *image = responseObject;
164 | if (imageProcessingBlock) {
165 | dispatch_async(image_request_operation_processing_queue(), ^(void) {
166 | UIImage *processedImage = imageProcessingBlock(image);
167 | #pragma clang diagnostic push
168 | #pragma clang diagnostic ignored "-Wgnu"
169 | dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
170 | success(operation.request, operation.response, processedImage);
171 | });
172 | #pragma clang diagnostic pop
173 | });
174 | } else {
175 | success(operation.request, operation.response, image);
176 | }
177 | }
178 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
179 | if (failure) {
180 | failure(operation.request, operation.response, error);
181 | }
182 | }];
183 |
184 |
185 | return requestOperation;
186 | }
187 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
188 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
189 | imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
190 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
191 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
192 | {
193 | AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest];
194 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
195 | if (success) {
196 | NSImage *image = responseObject;
197 | if (imageProcessingBlock) {
198 | dispatch_async(image_request_operation_processing_queue(), ^(void) {
199 | NSImage *processedImage = imageProcessingBlock(image);
200 |
201 | dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
202 | success(operation.request, operation.response, processedImage);
203 | });
204 | });
205 | } else {
206 | success(operation.request, operation.response, image);
207 | }
208 | }
209 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
210 | if (failure) {
211 | failure(operation.request, operation.response, error);
212 | }
213 | }];
214 |
215 | return requestOperation;
216 | }
217 | #endif
218 |
219 | - (id)initWithRequest:(NSURLRequest *)urlRequest {
220 | self = [super initWithRequest:urlRequest];
221 | if (!self) {
222 | return nil;
223 | }
224 |
225 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
226 | self.imageScale = [[UIScreen mainScreen] scale];
227 | self.automaticallyInflatesResponseImage = YES;
228 | #endif
229 |
230 | return self;
231 | }
232 |
233 |
234 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
235 | - (UIImage *)responseImage {
236 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
237 | if (self.automaticallyInflatesResponseImage) {
238 | self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale);
239 | } else {
240 | self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale);
241 | }
242 | }
243 |
244 | return _responseImage;
245 | }
246 |
247 | - (void)setImageScale:(CGFloat)imageScale {
248 | #pragma clang diagnostic push
249 | #pragma clang diagnostic ignored "-Wfloat-equal"
250 | if (imageScale == _imageScale) {
251 | return;
252 | }
253 | #pragma clang diagnostic pop
254 |
255 | _imageScale = imageScale;
256 |
257 | self.responseImage = nil;
258 | }
259 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
260 | - (NSImage *)responseImage {
261 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
262 | // Ensure that the image is set to it's correct pixel width and height
263 | NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
264 | self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
265 | [self.responseImage addRepresentation:bitimage];
266 | }
267 |
268 | return _responseImage;
269 | }
270 | #endif
271 |
272 | #pragma mark - AFHTTPRequestOperation
273 |
274 | + (NSSet *)acceptableContentTypes {
275 | return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
276 | }
277 |
278 | + (BOOL)canProcessRequest:(NSURLRequest *)request {
279 | static NSSet * _acceptablePathExtension = nil;
280 | static dispatch_once_t onceToken;
281 | dispatch_once(&onceToken, ^{
282 | _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
283 | });
284 |
285 | return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
286 | }
287 |
288 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
289 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
290 | {
291 | #pragma clang diagnostic push
292 | #pragma clang diagnostic ignored "-Warc-retain-cycles"
293 | #pragma clang diagnostic ignored "-Wgnu"
294 |
295 | self.completionBlock = ^ {
296 | dispatch_async(image_request_operation_processing_queue(), ^(void) {
297 | if (self.error) {
298 | if (failure) {
299 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
300 | failure(self, self.error);
301 | });
302 | }
303 | } else {
304 | if (success) {
305 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
306 | UIImage *image = nil;
307 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
308 | NSImage *image = nil;
309 | #endif
310 |
311 | image = self.responseImage;
312 |
313 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
314 | success(self, image);
315 | });
316 | }
317 | }
318 | });
319 | };
320 | #pragma clang diagnostic pop
321 | }
322 |
323 | @end
324 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFJSONRequestOperation.h:
--------------------------------------------------------------------------------
1 | // AFJSONRequestOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h"
25 |
26 | /**
27 | `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
28 |
29 | ## Acceptable Content Types
30 |
31 | By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
32 |
33 | - `application/json`
34 | - `text/json`
35 |
36 | @warning JSON parsing will use the built-in `NSJSONSerialization` class.
37 | */
38 | @interface AFJSONRequestOperation : AFHTTPRequestOperation
39 |
40 | ///----------------------------
41 | /// @name Getting Response Data
42 | ///----------------------------
43 |
44 | /**
45 | A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
46 | */
47 | @property (readonly, nonatomic, strong) id responseJSON;
48 |
49 | /**
50 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions".
51 | */
52 | @property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions;
53 |
54 | ///----------------------------------
55 | /// @name Creating Request Operations
56 | ///----------------------------------
57 |
58 | /**
59 | Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
60 |
61 | @param urlRequest The request object to be loaded asynchronously during execution of the operation
62 | @param success A block object to be executed when the operation 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 JSON object created from the response data of request.
63 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. 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 describing the network or parsing error that occurred.
64 |
65 | @return A new JSON request operation
66 | */
67 | + (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
70 |
71 | @end
72 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFJSONRequestOperation.m:
--------------------------------------------------------------------------------
1 | // AFJSONRequestOperation.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFJSONRequestOperation.h"
24 |
25 | static dispatch_queue_t json_request_operation_processing_queue() {
26 | static dispatch_queue_t af_json_request_operation_processing_queue;
27 | static dispatch_once_t onceToken;
28 | dispatch_once(&onceToken, ^{
29 | af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT);
30 | });
31 |
32 | return af_json_request_operation_processing_queue;
33 | }
34 |
35 | @interface AFJSONRequestOperation ()
36 | @property (readwrite, nonatomic, strong) id responseJSON;
37 | @property (readwrite, nonatomic, strong) NSError *JSONError;
38 | @property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
39 | @end
40 |
41 | @implementation AFJSONRequestOperation
42 | @synthesize responseJSON = _responseJSON;
43 | @synthesize JSONReadingOptions = _JSONReadingOptions;
44 | @synthesize JSONError = _JSONError;
45 | @dynamic lock;
46 |
47 | + (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
48 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
49 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
50 | {
51 | AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest];
52 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
53 | if (success) {
54 | success(operation.request, operation.response, responseObject);
55 | }
56 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
57 | if (failure) {
58 | failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
59 | }
60 | }];
61 |
62 | return requestOperation;
63 | }
64 |
65 |
66 | - (id)responseJSON {
67 | [self.lock lock];
68 | if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
69 | NSError *error = nil;
70 |
71 | // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
72 | // See https://github.com/rails/rails/issues/1742
73 | if (self.responseString && ![self.responseString isEqualToString:@" "]) {
74 | // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
75 | // See http://stackoverflow.com/a/12843465/157142
76 | NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding];
77 |
78 | if (data) {
79 | self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error];
80 | } else {
81 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
82 | [userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey];
83 | [userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey];
84 | error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
85 | }
86 | }
87 |
88 | self.JSONError = error;
89 | }
90 | [self.lock unlock];
91 |
92 | return _responseJSON;
93 | }
94 |
95 | - (NSError *)error {
96 | if (_JSONError) {
97 | return _JSONError;
98 | } else {
99 | return [super error];
100 | }
101 | }
102 |
103 | #pragma mark - AFHTTPRequestOperation
104 |
105 | + (NSSet *)acceptableContentTypes {
106 | return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
107 | }
108 |
109 | + (BOOL)canProcessRequest:(NSURLRequest *)request {
110 | return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
111 | }
112 |
113 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
114 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
115 | {
116 | #pragma clang diagnostic push
117 | #pragma clang diagnostic ignored "-Warc-retain-cycles"
118 | #pragma clang diagnostic ignored "-Wgnu"
119 |
120 | self.completionBlock = ^ {
121 | if (self.error) {
122 | if (failure) {
123 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
124 | failure(self, self.error);
125 | });
126 | }
127 | } else {
128 | dispatch_async(json_request_operation_processing_queue(), ^{
129 | id JSON = self.responseJSON;
130 |
131 | if (self.error) {
132 | if (failure) {
133 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
134 | failure(self, self.error);
135 | });
136 | }
137 | } else {
138 | if (success) {
139 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
140 | success(self, JSON);
141 | });
142 | }
143 | }
144 | });
145 | }
146 | };
147 | #pragma clang diagnostic pop
148 | }
149 |
150 | @end
151 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFNetworkActivityIndicatorManager.h:
--------------------------------------------------------------------------------
1 | // AFNetworkActivityIndicatorManager.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 |
25 | #import
26 |
27 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
28 | #import
29 |
30 | /**
31 | `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation 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.
32 |
33 | 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:
34 |
35 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
36 |
37 | By setting `isNetworkActivityIndicatorVisible` 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.
38 |
39 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
40 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
41 | */
42 | @interface AFNetworkActivityIndicatorManager : NSObject
43 |
44 | /**
45 | A Boolean value indicating whether the manager is enabled.
46 |
47 | If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
48 | */
49 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled;
50 |
51 | /**
52 | A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
53 | */
54 | @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
55 |
56 | /**
57 | Returns the shared network activity indicator manager object for the system.
58 |
59 | @return The systemwide network activity indicator manager.
60 | */
61 | + (instancetype)sharedManager;
62 |
63 | /**
64 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
65 | */
66 | - (void)incrementActivityCount;
67 |
68 | /**
69 | Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator.
70 | */
71 | - (void)decrementActivityCount;
72 |
73 | @end
74 |
75 | #endif
76 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFNetworkActivityIndicatorManager.m:
--------------------------------------------------------------------------------
1 | // AFNetworkActivityIndicatorManager.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFNetworkActivityIndicatorManager.h"
24 |
25 | #import "AFHTTPRequestOperation.h"
26 |
27 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
28 | static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
29 |
30 | @interface AFNetworkActivityIndicatorManager ()
31 | @property (readwrite, nonatomic, assign) NSInteger activityCount;
32 | @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer;
33 | @property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
34 |
35 | - (void)updateNetworkActivityIndicatorVisibility;
36 | - (void)updateNetworkActivityIndicatorVisibilityDelayed;
37 | @end
38 |
39 | @implementation AFNetworkActivityIndicatorManager
40 | @synthesize activityCount = _activityCount;
41 | @synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
42 | @synthesize enabled = _enabled;
43 | @dynamic networkActivityIndicatorVisible;
44 |
45 | + (instancetype)sharedManager {
46 | static AFNetworkActivityIndicatorManager *_sharedManager = nil;
47 | static dispatch_once_t oncePredicate;
48 | dispatch_once(&oncePredicate, ^{
49 | _sharedManager = [[self alloc] init];
50 | });
51 |
52 | return _sharedManager;
53 | }
54 |
55 | + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
56 | return [NSSet setWithObject:@"activityCount"];
57 | }
58 |
59 | - (id)init {
60 | self = [super init];
61 | if (!self) {
62 | return nil;
63 | }
64 |
65 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil];
66 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil];
67 |
68 | return self;
69 | }
70 |
71 | - (void)dealloc {
72 | [[NSNotificationCenter defaultCenter] removeObserver:self];
73 |
74 | [_activityIndicatorVisibilityTimer invalidate];
75 |
76 | }
77 |
78 | - (void)updateNetworkActivityIndicatorVisibilityDelayed {
79 | if (self.enabled) {
80 | // Delay hiding of activity indicator for a short interval, to avoid flickering
81 | if (![self isNetworkActivityIndicatorVisible]) {
82 | [self.activityIndicatorVisibilityTimer invalidate];
83 | self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
84 | [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
85 | } else {
86 | [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
87 | }
88 | }
89 | }
90 |
91 | - (BOOL)isNetworkActivityIndicatorVisible {
92 | return _activityCount > 0;
93 | }
94 |
95 | - (void)updateNetworkActivityIndicatorVisibility {
96 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
97 | }
98 |
99 | // Not exposed, but used if activityCount is set via KVC.
100 | - (NSInteger)activityCount {
101 | return _activityCount;
102 | }
103 |
104 | - (void)setActivityCount:(NSInteger)activityCount {
105 | @synchronized(self) {
106 | _activityCount = activityCount;
107 | }
108 |
109 | dispatch_async(dispatch_get_main_queue(), ^{
110 | [self updateNetworkActivityIndicatorVisibilityDelayed];
111 | });
112 | }
113 |
114 | - (void)incrementActivityCount {
115 | [self willChangeValueForKey:@"activityCount"];
116 | @synchronized(self) {
117 | _activityCount++;
118 | }
119 | [self didChangeValueForKey:@"activityCount"];
120 |
121 | dispatch_async(dispatch_get_main_queue(), ^{
122 | [self updateNetworkActivityIndicatorVisibilityDelayed];
123 | });
124 | }
125 |
126 | - (void)decrementActivityCount {
127 | [self willChangeValueForKey:@"activityCount"];
128 | @synchronized(self) {
129 | #pragma clang diagnostic push
130 | #pragma clang diagnostic ignored "-Wgnu"
131 | _activityCount = MAX(_activityCount - 1, 0);
132 | #pragma clang diagnostic pop
133 | }
134 | [self didChangeValueForKey:@"activityCount"];
135 |
136 | dispatch_async(dispatch_get_main_queue(), ^{
137 | [self updateNetworkActivityIndicatorVisibilityDelayed];
138 | });
139 | }
140 |
141 | - (void)networkingOperationDidStart:(NSNotification *)notification {
142 | AFURLConnectionOperation *connectionOperation = [notification object];
143 | if (connectionOperation.request.URL) {
144 | [self incrementActivityCount];
145 | }
146 | }
147 |
148 | - (void)networkingOperationDidFinish:(NSNotification *)notification {
149 | AFURLConnectionOperation *connectionOperation = [notification object];
150 | if (connectionOperation.request.URL) {
151 | [self decrementActivityCount];
152 | }
153 | }
154 |
155 | @end
156 |
157 | #endif
158 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFNetworking.h:
--------------------------------------------------------------------------------
1 | // AFNetworking.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 |
26 | #ifndef _AFNETWORKING_
27 | #define _AFNETWORKING_
28 |
29 | #import "AFURLConnectionOperation.h"
30 |
31 | #import "AFHTTPRequestOperation.h"
32 | #import "AFJSONRequestOperation.h"
33 | #import "AFXMLRequestOperation.h"
34 | #import "AFPropertyListRequestOperation.h"
35 | #import "AFHTTPClient.h"
36 |
37 | #import "AFImageRequestOperation.h"
38 |
39 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
40 | #import "AFNetworkActivityIndicatorManager.h"
41 | #import "UIImageView+AFNetworking.h"
42 | #endif
43 | #endif /* _AFNETWORKING_ */
44 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFPropertyListRequestOperation.h:
--------------------------------------------------------------------------------
1 | // AFPropertyListRequestOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h"
25 |
26 | /**
27 | `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
28 |
29 | ## Acceptable Content Types
30 |
31 | By default, `AFPropertyListRequestOperation` accepts the following MIME types:
32 |
33 | - `application/x-plist`
34 | */
35 | @interface AFPropertyListRequestOperation : AFHTTPRequestOperation
36 |
37 | ///----------------------------
38 | /// @name Getting Response Data
39 | ///----------------------------
40 |
41 | /**
42 | An object deserialized from a plist constructed using the response data.
43 | */
44 | @property (readonly, nonatomic) id responsePropertyList;
45 |
46 | ///--------------------------------------
47 | /// @name Managing Property List Behavior
48 | ///--------------------------------------
49 |
50 | /**
51 | One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`.
52 | */
53 | @property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
54 |
55 | /**
56 | Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
57 |
58 | @param urlRequest The request object to be loaded asynchronously during execution of the operation
59 | @param success A block object to be executed when the operation 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 object deserialized from a plist constructed using the response data.
60 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. 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 describing the network or parsing error that occurred.
61 |
62 | @return A new property list request operation
63 | */
64 | + (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
65 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
66 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure;
67 |
68 | @end
69 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFPropertyListRequestOperation.m:
--------------------------------------------------------------------------------
1 | // AFPropertyListRequestOperation.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFPropertyListRequestOperation.h"
24 |
25 | static dispatch_queue_t property_list_request_operation_processing_queue() {
26 | static dispatch_queue_t af_property_list_request_operation_processing_queue;
27 | static dispatch_once_t onceToken;
28 | dispatch_once(&onceToken, ^{
29 | af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT);
30 | });
31 |
32 | return af_property_list_request_operation_processing_queue;
33 | }
34 |
35 | @interface AFPropertyListRequestOperation ()
36 | @property (readwrite, nonatomic) id responsePropertyList;
37 | @property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
38 | @property (readwrite, nonatomic) NSError *propertyListError;
39 | @end
40 |
41 | @implementation AFPropertyListRequestOperation
42 | @synthesize responsePropertyList = _responsePropertyList;
43 | @synthesize propertyListReadOptions = _propertyListReadOptions;
44 | @synthesize propertyListFormat = _propertyListFormat;
45 | @synthesize propertyListError = _propertyListError;
46 |
47 | + (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request
48 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
49 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure
50 | {
51 | AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request];
52 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
53 | if (success) {
54 | success(operation.request, operation.response, responseObject);
55 | }
56 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
57 | if (failure) {
58 | failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
59 | }
60 | }];
61 |
62 | return requestOperation;
63 | }
64 |
65 | - (id)initWithRequest:(NSURLRequest *)urlRequest {
66 | self = [super initWithRequest:urlRequest];
67 | if (!self) {
68 | return nil;
69 | }
70 |
71 | self.propertyListReadOptions = NSPropertyListImmutable;
72 |
73 | return self;
74 | }
75 |
76 |
77 | - (id)responsePropertyList {
78 | if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) {
79 | NSPropertyListFormat format;
80 | NSError *error = nil;
81 | self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
82 | self.propertyListFormat = format;
83 | self.propertyListError = error;
84 | }
85 |
86 | return _responsePropertyList;
87 | }
88 |
89 | - (NSError *)error {
90 | if (_propertyListError) {
91 | return _propertyListError;
92 | } else {
93 | return [super error];
94 | }
95 | }
96 |
97 | #pragma mark - AFHTTPRequestOperation
98 |
99 | + (NSSet *)acceptableContentTypes {
100 | return [NSSet setWithObjects:@"application/x-plist", nil];
101 | }
102 |
103 | + (BOOL)canProcessRequest:(NSURLRequest *)request {
104 | return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request];
105 | }
106 |
107 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
108 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
109 | {
110 | #pragma clang diagnostic push
111 | #pragma clang diagnostic ignored "-Warc-retain-cycles"
112 | #pragma clang diagnostic ignored "-Wgnu"
113 | self.completionBlock = ^ {
114 | if (self.error) {
115 | if (failure) {
116 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
117 | failure(self, self.error);
118 | });
119 | }
120 | } else {
121 | dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
122 | id propertyList = self.responsePropertyList;
123 |
124 | if (self.propertyListError) {
125 | if (failure) {
126 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
127 | failure(self, self.error);
128 | });
129 | }
130 | } else {
131 | if (success) {
132 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
133 | success(self, propertyList);
134 | });
135 | }
136 | }
137 | });
138 | }
139 | };
140 | #pragma clang diagnostic pop
141 | }
142 |
143 | @end
144 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFURLConnectionOperation.h:
--------------------------------------------------------------------------------
1 | // AFURLConnectionOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 |
25 | #import
26 |
27 | /**
28 | `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
29 |
30 | ## Subclassing Notes
31 |
32 | This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
33 |
34 | If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
35 |
36 | ## NSURLConnection Delegate Methods
37 |
38 | `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
39 |
40 | - `connection:didReceiveResponse:`
41 | - `connection:didReceiveData:`
42 | - `connectionDidFinishLoading:`
43 | - `connection:didFailWithError:`
44 | - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
45 | - `connection:willCacheResponse:`
46 | - `connectionShouldUseCredentialStorage:`
47 | - `connection:needNewBodyStream:`
48 | - `connection:willSendRequestForAuthenticationChallenge:`
49 |
50 | If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
51 |
52 | ## Class Constructors
53 |
54 | Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
55 |
56 | ## Callbacks and Completion Blocks
57 |
58 | The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
59 |
60 | Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
61 |
62 | ## SSL Pinning
63 |
64 | Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle.
65 |
66 | SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
67 |
68 | When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
69 |
70 | ## NSCoding & NSCopying Conformance
71 |
72 | `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
73 |
74 | ### NSCoding Caveats
75 |
76 | - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
77 | - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
78 |
79 | ### NSCopying Caveats
80 |
81 | - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
82 | - A copy of an operation will not include the `outputStream` of the original.
83 | - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
84 | */
85 |
86 | typedef enum {
87 | AFSSLPinningModeNone,
88 | AFSSLPinningModePublicKey,
89 | AFSSLPinningModeCertificate,
90 | } AFURLConnectionOperationSSLPinningMode;
91 |
92 | @interface AFURLConnectionOperation : NSOperation = 50000) || \
94 | (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
95 | NSURLConnectionDataDelegate,
96 | #endif
97 | NSCoding, NSCopying>
98 |
99 | ///-------------------------------
100 | /// @name Accessing Run Loop Modes
101 | ///-------------------------------
102 |
103 | /**
104 | The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
105 | */
106 | @property (nonatomic, strong) NSSet *runLoopModes;
107 |
108 | ///-----------------------------------------
109 | /// @name Getting URL Connection Information
110 | ///-----------------------------------------
111 |
112 | /**
113 | The request used by the operation's connection.
114 | */
115 | @property (readonly, nonatomic, strong) NSURLRequest *request;
116 |
117 | /**
118 | The last response received by the operation's connection.
119 | */
120 | @property (readonly, nonatomic, strong) NSURLResponse *response;
121 |
122 | /**
123 | The error, if any, that occurred in the lifecycle of the request.
124 | */
125 | @property (readonly, nonatomic, strong) NSError *error;
126 |
127 | /**
128 | Whether the connection should accept an invalid SSL certificate.
129 |
130 | If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`.
131 | */
132 | @property (nonatomic, assign) BOOL allowsInvalidSSLCertificate;
133 |
134 | ///----------------------------
135 | /// @name Getting Response Data
136 | ///----------------------------
137 |
138 | /**
139 | The data received during the request.
140 | */
141 | @property (readonly, nonatomic, strong) NSData *responseData;
142 |
143 | /**
144 | The string representation of the response data.
145 | */
146 | @property (readonly, nonatomic, copy) NSString *responseString;
147 |
148 | /**
149 | The string encoding of the response.
150 |
151 | If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
152 | */
153 | @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
154 |
155 | ///-------------------------------
156 | /// @name Managing URL Credentials
157 | ///-------------------------------
158 |
159 | /**
160 | Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
161 |
162 | This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
163 | */
164 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
165 |
166 | /**
167 | The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
168 |
169 | This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
170 | */
171 | @property (nonatomic, strong) NSURLCredential *credential;
172 |
173 | /**
174 | The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default.
175 |
176 | SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information.
177 | */
178 | @property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode;
179 |
180 | ///------------------------
181 | /// @name Accessing Streams
182 | ///------------------------
183 |
184 | /**
185 | The input stream used to read data to be sent during the request.
186 |
187 | This property acts as a proxy to the `HTTPBodyStream` property of `request`.
188 | */
189 | @property (nonatomic, strong) NSInputStream *inputStream;
190 |
191 | /**
192 | The output stream that is used to write data received until the request is finished.
193 |
194 | By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
195 | */
196 | @property (nonatomic, strong) NSOutputStream *outputStream;
197 |
198 | ///---------------------------------------------
199 | /// @name Managing Request Operation Information
200 | ///---------------------------------------------
201 |
202 | /**
203 | The user info dictionary for the receiver.
204 | */
205 | @property (nonatomic, strong) NSDictionary *userInfo;
206 |
207 | ///------------------------------------------------------
208 | /// @name Initializing an AFURLConnectionOperation Object
209 | ///------------------------------------------------------
210 |
211 | /**
212 | Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
213 |
214 | This is the designated initializer.
215 |
216 | @param urlRequest The request object to be used by the operation connection.
217 | */
218 | - (id)initWithRequest:(NSURLRequest *)urlRequest;
219 |
220 | ///----------------------------------
221 | /// @name Pausing / Resuming Requests
222 | ///----------------------------------
223 |
224 | /**
225 | Pauses the execution of the request operation.
226 |
227 | A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
228 | */
229 | - (void)pause;
230 |
231 | /**
232 | Whether the request operation is currently paused.
233 |
234 | @return `YES` if the operation is currently paused, otherwise `NO`.
235 | */
236 | - (BOOL)isPaused;
237 |
238 | /**
239 | Resumes the execution of the paused request operation.
240 |
241 | Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
242 | */
243 | - (void)resume;
244 |
245 | ///----------------------------------------------
246 | /// @name Configuring Backgrounding Task Behavior
247 | ///----------------------------------------------
248 |
249 | /**
250 | Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
251 |
252 | @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
253 | */
254 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
255 | - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
256 | #endif
257 |
258 | ///---------------------------------
259 | /// @name Setting Progress Callbacks
260 | ///---------------------------------
261 |
262 | /**
263 | Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
264 |
265 | @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
266 | */
267 | - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
268 |
269 | /**
270 | Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
271 |
272 | @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
273 | */
274 | - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
275 |
276 | ///-------------------------------------------------
277 | /// @name Setting NSURLConnection Delegate Callbacks
278 | ///-------------------------------------------------
279 |
280 | /**
281 | Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`.
282 |
283 | @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol).
284 |
285 | If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
286 | */
287 | - (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
288 |
289 | /**
290 | Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
291 |
292 | @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
293 | */
294 | - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
295 |
296 |
297 | /**
298 | Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
299 |
300 | @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
301 | */
302 | - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
303 |
304 | @end
305 |
306 | ///----------------
307 | /// @name Constants
308 | ///----------------
309 |
310 | /**
311 | ## SSL Pinning Options
312 |
313 | The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options.
314 |
315 | enum {
316 | AFSSLPinningModeNone,
317 | AFSSLPinningModePublicKey,
318 | AFSSLPinningModeCertificate,
319 | }
320 |
321 | `AFSSLPinningModeNone`
322 | Do not pin SSL connections
323 |
324 | `AFSSLPinningModePublicKey`
325 | Pin SSL connections to certificate public key (SPKI).
326 |
327 | `AFSSLPinningModeCertificate`
328 | Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance.
329 |
330 | ## User info dictionary keys
331 |
332 | These keys may exist in the user info dictionary, in addition to those defined for NSError.
333 |
334 | - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
335 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
336 |
337 | ### Constants
338 |
339 | `AFNetworkingOperationFailingURLRequestErrorKey`
340 | The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
341 |
342 | `AFNetworkingOperationFailingURLResponseErrorKey`
343 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
344 |
345 | ## Error Domains
346 |
347 | The following error domain is predefined.
348 |
349 | - `NSString * const AFNetworkingErrorDomain`
350 |
351 | ### Constants
352 |
353 | `AFNetworkingErrorDomain`
354 | AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
355 | */
356 | extern NSString * const AFNetworkingErrorDomain;
357 | extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey;
358 | extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey;
359 |
360 | ///--------------------
361 | /// @name Notifications
362 | ///--------------------
363 |
364 | /**
365 | Posted when an operation begins executing.
366 | */
367 | extern NSString * const AFNetworkingOperationDidStartNotification;
368 |
369 | /**
370 | Posted when an operation finishes.
371 | */
372 | extern NSString * const AFNetworkingOperationDidFinishNotification;
373 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFXMLRequestOperation.h:
--------------------------------------------------------------------------------
1 | // AFXMLRequestOperation.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFHTTPRequestOperation.h"
25 |
26 | #import
27 |
28 | /**
29 | `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
30 |
31 | ## Acceptable Content Types
32 |
33 | By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
34 |
35 | - `application/xml`
36 | - `text/xml`
37 |
38 | ## Use With AFHTTPClient
39 |
40 | When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
41 | */
42 | @interface AFXMLRequestOperation : AFHTTPRequestOperation
43 |
44 | ///----------------------------
45 | /// @name Getting Response Data
46 | ///----------------------------
47 |
48 | /**
49 | An `NSXMLParser` object constructed from the response data.
50 | */
51 | @property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser;
52 |
53 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
54 | /**
55 | An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
56 | */
57 | @property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument;
58 | #endif
59 |
60 | /**
61 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
62 |
63 | @param urlRequest The request object to be loaded asynchronously during execution of the operation
64 | @param success A block object to be executed when the operation 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 XML parser constructed with the response data of request.
65 | @param failure A block object to be executed when the operation finishes unsuccessfully. 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 describing the network error that occurred.
66 |
67 | @return A new XML request operation
68 | */
69 | + (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
70 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
71 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure;
72 |
73 |
74 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
75 | /**
76 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
77 |
78 | @param urlRequest The request object to be loaded asynchronously during execution of the operation
79 | @param success A block object to be executed when the operation 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 XML document created from the response data of request.
80 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. 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 describing the network or parsing error that occurred.
81 |
82 | @return A new XML request operation
83 | */
84 | + (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
85 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
86 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure;
87 | #endif
88 |
89 | @end
90 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/AFXMLRequestOperation.m:
--------------------------------------------------------------------------------
1 | // AFXMLRequestOperation.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFXMLRequestOperation.h"
24 |
25 | #include
26 |
27 | static dispatch_queue_t xml_request_operation_processing_queue() {
28 | static dispatch_queue_t af_xml_request_operation_processing_queue;
29 | static dispatch_once_t onceToken;
30 | dispatch_once(&onceToken, ^{
31 | af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT);
32 | });
33 |
34 | return af_xml_request_operation_processing_queue;
35 | }
36 |
37 | @interface AFXMLRequestOperation ()
38 | @property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser;
39 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
40 | @property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument;
41 | #endif
42 | @property (readwrite, nonatomic, strong) NSError *XMLError;
43 | @end
44 |
45 | @implementation AFXMLRequestOperation
46 | @synthesize responseXMLParser = _responseXMLParser;
47 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
48 | @synthesize responseXMLDocument = _responseXMLDocument;
49 | #endif
50 | @synthesize XMLError = _XMLError;
51 |
52 | + (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
53 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
54 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure
55 | {
56 | AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest];
57 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
58 | if (success) {
59 | success(operation.request, operation.response, responseObject);
60 | }
61 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
62 | if (failure) {
63 | failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
64 | }
65 | }];
66 |
67 | return requestOperation;
68 | }
69 |
70 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
71 | + (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
72 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
73 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure
74 | {
75 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
76 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
77 | if (success) {
78 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
79 | success(operation.request, operation.response, XMLDocument);
80 | }
81 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
82 | if (failure) {
83 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
84 | failure(operation.request, operation.response, error, XMLDocument);
85 | }
86 | }];
87 |
88 | return requestOperation;
89 | }
90 | #endif
91 |
92 |
93 | - (NSXMLParser *)responseXMLParser {
94 | if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
95 | self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
96 | }
97 |
98 | return _responseXMLParser;
99 | }
100 |
101 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
102 | - (NSXMLDocument *)responseXMLDocument {
103 | if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) {
104 | NSError *error = nil;
105 | self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
106 | self.XMLError = error;
107 | }
108 |
109 | return _responseXMLDocument;
110 | }
111 | #endif
112 |
113 | - (NSError *)error {
114 | if (_XMLError) {
115 | return _XMLError;
116 | } else {
117 | return [super error];
118 | }
119 | }
120 |
121 | #pragma mark - NSOperation
122 |
123 | - (void)cancel {
124 | [super cancel];
125 |
126 | self.responseXMLParser.delegate = nil;
127 | }
128 |
129 | #pragma mark - AFHTTPRequestOperation
130 |
131 | + (NSSet *)acceptableContentTypes {
132 | return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
133 | }
134 |
135 | + (BOOL)canProcessRequest:(NSURLRequest *)request {
136 | return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request];
137 | }
138 |
139 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
140 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
141 | {
142 | #pragma clang diagnostic push
143 | #pragma clang diagnostic ignored "-Warc-retain-cycles"
144 | #pragma clang diagnostic ignored "-Wgnu"
145 | self.completionBlock = ^ {
146 | dispatch_async(xml_request_operation_processing_queue(), ^(void) {
147 | NSXMLParser *XMLParser = self.responseXMLParser;
148 |
149 | if (self.error) {
150 | if (failure) {
151 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
152 | failure(self, self.error);
153 | });
154 | }
155 | } else {
156 | if (success) {
157 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
158 | success(self, XMLParser);
159 | });
160 | }
161 | }
162 | });
163 | };
164 | #pragma clang diagnostic pop
165 | }
166 |
167 | @end
168 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/UIImageView+AFNetworking.h:
--------------------------------------------------------------------------------
1 | // UIImageView+AFNetworking.h
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 "AFImageRequestOperation.h"
25 |
26 | #import
27 |
28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED
29 | #import
30 |
31 | /**
32 | 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.
33 | */
34 | @interface UIImageView (AFNetworking)
35 |
36 | /**
37 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. 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.
38 |
39 | By default, URL requests have 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:`
40 |
41 | @param url The URL used for the image request.
42 | */
43 | - (void)setImageWithURL:(NSURL *)url;
44 |
45 | /**
46 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. 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.
47 |
48 | By default, URL requests have 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:`
49 |
50 | @param url The URL used for the image request.
51 | @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.
52 | */
53 | - (void)setImageWithURL:(NSURL *)url
54 | placeholderImage:(UIImage *)placeholderImage;
55 |
56 | /**
57 | Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. 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.
58 |
59 | 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 executed.
60 |
61 | @param urlRequest The URL request used for the image request.
62 | @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.
63 | @param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). 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 request and response parameters will be `nil`.
64 | @param failure A block object to be executed when the image request operation 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.
65 | */
66 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
67 | placeholderImage:(UIImage *)placeholderImage
68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
70 |
71 | /**
72 | Cancels any executing image request operation for the receiver, if one exists.
73 | */
74 | - (void)cancelImageRequestOperation;
75 |
76 | @end
77 |
78 | #endif
79 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/AFNetworking/UIImageView+AFNetworking.m:
--------------------------------------------------------------------------------
1 | // UIImageView+AFNetworking.m
2 | //
3 | // Copyright (c) 2011 Gowalla (http://gowalla.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 |
26 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
27 | #import "UIImageView+AFNetworking.h"
28 |
29 | @interface AFImageCache : NSCache
30 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request;
31 | - (void)cacheImage:(UIImage *)image
32 | forRequest:(NSURLRequest *)request;
33 | @end
34 |
35 | #pragma mark -
36 |
37 | static char kAFImageRequestOperationObjectKey;
38 |
39 | @interface UIImageView (_AFNetworking)
40 | @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
41 | @end
42 |
43 | @implementation UIImageView (_AFNetworking)
44 | @dynamic af_imageRequestOperation;
45 | @end
46 |
47 | #pragma mark -
48 |
49 | @implementation UIImageView (AFNetworking)
50 |
51 | - (AFHTTPRequestOperation *)af_imageRequestOperation {
52 | return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
53 | }
54 |
55 | - (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
56 | objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
57 | }
58 |
59 | + (NSOperationQueue *)af_sharedImageRequestOperationQueue {
60 | static NSOperationQueue *_af_imageRequestOperationQueue = nil;
61 | static dispatch_once_t onceToken;
62 | dispatch_once(&onceToken, ^{
63 | _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init];
64 | [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
65 | });
66 |
67 | return _af_imageRequestOperationQueue;
68 | }
69 |
70 | + (AFImageCache *)af_sharedImageCache {
71 | static AFImageCache *_af_imageCache = nil;
72 | static dispatch_once_t oncePredicate;
73 | dispatch_once(&oncePredicate, ^{
74 | _af_imageCache = [[AFImageCache alloc] init];
75 | });
76 |
77 | return _af_imageCache;
78 | }
79 |
80 | #pragma mark -
81 |
82 | - (void)setImageWithURL:(NSURL *)url {
83 | [self setImageWithURL:url placeholderImage:nil];
84 | }
85 |
86 | - (void)setImageWithURL:(NSURL *)url
87 | placeholderImage:(UIImage *)placeholderImage
88 | {
89 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
90 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
91 |
92 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
93 | }
94 |
95 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
96 | placeholderImage:(UIImage *)placeholderImage
97 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
98 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
99 | {
100 | [self cancelImageRequestOperation];
101 |
102 | UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest];
103 | if (cachedImage) {
104 | self.af_imageRequestOperation = nil;
105 |
106 | if (success) {
107 | success(nil, nil, cachedImage);
108 | } else {
109 | self.image = cachedImage;
110 | }
111 | } else {
112 | if (placeholderImage) {
113 | self.image = placeholderImage;
114 | }
115 |
116 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
117 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
118 | if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
119 | if (self.af_imageRequestOperation == operation) {
120 | self.af_imageRequestOperation = nil;
121 | }
122 |
123 | if (success) {
124 | success(operation.request, operation.response, responseObject);
125 | } else if (responseObject) {
126 | self.image = responseObject;
127 | }
128 | }
129 |
130 | [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest];
131 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
132 | if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) {
133 | if (self.af_imageRequestOperation == operation) {
134 | self.af_imageRequestOperation = nil;
135 | }
136 |
137 | if (failure) {
138 | failure(operation.request, operation.response, error);
139 | }
140 | }
141 | }];
142 |
143 | self.af_imageRequestOperation = requestOperation;
144 |
145 | [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];
146 | }
147 | }
148 |
149 | - (void)cancelImageRequestOperation {
150 | [self.af_imageRequestOperation cancel];
151 | self.af_imageRequestOperation = nil;
152 | }
153 |
154 | @end
155 |
156 | #pragma mark -
157 |
158 | static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) {
159 | return [[request URL] absoluteString];
160 | }
161 |
162 | @implementation AFImageCache
163 |
164 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request {
165 | switch ([request cachePolicy]) {
166 | case NSURLRequestReloadIgnoringCacheData:
167 | case NSURLRequestReloadIgnoringLocalAndRemoteCacheData:
168 | return nil;
169 | default:
170 | break;
171 | }
172 |
173 | return [self objectForKey:AFImageCacheKeyFromURLRequest(request)];
174 | }
175 |
176 | - (void)cacheImage:(UIImage *)image
177 | forRequest:(NSURLRequest *)request
178 | {
179 | if (image && request) {
180 | [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)];
181 | }
182 | }
183 |
184 | @end
185 |
186 | #endif
187 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestParam.h:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTestParam.h
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface CYLHttpTestParam : NSObject
12 | @property (nonatomic, copy) NSString *hospitalName;
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestParam.m:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTestParam.m
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import "CYLHttpTestParam.h"
10 |
11 | @implementation CYLHttpTestParam
12 | @synthesize hospitalName;
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestResult.h:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTestResult.h
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface CYLHttpTestResult : NSObject
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestResult.m:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTestResult.m
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import "CYLHttpTestResult.h"
10 |
11 | @implementation CYLHttpTestResult
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestTool.h:
--------------------------------------------------------------------------------
1 |
2 |
3 | //CYLHttpTestTool.h
4 |
5 | #import "CYLHttpTestResult.h"
6 | #import "CYLHttpTestParam.h"
7 | //#import "CYLHttpTestInfo.h"
8 | #import "CYLHttpTool.h"
9 |
10 | typedef void(^CYLHttpTestSuccess)(CYLHttpTestResult*result);
11 |
12 | @interface CYLHttpTestTool : NSObject
13 |
14 | + (void)operateNetHttpTestWithParam:(CYLHttpTestParam*)param success:(CYLHttpTestSuccess)success failure:(CYLHttpFailure)failure;
15 |
16 | @end
17 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/CYLHttpTestTool.m:
--------------------------------------------------------------------------------
1 |
2 | #define SEVERURL @"http://123.57.73.61/mf/handler.aspx?api=Question.GetList"
3 |
4 | #import "CYLHttpTestTool.h"
5 | #import "MJExtension.h"
6 |
7 | @implementation CYLHttpTestTool
8 |
9 | + (void)operateNetHttpTestWithParam:(CYLHttpTestParam*)param success:(CYLHttpTestSuccess)success failure:(CYLHttpFailure)failure {
10 |
11 | // 1.封装请求参数
12 | NSDictionary *params = param.keyValues;
13 | NSLog(@"CYLHttpTestTool将模型转为字典\n%@",params);
14 | NSString *urlStr = SEVERURL;
15 | urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
16 | // 2.发送请求
17 | [CYLHttpTool postWithURL:urlStr dataFormat:@"JSON" params:params success:^(id jsonOrXml) {
18 | // NSLog("%@",jsonOrXml);
19 | [jsonOrXml writeToFile:@"/Users/chenyilong/Documents/咨询记录接口返回值.plist" atomically:YES];
20 | CYLHttpTestResult *result = [CYLHttpTestResult objectWithKeyValues:jsonOrXml];
21 | success(result);
22 | }failure:failure];
23 | }
24 | @end
25 | //使用方法如何封装AFNetworking XML解析之Model封装
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/Category/NSArray+log.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSArray+log.h
3 | // QueryExpress
4 | //
5 | // Created by CHENYI LONG on 14-8-10.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface NSArray (log)
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/Category/NSArray+log.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSArray+log.m
3 | // QueryExpress
4 | //
5 | // Created by CHENYI LONG on 14-8-10.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import "NSArray+log.h"
10 |
11 | @implementation NSArray (log)
12 | - (NSString *)descriptionWithLocale:(id)locale
13 | {
14 | NSMutableString *str = [NSMutableString stringWithFormat:@"%d (\n", (int)self.count];
15 |
16 | for (id obj in self) {
17 | [str appendFormat:@"\t%@,\n", obj];
18 | }
19 |
20 | [str appendString:@")"];
21 |
22 | return str;
23 | }
24 | @end
25 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/Category/NSDictionary+log.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSDictionary+log.h
3 | // QueryExpress
4 | //
5 | // Created by CHENYI LONG on 14-8-10.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface NSDictionary (log)
12 | @end
13 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/Category/NSDictionary+log.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSDictionary+log.m
3 | // QueryExpress
4 | //
5 | // Created by CHENYI LONG on 14-8-10.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import "NSDictionary+log.h"
10 |
11 | @implementation NSDictionary (log)
12 |
13 |
14 | - (NSString *)descriptionWithLocale:(id)locale
15 | {
16 | NSString *tempStr1 = [[self description] stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
17 | NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
18 | NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
19 | NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
20 | NSString *str = [NSPropertyListSerialization propertyListFromData:tempData mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:NULL];
21 | return str;
22 | }
23 |
24 |
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/CYLHttpTool.h:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTool.h
3 | //
4 | //
5 | // Created by apple on 14-1-14.
6 | // Copyright (c) 2014年 技术博客http://www.cnblogs.com/ChenYilong/. All rights reserved.
7 | // 封装任何的http请求
8 |
9 | #import
10 | /**
11 | * 请求成功后的回调
12 | *
13 | * @param json 服务器返回的JSON数据
14 | */
15 | typedef void (^CYLHttpSuccess)(id jsonOrXml);
16 | /**
17 | * 请求失败后的回调
18 | *
19 | * @param error 错误信息
20 | */
21 | typedef void (^CYLHttpFailure)(NSError *error);
22 |
23 |
24 | @interface CYLHttpTool : NSObject
25 |
26 | /**
27 | * 发送一POST请求
28 | * @param dataFormat 数据格式JSON或XML
29 | * @param url 请求路径
30 | * @param params 请求参数
31 | * @param success 请求成功后的回调
32 | * @param failure 请求失败后的回调
33 | */
34 | + (void)postWithURL:(NSString *)url dataFormat:(NSString *)dataFormat params:(NSDictionary *)params success:(CYLHttpSuccess)success failure:(CYLHttpFailure)failure;
35 | /**
36 | * 发送一GET请求
37 | * @param dataFormat 数据格式JSON或XML
38 | * @param url 请求路径
39 | * @param params 请求参数
40 | * @param success 请求成功后的回调
41 | * @param failure 请求失败后的回调
42 | */
43 | + (void)getWithURL:(NSString *)url dataFormat:(NSString *)dataFormat params:(NSDictionary *)params success:(CYLHttpSuccess)success failure:(CYLHttpFailure)failure;
44 | @end
45 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/CYLHttpTool.m:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTool.h
3 | //
4 | //
5 | // Created by apple on 14-1-14.
6 | // Copyright (c) 2014年 技术博客http://www.cnblogs.com/ChenYilong/. All rights reserved.
7 | // 封装任何的http请求
8 |
9 | #import "CYLHttpTool.h"
10 | #import "AFNetworking.h"
11 | #import "MJExtension.h"
12 | #import "XMLReader.h"
13 | #import "XMLWriter.h"
14 | #import "NSDictionary+SwitchKeyLowercase.h"
15 |
16 | @implementation CYLHttpTool
17 |
18 | + (void)postWithURL:(NSString *)url dataFormat:(NSString *)dataFormat params:(NSDictionary *)params success:(CYLHttpSuccess)success failure:(CYLHttpFailure)failure
19 | {
20 | [self requestWithMethod:@"POST" url:url dataFormat:dataFormat params:params success:success failure:failure];
21 | }
22 |
23 | + (void)getWithURL:(NSString *)url dataFormat:(NSString *)dataFormat params:(NSDictionary *)params success:(CYLHttpSuccess)success failure:(CYLHttpFailure)failure
24 | {
25 | [self requestWithMethod:@"GET" url:url dataFormat:dataFormat params:params success:success failure:failure];
26 | }
27 |
28 | + (void)requestWithMethod:(NSString *)method url:(NSString *)url dataFormat:(NSString *)dataFormat params:(NSDictionary *)params success:(CYLHttpSuccess)success failure:(CYLHttpFailure)failure
29 | {
30 | if ([dataFormat isEqualToString:@"XML"]) {
31 | NSString *xmlStr = [XMLWriter XMLStringFromDictionary:params withHeader:NO];
32 | NSURL *urls = [NSURL URLWithString:url];
33 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urls];
34 | [request setTimeoutInterval:20.f];
35 | [request setHTTPMethod:method];
36 | NSString *msgLength = [NSString stringWithFormat:@"%d", [xmlStr length]];
37 | [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
38 | [request setValue:msgLength forHTTPHeaderField:@"Content-Length"];
39 | [request setHTTPBody: [xmlStr dataUsingEncoding:NSUTF8StringEncoding]];
40 | AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc]initWithRequest:request];
41 | NSLog(@"CYLHttpTool类向服务器POST的字符串\n%@", xmlStr);
42 |
43 | // 3.创建操作对象
44 | [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
45 | NSError *error = nil;
46 | id xml = [XMLReader dictionaryForXMLData:(NSData *)responseObject
47 | options:XMLReaderOptionsProcessNamespaces
48 | error:&error];
49 | // 将XML的key统一转为小写
50 | NSDictionary *xmlKeyLowercase = [xml switchKeyLowercase];
51 | success(xmlKeyLowercase);
52 | NSLog(@"CYLHttpTool类_(requestWithMethod:url:params:success:failure:方法)\n成功后\n打印返回值\n%@", xmlKeyLowercase);
53 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
54 | // 请求失败的时候会调用这里的代码
55 | // 通知外面的block,请求成功了
56 | if (failure) {
57 | failure(error);
58 | }
59 | }];
60 | // 4.执行操作(真正发送请求)
61 | [operation start];
62 | }
63 | else if ([dataFormat isEqualToString:@"JSON"]) {
64 | // 1.创建client对象,设置url路径
65 | AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:url]];
66 | // 2.创建请求对象
67 | NSMutableURLRequest *request = [client requestWithMethod:method path:nil parameters:params];
68 | [request addValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
69 | [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
70 | [request addValue:@"text/javascript" forHTTPHeaderField:@"Content-Type"];
71 | [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
72 | NSLog(@"CYLHttpTool类_(requestWithMethod:url:params:success:failure:方法)打印参数%@",params);
73 | // 3.创建操作对象
74 | AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
75 | // 请求成功的时候会调用这里的代码
76 | // 通知外面的block,请求成功了
77 | if (success) {
78 | id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
79 | success(json);
80 | NSLog(@"✅✅✅✅✅✅✅CYLHttpTool类_(requestWithMethod:url:params:success:failure:方法)打印返回值\n%@", json);
81 | }
82 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
83 | // 请求失败的时候会调用这里的代码
84 |
85 | // 通知外面的block,请求成功了
86 | if (failure) {
87 | failure(error);
88 | }
89 | }];
90 | // 4.执行操作(真正发送请求)
91 | [operation start];
92 | }
93 | }
94 |
95 | @end
96 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/NSDictionary+SwitchKeyLowercase.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSDictionary+SwitchKeyLowercase.h
3 | // CYLKDTXMLDemo
4 | //
5 | // Created by CHENYI LONG on 14-10-22.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface NSDictionary (SwitchKeyLowercase)
12 | - (NSMutableDictionary *)switchKeyLowercase;
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/NSDictionary+SwitchKeyLowercase.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSDictionary+SwitchKeyLowercase.m
3 | // CYLKDTXMLDemo
4 | //
5 | // Created by CHENYI LONG on 14-10-22.
6 | // Copyright (c) 2014年 CHENYI LONG. All rights reserved.
7 | //
8 |
9 | #import "NSDictionary+SwitchKeyLowercase.h"
10 |
11 | @implementation NSDictionary (SwitchKeyLowercase)
12 | - (NSMutableDictionary *)switchKeyLowercase {
13 | NSMutableDictionary *returnDict = [[NSMutableDictionary alloc]
14 | initWithCapacity:[self count]];
15 | NSArray *keys = [self allKeys];
16 | for (id key in keys) {
17 |
18 | id oneValue = [self valueForKey:key];
19 | id oneCopy = nil;
20 | // value是字典
21 | if ([oneValue respondsToSelector:@selector(switchKeyLowercase)])
22 | {
23 | oneCopy = [oneValue switchKeyLowercase];
24 | }
25 | // value不是字典
26 | else if ([oneValue respondsToSelector:@selector(mutableCopy)])
27 | {
28 | if ([oneValue isKindOfClass:[NSArray class]]) {
29 | NSArray *oneValueArr = oneValue;
30 | NSMutableArray *oneVallueMutableArr = [NSMutableArray arrayWithCapacity:[oneValueArr count]];
31 | for (NSDictionary *obj in oneValueArr) {
32 | // 肯定是字典
33 | [oneVallueMutableArr addObject:[obj switchKeyLowercase]];
34 | }
35 | oneCopy = oneVallueMutableArr;
36 | }
37 | //如果不是数组
38 | else
39 | {oneCopy = [oneValue mutableCopy];}
40 | }
41 | // value是nil
42 | if (oneCopy == nil)
43 | {
44 | oneCopy = [oneValue copy];
45 | }
46 |
47 | [returnDict setValue:oneCopy forKey:[key lowercaseString]];
48 | }
49 | return returnDict;
50 | }
51 |
52 | @end
53 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/XMLReader/README.md:
--------------------------------------------------------------------------------
1 | # XMLReader
2 |
3 | This project comes from a component developed by Troy Brant and published on his website : http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
4 |
5 | I'm open sourcing some of the updates I've made on it.
6 |
7 |
8 | ## Usage
9 |
10 | NSData *data = ...; // some data that can be received from remote service
11 | NSError *error = nil;
12 | NSDictionary *dict = [XMLReader dictionaryForXMLData:data
13 | options:XMLReaderOptionsProcessNamespaces
14 | error:&error];
15 |
16 |
17 | ## Requirements
18 |
19 | Xcode 4.4 and above because project use the "auto-synthesized property" feature.
20 |
21 |
22 | ## FAQ
23 |
24 | #### Sometimes I get an `NSDictionary` while I must get an `NSArray`, why ?
25 |
26 | In the algorithm of the `XMLReader`, when the parser found a new tag it automatically creates an `NSDictionary`, if it found another occurrence of the same tag at the same level in the XML tree it creates another dictionary and put both dictionaries inside an `NSArray`.
27 |
28 | The consequence is: if you have a list that contains only one item, you will get an `NSDictionary` as result and not an `NSArray`.
29 | The only workaround is to check the class of the object contained for in the dictionary using `isKindOfClass:`. See sample code below :
30 |
31 | NSData *data = ...;
32 | NSError *error = nil;
33 | NSDictionary *dict = [XMLReader dictionaryForXMLData:data error:&error];
34 |
35 | NSArray *list = [dict objectForKey:@"list"];
36 | if (![list isKindOfClass:[NSArray class]])
37 | {
38 | // if 'list' isn't an array, we create a new array containing our object
39 | list = [NSArray arrayWithObject:list];
40 | }
41 |
42 | // we can loop through items safely now
43 | for (NSDictionary *item in list)
44 | {
45 | // ...
46 | }
47 |
48 |
49 | #### I don't have enable ARC on my project, how can I use your library ?
50 |
51 | You have 2 options:
52 |
53 | * Use the branch "[no-objc-arc](https://github.com/amarcadet/XMLReader/tree/no-objc-arc)" that use manual reference counting.
54 | * **Better choice:** add the "-fobjc-arc" compiler flag on `XMLReader.m` file in your build phases.
55 |
56 | #### I have trust issues, I don't want ARC, I prefer MRC, what can I do ?
57 |
58 | Well, nobody is perfect but, still, you can use the branch "[no-objc-arc](https://github.com/amarcadet/XMLReader/tree/no-objc-arc)".
59 |
60 |
61 | ## Contributions
62 |
63 | Thanks to the original author of this component Troy Brant and to [Divan "snip3r8" Visagie](https://github.com/snip3r8) for providing ARC support.
64 |
65 |
66 | ## License
67 |
68 | Copyright (C) 2012 Antoine Marcadet
69 |
70 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
71 |
72 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
73 |
74 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
75 |
76 | [](https://bitdeli.com/free "Bitdeli Badge")
77 |
78 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/XMLReader/XMLReader.h:
--------------------------------------------------------------------------------
1 | //
2 | // XMLReader.h
3 | //
4 | // Created by Troy Brant on 9/18/10.
5 | // Updated by Antoine Marcadet on 9/23/11.
6 | // Updated by Divan Visagie on 2012-08-26
7 | //
8 |
9 | #import
10 |
11 | enum {
12 | XMLReaderOptionsProcessNamespaces = 1 << 0, // Specifies whether the receiver reports the namespace and the qualified name of an element.
13 | XMLReaderOptionsReportNamespacePrefixes = 1 << 1, // Specifies whether the receiver reports the scope of namespace declarations.
14 | XMLReaderOptionsResolveExternalEntities = 1 << 2, // Specifies whether the receiver reports declarations of external entities.
15 | };
16 | typedef NSUInteger XMLReaderOptions;
17 |
18 | @interface XMLReader : NSObject
19 |
20 | + (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
21 | + (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;
22 | + (NSDictionary *)dictionaryForXMLData:(NSData *)data options:(XMLReaderOptions)options error:(NSError **)errorPointer;
23 | + (NSDictionary *)dictionaryForXMLString:(NSString *)string options:(XMLReaderOptions)options error:(NSError **)errorPointer;
24 |
25 | @end
26 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/XMLReader/XMLReader.m:
--------------------------------------------------------------------------------
1 | //
2 | // XMLReader.m
3 | //
4 | // Created by Troy Brant on 9/18/10.
5 | // Updated by Antoine Marcadet on 9/23/11.
6 | // Updated by Divan Visagie on 2012-08-26
7 | //
8 |
9 | #import "XMLReader.h"
10 |
11 | #if !defined(__has_feature) || !__has_feature(objc_arc)
12 | //#error "XMLReader requires ARC support."
13 | #endif
14 |
15 | NSString *const kXMLReaderTextNodeKey = @"text";
16 | NSString *const kXMLReaderAttributePrefix = @"@";
17 |
18 | @interface XMLReader ()
19 |
20 | @property (nonatomic, strong) NSMutableArray *dictionaryStack;
21 | @property (nonatomic, strong) NSMutableString *textInProgress;
22 | @property (nonatomic, strong) NSError *errorPointer;
23 |
24 | @end
25 |
26 |
27 | @implementation XMLReader
28 |
29 | #pragma mark - Public methods
30 |
31 | + (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
32 | {
33 | XMLReader *reader = [[XMLReader alloc] initWithError:error];
34 | NSDictionary *rootDictionary = [reader objectWithData:data options:0];
35 | return rootDictionary;
36 | }
37 |
38 | + (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
39 | {
40 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
41 | return [XMLReader dictionaryForXMLData:data error:error];
42 | }
43 |
44 | + (NSDictionary *)dictionaryForXMLData:(NSData *)data options:(XMLReaderOptions)options error:(NSError **)error
45 | {
46 | XMLReader *reader = [[XMLReader alloc] initWithError:error];
47 | NSDictionary *rootDictionary = [reader objectWithData:data options:options];
48 | return rootDictionary;
49 | }
50 |
51 | + (NSDictionary *)dictionaryForXMLString:(NSString *)string options:(XMLReaderOptions)options error:(NSError **)error
52 | {
53 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
54 | return [XMLReader dictionaryForXMLData:data options:options error:error];
55 | }
56 |
57 |
58 | #pragma mark - Parsing
59 |
60 | - (id)initWithError:(NSError **)error
61 | {
62 | self = [super init];
63 | if (self)
64 | {
65 | self.errorPointer = *error;
66 | }
67 | return self;
68 | }
69 |
70 | - (NSDictionary *)objectWithData:(NSData *)data options:(XMLReaderOptions)options
71 | {
72 | // Clear out any old data
73 | self.dictionaryStack = [[NSMutableArray alloc] init];
74 | self.textInProgress = [[NSMutableString alloc] init];
75 |
76 | // Initialize the stack with a fresh dictionary
77 | [self.dictionaryStack addObject:[NSMutableDictionary dictionary]];
78 |
79 | // Parse the XML
80 | NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
81 |
82 | [parser setShouldProcessNamespaces:(options & XMLReaderOptionsProcessNamespaces)];
83 | [parser setShouldReportNamespacePrefixes:(options & XMLReaderOptionsReportNamespacePrefixes)];
84 | [parser setShouldResolveExternalEntities:(options & XMLReaderOptionsResolveExternalEntities)];
85 |
86 | parser.delegate = self;
87 | BOOL success = [parser parse];
88 |
89 | // Return the stack's root dictionary on success
90 | if (success)
91 | {
92 | NSDictionary *resultDict = [self.dictionaryStack objectAtIndex:0];
93 | return resultDict;
94 | }
95 |
96 | return nil;
97 | }
98 |
99 |
100 | #pragma mark - NSXMLParserDelegate methods
101 |
102 | - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
103 | {
104 | // Get the dictionary for the current level in the stack
105 | NSMutableDictionary *parentDict = [self.dictionaryStack lastObject];
106 |
107 | // Create the child dictionary for the new element, and initilaize it with the attributes
108 | NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
109 | [childDict addEntriesFromDictionary:attributeDict];
110 |
111 | // If there's already an item for this key, it means we need to create an array
112 | id existingValue = [parentDict objectForKey:elementName];
113 | if (existingValue)
114 | {
115 | NSMutableArray *array = nil;
116 | if ([existingValue isKindOfClass:[NSMutableArray class]])
117 | {
118 | // The array exists, so use it
119 | array = (NSMutableArray *) existingValue;
120 | }
121 | else
122 | {
123 | // Create an array if it doesn't exist
124 | array = [NSMutableArray array];
125 | [array addObject:existingValue];
126 |
127 | // Replace the child dictionary with an array of children dictionaries
128 | [parentDict setObject:array forKey:elementName];
129 | }
130 |
131 | // Add the new child dictionary to the array
132 | [array addObject:childDict];
133 | }
134 | else
135 | {
136 | // No existing value, so update the dictionary
137 | [parentDict setObject:childDict forKey:elementName];
138 | }
139 |
140 | // Update the stack
141 | [self.dictionaryStack addObject:childDict];
142 | }
143 |
144 | - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
145 | {
146 | // Update the parent dict with text info
147 | NSMutableDictionary *dictInProgress = [self.dictionaryStack lastObject];
148 |
149 | // Set the text property
150 | if ([self.textInProgress length] > 0)
151 | {
152 | // trim after concatenating
153 | NSString *trimmedString = [self.textInProgress stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
154 | [dictInProgress setObject:[trimmedString mutableCopy] forKey:kXMLReaderTextNodeKey];
155 |
156 | // Reset the text
157 | self.textInProgress = [[NSMutableString alloc] init];
158 | }
159 |
160 | // Pop the current dict
161 | [self.dictionaryStack removeLastObject];
162 | }
163 |
164 | - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
165 | {
166 | // Build the text value
167 | [self.textInProgress appendString:string];
168 | }
169 |
170 | - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
171 | {
172 | // Set the error pointer to the parser's error object
173 | self.errorPointer = parseError;
174 | }
175 |
176 | @end
177 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/xmlwriter/XMLWriter.h:
--------------------------------------------------------------------------------
1 | //
2 | // XMLWriter.h
3 | //
4 |
5 | #import
6 |
7 | @interface XMLWriter : NSObject{
8 | @private
9 | NSMutableArray* nodes;
10 | NSString* xml;
11 | NSMutableArray* treeNodes;
12 | BOOL isRoot;
13 | NSString* passDict;
14 | BOOL withHeader;
15 | }
16 | +(NSString *)XMLStringFromDictionary:(NSDictionary *)dictionary;
17 | +(NSString *)XMLStringFromDictionary:(NSDictionary *)dictionary withHeader:(BOOL)header;
18 | +(BOOL)XMLDataFromDictionary:(NSDictionary *)dictionary toStringPath:(NSString *) path Error:(NSError **)error;
19 |
20 | @end
21 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/CYLHttpTool/RequestTool/xmlwriter/XMLWriter.m:
--------------------------------------------------------------------------------
1 | //
2 | // XMLWriter.m
3 | //
4 | #import "XMLWriter.h"
5 | #define PREFIX_STRING_FOR_ELEMENT @"@" //From XMLReader
6 | @implementation XMLWriter
7 |
8 | -(void)serialize:(id)root
9 | {
10 | if([root isKindOfClass:[NSArray class]])
11 | {
12 | int mula = (int)[root count];
13 | mula--;
14 | [nodes addObject:[NSString stringWithFormat:@"%i",(int)mula]];
15 |
16 | for(id objects in root)
17 | {
18 | if ([[nodes lastObject] isEqualToString:@"0"] || [nodes lastObject] == NULL || ![nodes count])
19 | {
20 | [nodes removeLastObject];
21 | [self serialize:objects];
22 | }
23 | else
24 | {
25 | [self serialize:objects];
26 | if(!isRoot)
27 | xml = [xml stringByAppendingFormat:@"%@><%@>",[treeNodes lastObject],[treeNodes lastObject]];
28 | else
29 | isRoot = FALSE;
30 | int value = [[nodes lastObject] intValue];
31 | [nodes removeLastObject];
32 | value--;
33 | [nodes addObject:[NSString stringWithFormat:@"%i",(int)value]];
34 | }
35 | }
36 | }
37 | else if ([root isKindOfClass:[NSDictionary class]])
38 | {
39 | for (NSString* key in root)
40 | {
41 | if(!isRoot)
42 | {
43 | // NSLog(@"We came in");
44 | [treeNodes addObject:key];
45 | xml = [xml stringByAppendingFormat:@"<%@>",key];
46 | [self serialize:[root objectForKey:key]];
47 | xml =[xml stringByAppendingFormat:@"%@>",key];
48 | [treeNodes removeLastObject];
49 | } else {
50 | isRoot = FALSE;
51 | [self serialize:[root objectForKey:key]];
52 | }
53 | }
54 | }
55 | else if ([root isKindOfClass:[NSString class]] || [root isKindOfClass:[NSNumber class]] || [root isKindOfClass:[NSURL class]])
56 | {
57 | // if ([root hasPrefix:"PREFIX_STRING_FOR_ELEMENT"])
58 | // is element
59 | // else
60 | xml = [xml stringByAppendingFormat:@"%@",root];
61 | }
62 | }
63 |
64 | - (id)initWithDictionary:(NSDictionary *)dictionary
65 | {
66 | self = [super init];
67 | if (self) {
68 | // Initialization code here.
69 | xml = @"";
70 | if (withHeader)
71 | xml = @"";
72 | nodes = [[NSMutableArray alloc] init];
73 | treeNodes = [[NSMutableArray alloc] init];
74 | isRoot = YES;
75 | passDict = [[dictionary allKeys] lastObject];
76 | xml = [xml stringByAppendingFormat:@"<%@>\n",passDict];
77 | [self serialize:dictionary];
78 | }
79 |
80 | return self;
81 | }
82 | - (id)initWithDictionary:(NSDictionary *)dictionary withHeader:(BOOL)header {
83 | withHeader = header;
84 | self = [self initWithDictionary:dictionary];
85 | return self;
86 | }
87 |
88 | -(void)dealloc
89 | {
90 | // [xml release],nodes =nil;
91 | [nodes release], nodes = nil ;
92 | [treeNodes release], treeNodes = nil;
93 | [super dealloc];
94 | }
95 |
96 | -(NSString *)getXML
97 | {
98 | xml = [xml stringByReplacingOccurrencesOfString:@"(null)><(null)>" withString:@"\n"];
99 | xml = [xml stringByAppendingFormat:@"\n%@>",passDict];
100 | return xml;
101 | }
102 |
103 | +(NSString *)XMLStringFromDictionary:(NSDictionary *)dictionary
104 | {
105 | if (![[dictionary allKeys] count])
106 | return NULL;
107 | XMLWriter* fromDictionary = [[[XMLWriter alloc]initWithDictionary:dictionary]autorelease];
108 | return [fromDictionary getXML];
109 | }
110 |
111 | + (NSString *) XMLStringFromDictionary:(NSDictionary *)dictionary withHeader:(BOOL)header {
112 | if (![[dictionary allKeys] count])
113 | return NULL;
114 | XMLWriter* fromDictionary = [[[XMLWriter alloc]initWithDictionary:dictionary withHeader:header]autorelease];
115 | return [fromDictionary getXML];
116 | }
117 |
118 | +(BOOL)XMLDataFromDictionary:(NSDictionary *)dictionary toStringPath:(NSString *) path Error:(NSError **)error
119 | {
120 |
121 | XMLWriter* fromDictionary = [[[XMLWriter alloc]initWithDictionary:dictionary]autorelease];
122 | [[fromDictionary getXML] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:error];
123 | if (error)
124 | return FALSE;
125 | else
126 | return TRUE;
127 |
128 | }
129 | @end
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJConst.h:
--------------------------------------------------------------------------------
1 |
2 | #ifndef __MJConst__H__
3 | #define __MJConst__H__
4 |
5 | #import
6 |
7 | // 过期
8 | #define MJDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead)
9 |
10 | #ifdef DEBUG // 调试状态
11 | // 打开LOG功能
12 | #define MJLog(...) NSLog(__VA_ARGS__)
13 | #else // 发布状态
14 | // 关闭LOG功能
15 | #define MJLog(...)
16 | #endif
17 |
18 | // 构建错误
19 | #define MJBuildError(error, msg) \
20 | if (error) *error = [NSError errorWithDomain:msg code:250 userInfo:nil];
21 |
22 | /**
23 | * 断言
24 | * @param condition 条件
25 | * @param returnValue 返回值
26 | */
27 | #define MJAssertError(condition, returnValue, error, msg) \
28 | if ((condition) == NO) { \
29 | MJBuildError(error, msg); \
30 | return returnValue;\
31 | }
32 |
33 | #define MJAssert2(condition, returnValue) \
34 | if ((condition) == NO) return returnValue;
35 |
36 | /**
37 | * 断言
38 | * @param condition 条件
39 | */
40 | #define MJAssert(condition) MJAssert2(condition, )
41 |
42 | /**
43 | * 断言
44 | * @param param 参数
45 | * @param returnValue 返回值
46 | */
47 | #define MJAssertParamNotNil2(param, returnValue) \
48 | MJAssert2((param) != nil, returnValue)
49 |
50 | /**
51 | * 断言
52 | * @param param 参数
53 | */
54 | #define MJAssertParamNotNil(param) MJAssertParamNotNil2(param, )
55 |
56 | /**
57 | * 打印所有的属性
58 | */
59 | #define MJLogAllIvars \
60 | -(NSString *)description \
61 | { \
62 | return [self keyValues].description; \
63 | }
64 |
65 | /**
66 | * 类型(属性类型)
67 | */
68 | extern NSString *const MJTypeInt;
69 | extern NSString *const MJTypeFloat;
70 | extern NSString *const MJTypeDouble;
71 | extern NSString *const MJTypeLong;
72 | extern NSString *const MJTypeLongLong;
73 | extern NSString *const MJTypeChar;
74 | extern NSString *const MJTypeBOOL;
75 | extern NSString *const MJTypePointer;
76 |
77 | extern NSString *const MJTypeIvar;
78 | extern NSString *const MJTypeMethod;
79 | extern NSString *const MJTypeBlock;
80 | extern NSString *const MJTypeClass;
81 | extern NSString *const MJTypeSEL;
82 | extern NSString *const MJTypeId;
83 |
84 | #endif
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJConst.m:
--------------------------------------------------------------------------------
1 | #ifndef __MJConst__M__
2 | #define __MJConst__M__
3 |
4 | #import
5 |
6 | /**
7 | * 成员变量类型(属性类型)
8 | */
9 | NSString *const MJTypeInt = @"i";
10 | NSString *const MJTypeFloat = @"f";
11 | NSString *const MJTypeDouble = @"d";
12 | NSString *const MJTypeLong = @"q";
13 | NSString *const MJTypeLongLong = @"q";
14 | NSString *const MJTypeChar = @"c";
15 | NSString *const MJTypeBOOL = @"c";
16 | NSString *const MJTypePointer = @"*";
17 |
18 | NSString *const MJTypeIvar = @"^{objc_ivar=}";
19 | NSString *const MJTypeMethod = @"^{objc_method=}";
20 | NSString *const MJTypeBlock = @"@?";
21 | NSString *const MJTypeClass = @"#";
22 | NSString *const MJTypeSEL = @":";
23 | NSString *const MJTypeId = @"@";
24 |
25 | #endif
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJExtension.h:
--------------------------------------------------------------------------------
1 | //
2 | // MJExtension.h
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | // 代码地址:https://github.com/CoderMJLee/MJExtension
8 | // 代码地址:http://code4app.com/ios/%E5%AD%97%E5%85%B8-JSON-%E4%B8%8E%E6%A8%A1%E5%9E%8B%E7%9A%84%E8%BD%AC%E6%8D%A2/5339992a933bf062608b4c57
9 |
10 | #import "NSObject+MJCoding.h"
11 | #import "NSObject+MJIvar.h"
12 | #import "NSObject+MJKeyValue.h"
13 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJFoundation.h:
--------------------------------------------------------------------------------
1 | //
2 | // MJFoundation.h
3 | // MJExtensionExample
4 | //
5 | // Created by MJ Lee on 14/7/16.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface MJFoundation : NSObject
12 | + (BOOL)isClassFromFoundation:(Class)c;
13 | @end
14 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJFoundation.m:
--------------------------------------------------------------------------------
1 | //
2 | // MJFoundation.m
3 | // MJExtensionExample
4 | //
5 | // Created by MJ Lee on 14/7/16.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import "MJFoundation.h"
10 | #import "MJConst.h"
11 |
12 | static NSSet *_foundationClasses;
13 |
14 | @implementation MJFoundation
15 |
16 | + (void)load
17 | {
18 | _foundationClasses = [NSSet setWithObjects:
19 | [NSObject class],
20 | [NSURL class],
21 | [NSDate class],
22 | [NSNumber class],
23 | [NSDecimalNumber class],
24 | [NSData class],
25 | [NSMutableData class],
26 | [NSArray class],
27 | [NSMutableArray class],
28 | [NSDictionary class],
29 | [NSMutableDictionary class],
30 | [NSString class],
31 | [NSMutableString class], nil];
32 | }
33 |
34 | + (BOOL)isClassFromFoundation:(Class)c
35 | {
36 | return [_foundationClasses containsObject:c];
37 | }
38 | @end
39 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJIvar.h:
--------------------------------------------------------------------------------
1 | //
2 | // MJIvar.h
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | // 包装一个成员变量
8 |
9 | #import
10 | #import
11 | @class MJType;
12 |
13 | /**
14 | * 包装一个成员变量
15 | */
16 | @interface MJIvar : NSObject
17 | /** 成员变量 */
18 | @property (nonatomic, assign) Ivar ivar;
19 | /** 成员名 */
20 | @property (nonatomic, copy) NSString *name;
21 | /** 成员属性名 */
22 | @property (nonatomic, readonly) NSString *propertyName;
23 | /** 成员变量的类型 */
24 | @property (nonatomic, readonly) MJType *type;
25 | /** 成员来源于哪个类(可能是父类) */
26 | @property (nonatomic, assign) Class srcClass;
27 |
28 | /**** 同一个成员变量 - 父类和子类的行为可能不一致(key、keys、objectClassInArray) ****/
29 | /** 对应着字典中的key */
30 | - (void)setKey:(NSString *)key forClass:(Class)c;
31 | - (NSString *)keyFromClass:(Class)c;
32 |
33 | /** 对应着字典中的多级key */
34 | - (NSArray *)keysFromClass:(Class)c;
35 |
36 | /** 模型数组中的模型类型 */
37 | - (void)setObjectClassInArray:(Class)objectClass forClass:(Class)c;
38 | - (Class)objectClassInArrayFromClass:(Class)c;
39 | /**** 同一个成员变量 - 父类和子类的行为可能不一致(key、keys、objectClassInArray) ****/
40 |
41 | /**
42 | * 设置成员变量的值
43 | */
44 | - (void)setValue:(id)value forObject:(id)object;
45 | /**
46 | * 得到成员变量的值
47 | */
48 | - (id)valueFromObject:(id)object;
49 |
50 | /**
51 | * 初始化
52 | *
53 | * @param ivar 成员变量
54 | *
55 | * @return 初始化好的对象
56 | */
57 | + (instancetype)cachedIvarWithIvar:(Ivar)ivar;
58 | @end
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJIvar.m:
--------------------------------------------------------------------------------
1 | //
2 | // MJIvar.m
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import "MJIvar.h"
10 | #import "MJType.h"
11 | #import "MJFoundation.h"
12 | #import "MJConst.h"
13 |
14 | @interface MJIvar()
15 | @property (strong, nonatomic) NSMutableDictionary *keyDict;
16 | @property (strong, nonatomic) NSMutableDictionary *keysDict;
17 | @property (strong, nonatomic) NSMutableDictionary *objectClassInArrayDict;
18 | @end
19 |
20 | @implementation MJIvar
21 |
22 | - (NSMutableDictionary *)keyDict
23 | {
24 | if (!_keyDict) {
25 | self.keyDict = [NSMutableDictionary dictionary];
26 | }
27 | return _keyDict;
28 | }
29 |
30 | - (NSMutableDictionary *)keysDict
31 | {
32 | if (!_keysDict) {
33 | self.keysDict = [NSMutableDictionary dictionary];
34 | }
35 | return _keysDict;
36 | }
37 |
38 | - (NSMutableDictionary *)objectClassInArrayDict
39 | {
40 | if (!_objectClassInArrayDict) {
41 | self.objectClassInArrayDict = [NSMutableDictionary dictionary];
42 | }
43 | return _objectClassInArrayDict;
44 | }
45 |
46 | + (instancetype)cachedIvarWithIvar:(Ivar)ivar
47 | {
48 | MJIvar *ivarObject = objc_getAssociatedObject(self, ivar);
49 | if (ivarObject == nil) {
50 | ivarObject = [[self alloc] init];
51 | ivarObject.ivar = ivar;
52 | objc_setAssociatedObject(self, ivar, ivarObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
53 | }
54 | return ivarObject;
55 | }
56 |
57 | /**
58 | * 设置成员变量
59 | */
60 | - (void)setIvar:(Ivar)ivar
61 | {
62 | _ivar = ivar;
63 |
64 | MJAssertParamNotNil(ivar);
65 |
66 | // 1.成员变量名
67 | _name = @(ivar_getName(ivar));
68 |
69 | // 2.属性名
70 | if ([_name hasPrefix:@"_"]) {
71 | _propertyName = [_name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""];
72 | } else {
73 | _propertyName = _name;
74 | }
75 |
76 | // 3.成员变量的类型符
77 | NSString *code = @(ivar_getTypeEncoding(ivar));
78 | _type = [MJType cachedTypeWithCode:code];
79 | }
80 |
81 | /**
82 | * 获得成员变量的值
83 | */
84 | - (id)valueFromObject:(id)object
85 | {
86 | if (_type.KVCDisabled) return [NSNull null];
87 | return [object valueForKey:_propertyName];
88 | }
89 |
90 | /**
91 | * 设置成员变量的值
92 | */
93 | - (void)setValue:(id)value forObject:(id)object
94 | {
95 | if (_type.KVCDisabled || value == nil) return;
96 | [object setValue:value forKey:_propertyName];
97 | }
98 |
99 | /** 对应着字典中的key */
100 | - (void)setKey:(NSString *)key forClass:(Class)c
101 | {
102 | if (!key) return;
103 | self.keyDict[NSStringFromClass(c)] = key;
104 | // 如果有多级映射
105 | [self setKeys:[key componentsSeparatedByString:@"."] forClass:c];
106 | }
107 | - (NSString *)keyFromClass:(Class)c
108 | {
109 | return self.keyDict[NSStringFromClass(c)];
110 | }
111 |
112 | /** 对应着字典中的多级key */
113 | - (void)setKeys:(NSArray *)keys forClass:(Class)c
114 | {
115 | if (!keys) return;
116 | self.keysDict[NSStringFromClass(c)] = keys;
117 | }
118 | - (NSArray *)keysFromClass:(Class)c
119 | {
120 | return self.keysDict[NSStringFromClass(c)];
121 | }
122 |
123 | /** 模型数组中的模型类型 */
124 | - (void)setObjectClassInArray:(Class)objectClass forClass:(Class)c
125 | {
126 | if (!objectClass) return;
127 | self.objectClassInArrayDict[NSStringFromClass(c)] = objectClass;
128 | }
129 | - (Class)objectClassInArrayFromClass:(Class)c
130 | {
131 | return self.objectClassInArrayDict[NSStringFromClass(c)];
132 | }
133 | @end
134 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJType.h:
--------------------------------------------------------------------------------
1 | //
2 | // MJType.h
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | // 包装一种类型
8 |
9 | #import
10 | /**
11 | * 包装一种类型
12 | */
13 | @interface MJType : NSObject
14 | /** 类型标识符 */
15 | @property (nonatomic, copy) NSString *code;
16 |
17 | /** 是否为id类型 */
18 | @property (nonatomic, readonly, getter=isIdType) BOOL idType;
19 |
20 | /** 对象类型(如果是基本数据类型,此值为nil) */
21 | @property (nonatomic, readonly) Class typeClass;
22 |
23 | /** 类型是否来自于Foundation框架,比如NSString、NSArray */
24 | @property (nonatomic, readonly, getter = isFromFoundation) BOOL fromFoundation;
25 | /** 类型是否不支持KVC */
26 | @property (nonatomic, readonly, getter = isKVCDisabled) BOOL KVCDisabled;
27 |
28 | /**
29 | * 获得缓存的类型对象
30 | */
31 | + (instancetype)cachedTypeWithCode:(NSString *)code;
32 | @end
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/MJType.m:
--------------------------------------------------------------------------------
1 | //
2 | // MJType.m
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import "MJType.h"
10 | #import "MJExtension.h"
11 | #import "MJFoundation.h"
12 | #import "MJConst.h"
13 |
14 | @implementation MJType
15 |
16 | static NSMutableDictionary *_cachedTypes;
17 | + (void)load
18 | {
19 | _cachedTypes = [NSMutableDictionary dictionary];
20 | }
21 |
22 | + (instancetype)cachedTypeWithCode:(NSString *)code
23 | {
24 | MJAssertParamNotNil2(code, nil);
25 |
26 | MJType *type = _cachedTypes[code];
27 | if (type == nil) {
28 | type = [[self alloc] init];
29 | type.code = code;
30 | _cachedTypes[code] = type;
31 | }
32 | return type;
33 | }
34 |
35 | - (void)setCode:(NSString *)code
36 | {
37 | _code = code;
38 |
39 | MJAssertParamNotNil(code);
40 |
41 | if ([code isEqualToString:MJTypeId]) {
42 | _idType = YES;
43 | } else if (code.length == 0) {
44 | _KVCDisabled = YES;
45 | } else if (code.length > 3 && [code hasPrefix:@"@\""]) {
46 | // 去掉@"和",截取中间的类型名称
47 | _code = [code substringWithRange:NSMakeRange(2, code.length - 3)];
48 | _typeClass = NSClassFromString(_code);
49 | _fromFoundation = [MJFoundation isClassFromFoundation:_typeClass];
50 | } else if ([code isEqualToString:MJTypeSEL] ||
51 | [code isEqualToString:MJTypeIvar] ||
52 | [code isEqualToString:MJTypeMethod]) {
53 | _KVCDisabled = YES;
54 | }
55 | }
56 | @end
57 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/NSObject+MJCoding.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSObject+MJCoding.h
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import
10 | /**
11 | * Codeing协议
12 | */
13 | @protocol MJCoding
14 | @optional
15 | /**
16 | * 这个数组中的属性名将会被忽略:不进行归档
17 | */
18 | + (NSArray *)ignoredCodingPropertyNames;
19 | @end
20 |
21 | @interface NSObject (MJCoding)
22 | /**
23 | * 解码(从文件中解析对象)
24 | */
25 | - (void)decode:(NSCoder *)decoder;
26 | /**
27 | * 编码(将对象写入文件中)
28 | */
29 | - (void)encode:(NSCoder *)encoder;
30 | @end
31 |
32 | /**
33 | 归档的实现
34 | */
35 | #define MJCodingImplementation \
36 | - (id)initWithCoder:(NSCoder *)decoder \
37 | { \
38 | if (self = [super init]) { \
39 | [self decode:decoder]; \
40 | } \
41 | return self; \
42 | } \
43 | \
44 | - (void)encodeWithCoder:(NSCoder *)encoder \
45 | { \
46 | [self encode:encoder]; \
47 | }
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/NSObject+MJCoding.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSObject+MJCoding.m
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import "NSObject+MJCoding.h"
10 | #import "NSObject+MJIvar.h"
11 | #import "MJIvar.h"
12 |
13 | @implementation NSObject (MJCoding)
14 |
15 | - (void)encode:(NSCoder *)encoder
16 | {
17 | NSArray *ignoredCodingPropertyNames = nil;
18 | if ([[self class] respondsToSelector:@selector(ignoredCodingPropertyNames)]) {
19 | ignoredCodingPropertyNames = [[self class] ignoredCodingPropertyNames];
20 | }
21 |
22 | [[self class] enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
23 | // 检测是否被忽略
24 | if ([ignoredCodingPropertyNames containsObject:ivar.propertyName]) return;
25 |
26 | id value = [ivar valueFromObject:self];
27 | if (value == nil) return;
28 | [encoder encodeObject:value forKey:ivar.name];
29 | }];
30 | }
31 |
32 | - (void)decode:(NSCoder *)decoder
33 | {
34 | NSArray *ignoredCodingPropertyNames = nil;
35 | if ([[self class] respondsToSelector:@selector(ignoredCodingPropertyNames)]) {
36 | ignoredCodingPropertyNames = [[self class] ignoredCodingPropertyNames];
37 | }
38 |
39 | [[self class] enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
40 | // 检测是否被忽略
41 | if ([ignoredCodingPropertyNames containsObject:ivar.propertyName]) return;
42 |
43 | id value = [decoder decodeObjectForKey:ivar.name];
44 | if (value == nil) return;
45 | [ivar setValue:value forObject:self];
46 | }];
47 | }
48 | @end
49 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/NSObject+MJIvar.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSObject+MJIvar.h
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import
10 | @class MJIvar;
11 |
12 | /**
13 | * 遍历所有类的block(父类)
14 | */
15 | typedef void (^MJClassesBlock)(Class c, BOOL *stop);
16 |
17 | /**
18 | * 遍历成员变量用的block
19 | *
20 | * @param ivar 成员变量的包装对象
21 | * @param stop YES代表停止遍历,NO代表继续遍历
22 | */
23 | typedef void (^MJIvarsBlock)(MJIvar *ivar, BOOL *stop);
24 |
25 | @interface NSObject (MJMember)
26 |
27 | /**
28 | * 遍历所有的成员变量
29 | */
30 | + (void)enumerateIvarsWithBlock:(MJIvarsBlock)block;
31 |
32 | /**
33 | * 遍历所有的类
34 | */
35 | + (void)enumerateClassesWithBlock:(MJClassesBlock)block;
36 |
37 | /**
38 | * 返回一个临时对象
39 | */
40 | + (instancetype)tempObject;
41 | @end
42 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/NSObject+MJIvar.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSObject+MJIvar.m
3 | // MJExtension
4 | //
5 | // Created by mj on 14-1-15.
6 | // Copyright (c) 2014年 itcast. All rights reserved.
7 | //
8 |
9 | #import "MJIvar.h"
10 | #import "NSObject+MJIvar.h"
11 | #import "NSObject+MJKeyValue.h"
12 | #import "MJFoundation.h"
13 |
14 | @implementation NSObject (MJMember)
15 |
16 | #pragma mark - --私有方法--
17 | + (NSString *)ivarKey:(NSString *)propertyName
18 | {
19 | MJAssertParamNotNil2(propertyName, nil);
20 |
21 | NSString *key = nil;
22 | // 1.查看有没有需要替换的key
23 | if ([self respondsToSelector:@selector(replacedKeyFromPropertyName:)]) {
24 | key = [self replacedKeyFromPropertyName:propertyName];
25 | } else if ([self respondsToSelector:@selector(replacedKeyFromPropertyName)]) {
26 | key = self.replacedKeyFromPropertyName[propertyName];
27 | } else {
28 | // 为了兼容以前的对象方法
29 | id tempObject = self.tempObject;
30 | if ([tempObject respondsToSelector:@selector(replacedKeyFromPropertyName)]) {
31 | key = [tempObject replacedKeyFromPropertyName][propertyName];
32 | }
33 | }
34 |
35 | // 2.用属性名作为key
36 | if (!key) key = propertyName;
37 |
38 | return key;
39 | }
40 |
41 | + (Class)ivarObjectClassInArray:(NSString *)propertyName
42 | {
43 | id class = nil;
44 | if ([self respondsToSelector:@selector(objectClassInArray:)]) {
45 | class = [self objectClassInArray:propertyName];
46 | } else if ([self respondsToSelector:@selector(objectClassInArray)]) {
47 | class = self.objectClassInArray[propertyName];
48 | } else {
49 | // 为了兼容以前的对象方法
50 | id tempObject = self.tempObject;
51 | if ([tempObject respondsToSelector:@selector(objectClassInArray)]) {
52 | id dict = [tempObject objectClassInArray];
53 | class = dict[propertyName];
54 | }
55 | }
56 | // 如果是NSString类型
57 | if ([class isKindOfClass:[NSString class]]) {
58 | class = NSClassFromString(class);
59 | }
60 | return class;
61 | }
62 |
63 | #pragma mark - --公共方法--
64 | + (instancetype)tempObject
65 | {
66 | static const char MJTempObjectKey;
67 | id tempObject = objc_getAssociatedObject(self, &MJTempObjectKey);
68 | if (tempObject == nil) {
69 | tempObject = [[self alloc] init];
70 | objc_setAssociatedObject(self, &MJTempObjectKey, tempObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
71 | }
72 | return tempObject;
73 | }
74 |
75 | + (void)enumerateIvarsWithBlock:(MJIvarsBlock)block
76 | {
77 | static const char MJCachedIvarsKey;
78 | // 获得成员变量
79 | NSMutableArray *cachedIvars = objc_getAssociatedObject(self, &MJCachedIvarsKey);
80 | if (cachedIvars == nil) {
81 | cachedIvars = [NSMutableArray array];
82 |
83 | [self enumerateClassesWithBlock:^(__unsafe_unretained Class c, BOOL *stop) {
84 | // 1.获得所有的成员变量
85 | unsigned int outCount = 0;
86 | Ivar *ivars = class_copyIvarList(c, &outCount);
87 |
88 | // 2.遍历每一个成员变量
89 | for (unsigned int i = 0; i
10 | #import "MJConst.h"
11 |
12 | /**
13 | * KeyValue协议
14 | */
15 | @protocol MJKeyValue
16 | @optional
17 | /**
18 | * 这个数组中的属性名将会被忽略:不进行字典和模型的转换
19 | */
20 | + (NSArray *)ignoredPropertyNames;
21 |
22 | /**
23 | * 将属性名换为其他key去字典中取值
24 | *
25 | * @return 字典中的key是属性名,value是从字典中取值用的key
26 | */
27 | + (NSDictionary *)replacedKeyFromPropertyName;
28 | - (NSDictionary *)replacedKeyFromPropertyName MJDeprecated("请使用+ (NSDictionary *)replacedKeyFromPropertyName方法");
29 |
30 | /**
31 | * 将属性名换为其他key去字典中取值
32 | * @param propertyName 属性名
33 | *
34 | * @return 字典中的key
35 | */
36 | + (NSString *)replacedKeyFromPropertyName:(NSString *)propertyName;
37 | // 方法优先级:replacedKeyFromPropertyName: > replacedKeyFromPropertyName
38 |
39 | /**
40 | * 数组中需要转换的模型类
41 | *
42 | * @return 字典中的key是数组属性名,value是数组中存放模型的Class(Class类型或者NSString类型)
43 | */
44 | + (NSDictionary *)objectClassInArray;
45 | - (NSDictionary *)objectClassInArray MJDeprecated("请使用+ (NSDictionary *)objectClassInArray方法");
46 | /**
47 | * 数组中需要转换的模型类
48 | *
49 | * @return 数组中存放模型的Class
50 | */
51 | + (Class)objectClassInArray:(NSString *)propertyName;
52 | // 方法优先级:objectClassInArray: > objectClassInArray
53 |
54 | /**
55 | * 当字典转模型完毕时调用
56 | */
57 | - (void)keyValuesDidFinishConvertingToObject;
58 |
59 | /**
60 | * 当模型转字典完毕时调用
61 | */
62 | - (void)objectDidFinishConvertingToKeyValues;
63 | @end
64 |
65 | @interface NSObject (MJKeyValue)
66 | /**
67 | * 将字典的键值对转成模型属性
68 | * @param keyValues 字典
69 | */
70 | - (instancetype)setKeyValues:(NSDictionary *)keyValues;
71 | - (instancetype)setKeyValues:(NSDictionary *)keyValues error:(NSError **)error;
72 |
73 | /**
74 | * 将模型转成字典
75 | * @return 字典
76 | */
77 | - (NSDictionary *)keyValues;
78 | - (NSDictionary *)keyValuesWithError:(NSError **)error;
79 |
80 | /**
81 | * 通过模型数组来创建一个字典数组
82 | * @param objectArray 模型数组
83 | * @return 字典数组
84 | */
85 | + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray;
86 | + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray error:(NSError **)error;
87 |
88 | #pragma mark - 字典转模型
89 | /**
90 | * 通过JSON数据来创建一个模型
91 | * @param data JSON数据
92 | * @return 新建的对象
93 | */
94 | + (instancetype)objectWithJSONData:(NSData *)data;
95 | + (instancetype)objectWithJSONData:(NSData *)data error:(NSError **)error;
96 |
97 | /**
98 | * 通过字典来创建一个模型
99 | * @param keyValues 字典
100 | * @return 新建的对象
101 | */
102 | + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues;
103 | + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues error:(NSError **)error;
104 |
105 | /**
106 | * 通过plist来创建一个模型
107 | * @param filename 文件名(仅限于mainBundle中的文件)
108 | * @return 新建的对象
109 | */
110 | + (instancetype)objectWithFilename:(NSString *)filename;
111 | + (instancetype)objectWithFilename:(NSString *)filename error:(NSError **)error;
112 |
113 | /**
114 | * 通过plist来创建一个模型
115 | * @param file 文件全路径
116 | * @return 新建的对象
117 | */
118 | + (instancetype)objectWithFile:(NSString *)file;
119 | + (instancetype)objectWithFile:(NSString *)file error:(NSError **)error;
120 |
121 | #pragma mark - 字典数组转模型数组
122 | /**
123 | * 通过JSON数据来创建一个模型数组
124 | * @param data JSON数据
125 | * @return 新建的对象
126 | */
127 | + (NSArray *)objectArrayWithJSONData:(NSData *)data;
128 | + (NSArray *)objectArrayWithJSONData:(NSData *)data error:(NSError **)error;
129 |
130 | /**
131 | * 通过字典数组来创建一个模型数组
132 | * @param keyValuesArray 字典数组
133 | * @return 模型数组
134 | */
135 | + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray;
136 | + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray error:(NSError **)error;
137 |
138 | /**
139 | * 通过plist来创建一个模型数组
140 | * @param filename 文件名(仅限于mainBundle中的文件)
141 | * @return 模型数组
142 | */
143 | + (NSArray *)objectArrayWithFilename:(NSString *)filename;
144 | + (NSArray *)objectArrayWithFilename:(NSString *)filename error:(NSError **)error;
145 |
146 | /**
147 | * 通过plist来创建一个模型数组
148 | * @param file 文件全路径
149 | * @return 模型数组
150 | */
151 | + (NSArray *)objectArrayWithFile:(NSString *)file;
152 | + (NSArray *)objectArrayWithFile:(NSString *)file error:(NSError **)error;
153 | @end
154 |
--------------------------------------------------------------------------------
/CYLHttpTest/Tool(工具类)/MJExtension/NSObject+MJKeyValue.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSObject+MJKeyValue.m
3 | // MJExtension
4 | //
5 | // Created by mj on 13-8-24.
6 | // Copyright (c) 2013年 itcast. All rights reserved.
7 | //
8 |
9 | #import "NSObject+MJKeyValue.h"
10 | #import "NSObject+MJIvar.h"
11 | #import "MJIvar.h"
12 | #import "MJType.h"
13 | #import "MJConst.h"
14 | #import "MJFoundation.h"
15 |
16 | @implementation NSObject (MJKeyValue)
17 |
18 | #pragma mark - --常用的对象--
19 | static NSNumberFormatter *_numberFormatter;
20 | + (void)load
21 | {
22 | _numberFormatter = [[NSNumberFormatter alloc] init];
23 | }
24 |
25 | #pragma mark - --公共方法--
26 | + (instancetype)objectWithJSONData:(NSData *)data
27 | {
28 | return [self objectWithJSONData:data error:nil];
29 | }
30 |
31 | + (instancetype)objectWithJSONData:(NSData *)data error:(NSError *__autoreleasing *)error
32 | {
33 | MJAssertError(data != nil, nil, error, @"JSONData参数为nil");
34 |
35 | return [self objectWithKeyValues:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil] error:error];
36 | }
37 |
38 | + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues
39 | {
40 | return [self objectWithKeyValues:keyValues error:nil];
41 | }
42 |
43 | + (instancetype)objectWithKeyValues:(NSDictionary *)keyValues error:(NSError *__autoreleasing *)error
44 | {
45 | return [[[self alloc] init] setKeyValues:keyValues error:error];
46 | }
47 |
48 | + (instancetype)objectWithFilename:(NSString *)filename
49 | {
50 | return [self objectWithFilename:filename error:nil];
51 | }
52 |
53 | + (instancetype)objectWithFilename:(NSString *)filename error:(NSError *__autoreleasing *)error
54 | {
55 | MJAssertError(filename != nil, nil, error, @"filename参数为nil");
56 |
57 | return [self objectWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil] error:error];
58 | }
59 |
60 | + (instancetype)objectWithFile:(NSString *)file
61 | {
62 | return [self objectWithFile:file error:nil];
63 | }
64 |
65 | + (instancetype)objectWithFile:(NSString *)file error:(NSError *__autoreleasing *)error
66 | {
67 | MJAssertError(file != nil, nil, error, @"file参数为nil");
68 |
69 | return [self objectWithKeyValues:[NSDictionary dictionaryWithContentsOfFile:file] error:error];
70 | }
71 |
72 | - (instancetype)setKeyValues:(NSDictionary *)keyValues
73 | {
74 | return [self setKeyValues:keyValues error:nil];
75 | }
76 |
77 | - (instancetype)setKeyValues:(NSDictionary *)keyValues error:(NSError *__autoreleasing *)error
78 | {
79 | MJAssertError([keyValues isKindOfClass:[NSDictionary class]], self, error, @"keyValues参数不是一个字典");
80 |
81 | @try {
82 | NSArray *ignoredPropertyNames = nil;
83 | if ([[self class] respondsToSelector:@selector(ignoredPropertyNames)]) {
84 | ignoredPropertyNames = [[self class] ignoredPropertyNames];
85 | }
86 |
87 | [[self class] enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
88 | // 0.检测是否被忽略
89 | if ([ignoredPropertyNames containsObject:ivar.propertyName]) return;
90 |
91 | // 1.取出属性值
92 | id value = keyValues ;
93 | NSArray *keys = [ivar keysFromClass:[self class]];
94 | for (NSString *key in keys) {
95 | if (![value isKindOfClass:[NSDictionary class]]) continue;
96 | value = value[key];
97 | }
98 | if (!value || value == [NSNull null]) return;
99 |
100 | // 2.如果是模型属性
101 | MJType *type = ivar.type;
102 | Class typeClass = type.typeClass;
103 | if (!type.isFromFoundation && typeClass) {
104 | value = [typeClass objectWithKeyValues:value];
105 | } else if (typeClass == [NSString class]) {
106 | if ([value isKindOfClass:[NSNumber class]]) {
107 | // NSNumber -> NSString
108 | value = [value description];
109 | } else if ([value isKindOfClass:[NSURL class]]) {
110 | // NSURL -> NSString
111 | value = [value absoluteString];
112 | }
113 | } else if ([value isKindOfClass:[NSString class]]) {
114 | if (typeClass == [NSNumber class]) {
115 | // NSString -> NSNumber
116 | value = [_numberFormatter numberFromString:value];
117 | } else if (typeClass == [NSURL class]) {
118 | // NSString -> NSURL
119 | value = [NSURL URLWithString:value];
120 | }
121 | } else {
122 | Class objectClass = [ivar objectClassInArrayFromClass:[self class]];
123 | if (objectClass) {
124 | // 3.字典数组-->模型数组
125 | value = [objectClass objectArrayWithKeyValuesArray:value];
126 | }
127 | }
128 |
129 | // 4.赋值
130 | [ivar setValue:value forObject:self];
131 | }];
132 |
133 | // 转换完毕
134 | if ([self respondsToSelector:@selector(keyValuesDidFinishConvertingToObject)]) {
135 | [self keyValuesDidFinishConvertingToObject];
136 | }
137 | } @catch (NSException *exception) {
138 | MJBuildError(error, exception.reason);
139 | }
140 | return self;
141 | }
142 |
143 | + (NSArray *)objectArrayWithJSONData:(NSData *)data
144 | {
145 | return [self objectArrayWithJSONData:data error:nil];
146 | }
147 |
148 | + (NSArray *)objectArrayWithJSONData:(NSData *)data error:(NSError *__autoreleasing *)error
149 | {
150 | MJAssertError(data != nil, nil, error, @"JSONData参数为nil");
151 |
152 | return [self objectArrayWithKeyValuesArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil] error:error];
153 | }
154 |
155 | + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray
156 | {
157 | return [self objectArrayWithKeyValuesArray:keyValuesArray error:nil];
158 | }
159 |
160 | + (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray error:(NSError *__autoreleasing *)error
161 | {
162 | // 1.判断真实性
163 | MJAssertError([keyValuesArray isKindOfClass:[NSArray class]], nil, error, @"keyValuesArray参数不是一个数组");
164 |
165 | // 2.创建数组
166 | NSMutableArray *modelArray = [NSMutableArray array];
167 |
168 | // 3.遍历
169 | for (NSDictionary *keyValues in keyValuesArray) {
170 | id model = [self objectWithKeyValues:keyValues error:error];
171 | if (model) [modelArray addObject:model];
172 | }
173 |
174 | return modelArray;
175 | }
176 |
177 | + (NSArray *)objectArrayWithFilename:(NSString *)filename
178 | {
179 | return [self objectArrayWithFilename:filename error:nil];
180 | }
181 |
182 | + (NSArray *)objectArrayWithFilename:(NSString *)filename error:(NSError *__autoreleasing *)error
183 | {
184 | MJAssertError(filename != nil, nil, error, @"filename参数为nil");
185 |
186 | return [self objectArrayWithFile:[[NSBundle mainBundle] pathForResource:filename ofType:nil] error:error];
187 | }
188 |
189 | + (NSArray *)objectArrayWithFile:(NSString *)file
190 | {
191 | return [self objectArrayWithFile:file error:nil];
192 | }
193 |
194 | + (NSArray *)objectArrayWithFile:(NSString *)file error:(NSError *__autoreleasing *)error
195 | {
196 | MJAssertError(file != nil, nil, error, @"file参数为nil");
197 |
198 | return [self objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:file] error:error];
199 | }
200 |
201 | - (NSDictionary *)keyValues
202 | {
203 | return [self keyValuesWithError:nil];
204 | }
205 |
206 | - (NSDictionary *)keyValuesWithError:(NSError *__autoreleasing *)error
207 | {
208 | // 如果自己不是模型类
209 | if ([MJFoundation isClassFromFoundation:[self class]]) return (NSDictionary *)self;
210 |
211 | __block NSMutableDictionary *keyValues = [NSMutableDictionary dictionary];
212 |
213 | @try {
214 | NSArray *ignoredPropertyNames = nil;
215 | if ([[self class] respondsToSelector:@selector(ignoredPropertyNames)]) {
216 | ignoredPropertyNames = [[self class] ignoredPropertyNames];
217 | }
218 |
219 | [[self class] enumerateIvarsWithBlock:^(MJIvar *ivar, BOOL *stop) {
220 | // 0.检测是否被忽略
221 | if ([ignoredPropertyNames containsObject:ivar.propertyName]) return;
222 |
223 | // 1.取出属性值
224 | id value = [ivar valueFromObject:self];
225 | if (!value) return;
226 |
227 | // 2.如果是模型属性
228 | MJType *type = ivar.type;
229 | Class typeClass = type.typeClass;
230 | if (!type.isFromFoundation && typeClass) {
231 | value = [value keyValues];
232 | } else if (typeClass == [NSURL class]) {
233 | value = [value absoluteString];
234 | } else {
235 | Class objectClass = [ivar objectClassInArrayFromClass:[self class]];
236 | if (objectClass) {
237 | // 3.处理数组里面有模型的情况
238 | value = [objectClass keyValuesArrayWithObjectArray:value];
239 | }
240 | }
241 |
242 | // 4.赋值
243 | NSArray *keys = [ivar keysFromClass:[self class]];
244 | NSUInteger keyCount = keys.count;
245 | // 创建字典
246 | __block NSMutableDictionary *innerDict = keyValues;
247 | [keys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
248 | if (idx == keyCount - 1) { // 最后一个属性
249 | innerDict[key] = value;
250 | } else { // 字典
251 | NSMutableDictionary *tempDict = innerDict[key];
252 | if (tempDict == nil) {
253 | tempDict = [NSMutableDictionary dictionary];
254 | innerDict[key] = tempDict;
255 | }
256 | innerDict = tempDict;
257 | }
258 | }];
259 | }];
260 |
261 | // 转换完毕
262 | if ([self respondsToSelector:@selector(objectDidFinishConvertingToKeyValues)]) {
263 | [self objectDidFinishConvertingToKeyValues];
264 | }
265 | } @catch (NSException *exception) {
266 | MJBuildError(error, exception.reason);
267 | }
268 |
269 | return keyValues;
270 | }
271 |
272 | + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray
273 | {
274 | return [self keyValuesArrayWithObjectArray:objectArray error:nil];
275 | }
276 |
277 | + (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray error:(NSError *__autoreleasing *)error
278 | {
279 | // 0.判断真实性
280 | MJAssertError([objectArray isKindOfClass:[NSArray class]], nil, error, @"objectArray参数不是一个数组");
281 |
282 | // 1.创建数组
283 | NSMutableArray *keyValuesArray = [NSMutableArray array];
284 | for (id object in objectArray) {
285 | [keyValuesArray addObject:[object keyValuesWithError:error]];
286 | }
287 | return keyValuesArray;
288 | }
289 | @end
290 |
--------------------------------------------------------------------------------
/CYLHttpTest/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface ViewController : UIViewController
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/CYLHttpTest/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import "ViewController.h"
10 | #import "CYLHttpTool.h"
11 | #import "CYLHttpTestTool.h"
12 | #import "CYLHttpTestParam.h"
13 |
14 | @interface ViewController ()
15 |
16 | @end
17 |
18 | @implementation ViewController
19 |
20 |
21 | - (IBAction)requestButtonClicked:(id)sender {
22 |
23 | CYLHttpTestParam *param = [[CYLHttpTestParam alloc] init];
24 | param.hospitalName = @"111";
25 | [CYLHttpTestTool operateNetHttpTestWithParam:param success:^(CYLHttpTestResult *result) {
26 | NSLog(@"✅✅✅✅✅✅✅%@",result);
27 | } failure:^(NSError *error) {
28 | NSLog(@"‼️‼️‼️‼️‼️%@",error);
29 | }];
30 | }
31 |
32 | @end
33 |
--------------------------------------------------------------------------------
/CYLHttpTest/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // CYLHttpTest
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/CYLHttpTestTests/CYLHttpTestTests.m:
--------------------------------------------------------------------------------
1 | //
2 | // CYLHttpTestTests.m
3 | // CYLHttpTestTests
4 | //
5 | // Created by chenyilong on 15/4/7.
6 | // Copyright (c) 2015年 chenyilong. All rights reserved.
7 | //
8 |
9 | #import
10 | #import
11 |
12 | @interface CYLHttpTestTests : XCTestCase
13 |
14 | @end
15 |
16 | @implementation CYLHttpTestTests
17 |
18 | - (void)setUp {
19 | [super setUp];
20 | // Put setup code here. This method is called before the invocation of each test method in the class.
21 | }
22 |
23 | - (void)tearDown {
24 | // Put teardown code here. This method is called after the invocation of each test method in the class.
25 | [super tearDown];
26 | }
27 |
28 | - (void)testExample {
29 | // This is an example of a functional test case.
30 | XCTAssert(YES, @"Pass");
31 | }
32 |
33 | - (void)testPerformanceExample {
34 | // This is an example of a performance test case.
35 | [self measureBlock:^{
36 | // Put the code you want to measure the time of here.
37 | }];
38 | }
39 |
40 | @end
41 |
--------------------------------------------------------------------------------
/CYLHttpTestTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | CYL.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------