WKWebView+AFNetworking.m 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // WkWebView+AFNetworking.m
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "WKWebView+AFNetworking.h"
  22. #import <objc/runtime.h>
  23. #if TARGET_OS_IOS
  24. #import "AFHTTPSessionManager.h"
  25. #import "AFURLResponseSerialization.h"
  26. #import "AFURLRequestSerialization.h"
  27. @interface WKWebView (_AFNetworking)
  28. @property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
  29. @end
  30. @implementation WKWebView (_AFNetworking)
  31. - (NSURLSessionDataTask *)af_URLSessionTask {
  32. return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
  33. }
  34. - (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
  35. objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  36. }
  37. @end
  38. #pragma mark -
  39. @implementation WKWebView (AFNetworking)
  40. - (AFHTTPSessionManager *)sessionManager {
  41. static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
  42. static dispatch_once_t onceToken;
  43. dispatch_once(&onceToken, ^{
  44. _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  45. _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
  46. _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
  47. });
  48. return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
  49. }
  50. - (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
  51. objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  52. }
  53. - (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
  54. static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
  55. static dispatch_once_t onceToken;
  56. dispatch_once(&onceToken, ^{
  57. _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
  58. });
  59. return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
  60. }
  61. - (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
  62. objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  63. }
  64. #pragma mark -
  65. - (void)loadRequest:(NSURLRequest *)request
  66. navigation:(WKNavigation * _Nonnull)navigation
  67. progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
  68. success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
  69. failure:(nullable void (^)(NSError *error))failure {
  70. [self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) {
  71. NSStringEncoding stringEncoding = NSUTF8StringEncoding;
  72. if (response.textEncodingName) {
  73. CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
  74. if (encoding != kCFStringEncodingInvalidId) {
  75. stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
  76. }
  77. }
  78. NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
  79. if (success) {
  80. string = success(response, string);
  81. }
  82. return [string dataUsingEncoding:stringEncoding];
  83. } failure:failure];
  84. }
  85. - (void)loadRequest:(NSURLRequest *)request
  86. navigation:(WKNavigation * _Nonnull)navigation
  87. MIMEType:(nullable NSString *)MIMEType
  88. textEncodingName:(nullable NSString *)textEncodingName
  89. progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
  90. success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
  91. failure:(nullable void (^)(NSError *error))failure {
  92. NSParameterAssert(request);
  93. if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
  94. [self.af_URLSessionTask cancel];
  95. }
  96. self.af_URLSessionTask = nil;
  97. __weak __typeof(self)weakSelf = self;
  98. __block NSURLSessionDataTask *dataTask;
  99. __strong __typeof(weakSelf) strongSelf = weakSelf;
  100. __strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate;
  101. dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  102. if (error) {
  103. if (failure) {
  104. failure(error);
  105. }
  106. } else {
  107. if (success) {
  108. success((NSHTTPURLResponse *)response, responseObject);
  109. }
  110. [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
  111. if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
  112. [strongSelfDelegate webView:strongSelf didFinishNavigation:navigation];
  113. }
  114. }
  115. }];
  116. self.af_URLSessionTask = dataTask;
  117. if (progress != nil) {
  118. *progress = [self.sessionManager downloadProgressForTask:dataTask];
  119. }
  120. [self.af_URLSessionTask resume];
  121. if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
  122. [strongSelfDelegate webView:self didStartProvisionalNavigation:navigation];
  123. }
  124. }
  125. @end
  126. #endif