Commit 70bd7649 authored by 董振宁's avatar 董振宁

first

parents
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXAggregateTarget section */
A6DDD7041F384D8300B66159 /* TaTmSDKG */ = {
isa = PBXAggregateTarget;
buildConfigurationList = A6DDD7071F384D8300B66159 /* Build configuration list for PBXAggregateTarget "TaTmSDKG" */;
buildPhases = (
A6DDD70A1F384DBE00B66159 /* ShellScript */,
);
dependencies = (
A6DDD7091F384DB800B66159 /* PBXTargetDependency */,
);
name = TaTmSDKG;
productName = TaTmSDKG;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
A606EDE71F34215C008789DB /* libduibaFMDeviceManager_without_IDFA.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A6C9383C1E9F566B0039B6DA /* libduibaFMDeviceManager_without_IDFA.a */; };
A6C938971E9F566C0039B6DA /* duiba_FMDeviceManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9383B1E9F566B0039B6DA /* duiba_FMDeviceManager.h */; };
A6C938A41E9F566C0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9384C1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.h */; };
A6C938A51E9F566C0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9384D1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.m */; };
A6C938A61E9F566C0039B6DA /* HAIJIANPPAFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9384E1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.h */; };
A6C938A71E9F566C0039B6DA /* HAIJIANPPAFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9384F1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.m */; };
A6C938A81E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938501E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.h */; };
A6C938A91E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938511E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.m */; };
A6C938AA1E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperationManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938521E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.h */; };
A6C938AB1E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938531E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.m */; };
A6C938AC1E9F566C0039B6DA /* HAIJIANPPHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938541E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.h */; };
A6C938AD1E9F566C0039B6DA /* HAIJIANPPHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938551E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.m */; };
A6C938AE1E9F566C0039B6DA /* HAIJIANPPNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938561E9F566B0039B6DA /* HAIJIANPPNetworking.h */; };
A6C938AF1E9F566C0039B6DA /* HAIJIANPPNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938571E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.h */; };
A6C938B01E9F566C0039B6DA /* HAIJIANPPNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938581E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.m */; };
A6C938B11E9F566C0039B6DA /* HAIJIANPPSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938591E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.h */; };
A6C938B21E9F566C0039B6DA /* HAIJIANPPSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9385A1E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.m */; };
A6C938B31E9F566C0039B6DA /* HAIJIANPPURLConnectionOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9385B1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.h */; };
A6C938B41E9F566C0039B6DA /* HAIJIANPPURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9385C1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.m */; };
A6C938B51E9F566C0039B6DA /* HAIJIANPPURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9385D1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.h */; };
A6C938B61E9F566C0039B6DA /* HAIJIANPPURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9385E1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.m */; };
A6C938B71E9F566C0039B6DA /* HAIJIANPPURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9385F1E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.h */; };
A6C938B81E9F566C0039B6DA /* HAIJIANPPURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938601E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.m */; };
A6C938B91E9F566C0039B6DA /* HAIJIANPPURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938611E9F566B0039B6DA /* HAIJIANPPURLSessionManager.h */; };
A6C938BA1E9F566C0039B6DA /* HAIJIANPPURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938621E9F566B0039B6DA /* HAIJIANPPURLSessionManager.m */; };
A6C938BB1E9F566C0039B6DA /* UIImageView+HAIJIANPPAFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938631E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.h */; };
A6C938BC1E9F566C0039B6DA /* UIImageView+HAIJIANPPAFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938641E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.m */; };
A6C938BF1E9F566C0039B6DA /* UIImage+dzanimatedGIF.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938681E9F566B0039B6DA /* UIImage+dzanimatedGIF.h */; };
A6C938C01E9F566C0039B6DA /* UIImage+dzanimatedGIF.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938691E9F566B0039B6DA /* UIImage+dzanimatedGIF.m */; };
A6C938C11E9F566C0039B6DA /* TaAppWallView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9386A1E9F566B0039B6DA /* TaAppWallView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938C21E9F566C0039B6DA /* TaAppWallView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9386B1E9F566B0039B6DA /* TaAppWallView.m */; };
A6C938C31E9F566C0039B6DA /* TaBnView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9386C1E9F566B0039B6DA /* TaBnView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938C41E9F566C0039B6DA /* TaBnView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9386D1E9F566B0039B6DA /* TaBnView.m */; };
A6C938C51E9F566C0039B6DA /* TaBaseActivityView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9386E1E9F566B0039B6DA /* TaBaseActivityView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938C61E9F566C0039B6DA /* TaBaseActivityView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9386F1E9F566B0039B6DA /* TaBaseActivityView.m */; };
A6C938C71E9F566C0039B6DA /* TaDriftView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938701E9F566B0039B6DA /* TaDriftView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938C81E9F566C0039B6DA /* TaDriftView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938711E9F566B0039B6DA /* TaDriftView.m */; };
A6C938C91E9F566C0039B6DA /* TaInfoStreamerView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938721E9F566B0039B6DA /* TaInfoStreamerView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938CA1E9F566C0039B6DA /* TaInfoStreamerView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938731E9F566B0039B6DA /* TaInfoStreamerView.m */; };
A6C938CB1E9F566C0039B6DA /* TaLaunchScreenView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938741E9F566B0039B6DA /* TaLaunchScreenView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938CC1E9F566C0039B6DA /* TaLaunchScreenView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938751E9F566C0039B6DA /* TaLaunchScreenView.m */; };
A6C938CD1E9F566C0039B6DA /* TaScreenView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938761E9F566C0039B6DA /* TaScreenView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938CE1E9F566C0039B6DA /* TaScreenView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938771E9F566C0039B6DA /* TaScreenView.m */; };
A6C938CF1E9F566C0039B6DA /* TaSimpleWebViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938781E9F566C0039B6DA /* TaSimpleWebViewController.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938D01E9F566C0039B6DA /* TaSimpleWebViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938791E9F566C0039B6DA /* TaSimpleWebViewController.m */; };
A6C938D11E9F566C0039B6DA /* TaStreamerView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9387A1E9F566C0039B6DA /* TaStreamerView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938D21E9F566C0039B6DA /* TaStreamerView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9387B1E9F566C0039B6DA /* TaStreamerView.m */; };
A6C938D31E9F566C0039B6DA /* TaTmHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9387C1E9F566C0039B6DA /* TaTmHelper.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938D41E9F566C0039B6DA /* TaTmHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9387D1E9F566C0039B6DA /* TaTmHelper.m */; };
A6C938D51E9F566C0039B6DA /* TaUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9387E1E9F566C0039B6DA /* TaUtils.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938D61E9F566C0039B6DA /* TaUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9387F1E9F566C0039B6DA /* TaUtils.m */; };
A6C938D71E9F566C0039B6DA /* TuiaAd.bundle in Resources */ = {isa = PBXBuildFile; fileRef = A6C938801E9F566C0039B6DA /* TuiaAd.bundle */; };
A6C938DC1E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938881E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.h */; };
A6C938DD1E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938891E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.m */; };
A6C938DE1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9388A1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.h */; };
A6C938DF1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9388B1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.m */; };
A6C938E01E9F566C0039B6DA /* DZYLGIFImage.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9388D1E9F566C0039B6DA /* DZYLGIFImage.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938E11E9F566C0039B6DA /* DZYLGIFImage.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C9388E1E9F566C0039B6DA /* DZYLGIFImage.m */; };
A6C938E21E9F566C0039B6DA /* DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9388F1E9F566C0039B6DA /* DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h */; };
A6C938E31E9F566C0039B6DA /* DZYLImageView.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938901E9F566C0039B6DA /* DZYLImageView.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938E41E9F566C0039B6DA /* DZYLImageView.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938911E9F566C0039B6DA /* DZYLImageView.m */; };
A6C938E51E9F566C0039B6DA /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = A6C938921E9F566C0039B6DA /* Info.plist */; };
A6C938E61E9F566C0039B6DA /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = A6C938941E9F566C0039B6DA /* Info.plist */; };
A6C938E71E9F566C0039B6DA /* TaTm.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C938951E9F566C0039B6DA /* TaTm.h */; settings = {ATTRIBUTES = (Public, ); }; };
A6C938E81E9F566C0039B6DA /* TaTm.m in Sources */ = {isa = PBXBuildFile; fileRef = A6C938961E9F566C0039B6DA /* TaTm.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
A6DDD7081F384DB800B66159 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = A675B6741E5DD80300CE9377 /* Project object */;
proxyType = 1;
remoteGlobalIDString = A675B67C1E5DD80300CE9377;
remoteInfo = TaTmSDK;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
A675B67D1E5DD80300CE9377 /* TaTmSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = TaTmSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; };
A6C9383B1E9F566B0039B6DA /* duiba_FMDeviceManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = duiba_FMDeviceManager.h; sourceTree = "<group>"; };
A6C9383C1E9F566B0039B6DA /* libduibaFMDeviceManager_without_IDFA.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libduibaFMDeviceManager_without_IDFA.a; sourceTree = "<group>"; };
A6C9384C1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPAFAutoPurgingImageCache.h; sourceTree = "<group>"; };
A6C9384D1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPAFAutoPurgingImageCache.m; sourceTree = "<group>"; };
A6C9384E1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPAFImageDownloader.h; sourceTree = "<group>"; };
A6C9384F1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPAFImageDownloader.m; sourceTree = "<group>"; };
A6C938501E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPHTTPRequestOperation.h; sourceTree = "<group>"; };
A6C938511E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPHTTPRequestOperation.m; sourceTree = "<group>"; };
A6C938521E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPHTTPRequestOperationManager.h; sourceTree = "<group>"; };
A6C938531E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPHTTPRequestOperationManager.m; sourceTree = "<group>"; };
A6C938541E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPHTTPSessionManager.h; sourceTree = "<group>"; };
A6C938551E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPHTTPSessionManager.m; sourceTree = "<group>"; };
A6C938561E9F566B0039B6DA /* HAIJIANPPNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPNetworking.h; sourceTree = "<group>"; };
A6C938571E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPNetworkReachabilityManager.h; sourceTree = "<group>"; };
A6C938581E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPNetworkReachabilityManager.m; sourceTree = "<group>"; };
A6C938591E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPSecurityPolicy.h; sourceTree = "<group>"; };
A6C9385A1E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPSecurityPolicy.m; sourceTree = "<group>"; };
A6C9385B1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPURLConnectionOperation.h; sourceTree = "<group>"; };
A6C9385C1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPURLConnectionOperation.m; sourceTree = "<group>"; };
A6C9385D1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPURLRequestSerialization.h; sourceTree = "<group>"; };
A6C9385E1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPURLRequestSerialization.m; sourceTree = "<group>"; };
A6C9385F1E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPURLResponseSerialization.h; sourceTree = "<group>"; };
A6C938601E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPURLResponseSerialization.m; sourceTree = "<group>"; };
A6C938611E9F566B0039B6DA /* HAIJIANPPURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HAIJIANPPURLSessionManager.h; sourceTree = "<group>"; };
A6C938621E9F566B0039B6DA /* HAIJIANPPURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HAIJIANPPURLSessionManager.m; sourceTree = "<group>"; };
A6C938631E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+HAIJIANPPAFNetworking.h"; sourceTree = "<group>"; };
A6C938641E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+HAIJIANPPAFNetworking.m"; sourceTree = "<group>"; };
A6C938681E9F566B0039B6DA /* UIImage+dzanimatedGIF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+dzanimatedGIF.h"; sourceTree = "<group>"; };
A6C938691E9F566B0039B6DA /* UIImage+dzanimatedGIF.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+dzanimatedGIF.m"; sourceTree = "<group>"; };
A6C9386A1E9F566B0039B6DA /* TaAppWallView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaAppWallView.h; sourceTree = "<group>"; };
A6C9386B1E9F566B0039B6DA /* TaAppWallView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaAppWallView.m; sourceTree = "<group>"; };
A6C9386C1E9F566B0039B6DA /* TaBnView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaBnView.h; sourceTree = "<group>"; };
A6C9386D1E9F566B0039B6DA /* TaBnView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaBnView.m; sourceTree = "<group>"; };
A6C9386E1E9F566B0039B6DA /* TaBaseActivityView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaBaseActivityView.h; sourceTree = "<group>"; };
A6C9386F1E9F566B0039B6DA /* TaBaseActivityView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaBaseActivityView.m; sourceTree = "<group>"; };
A6C938701E9F566B0039B6DA /* TaDriftView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaDriftView.h; sourceTree = "<group>"; };
A6C938711E9F566B0039B6DA /* TaDriftView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaDriftView.m; sourceTree = "<group>"; };
A6C938721E9F566B0039B6DA /* TaInfoStreamerView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaInfoStreamerView.h; sourceTree = "<group>"; };
A6C938731E9F566B0039B6DA /* TaInfoStreamerView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaInfoStreamerView.m; sourceTree = "<group>"; };
A6C938741E9F566B0039B6DA /* TaLaunchScreenView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaLaunchScreenView.h; sourceTree = "<group>"; };
A6C938751E9F566C0039B6DA /* TaLaunchScreenView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaLaunchScreenView.m; sourceTree = "<group>"; };
A6C938761E9F566C0039B6DA /* TaScreenView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaScreenView.h; sourceTree = "<group>"; };
A6C938771E9F566C0039B6DA /* TaScreenView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaScreenView.m; sourceTree = "<group>"; };
A6C938781E9F566C0039B6DA /* TaSimpleWebViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaSimpleWebViewController.h; sourceTree = "<group>"; };
A6C938791E9F566C0039B6DA /* TaSimpleWebViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaSimpleWebViewController.m; sourceTree = "<group>"; };
A6C9387A1E9F566C0039B6DA /* TaStreamerView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaStreamerView.h; sourceTree = "<group>"; };
A6C9387B1E9F566C0039B6DA /* TaStreamerView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaStreamerView.m; sourceTree = "<group>"; };
A6C9387C1E9F566C0039B6DA /* TaTmHelper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaTmHelper.h; sourceTree = "<group>"; };
A6C9387D1E9F566C0039B6DA /* TaTmHelper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaTmHelper.m; sourceTree = "<group>"; };
A6C9387E1E9F566C0039B6DA /* TaUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaUtils.h; sourceTree = "<group>"; };
A6C9387F1E9F566C0039B6DA /* TaUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaUtils.m; sourceTree = "<group>"; };
A6C938801E9F566C0039B6DA /* TuiaAd.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = TuiaAd.bundle; sourceTree = "<group>"; };
A6C938881E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIDevice+VKKeychainIDFV.h"; sourceTree = "<group>"; };
A6C938891E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIDevice+VKKeychainIDFV.m"; sourceTree = "<group>"; };
A6C9388A1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIViewController+DZBackButtonHandler.h"; sourceTree = "<group>"; };
A6C9388B1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIViewController+DZBackButtonHandler.m"; sourceTree = "<group>"; };
A6C9388D1E9F566C0039B6DA /* DZYLGIFImage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DZYLGIFImage.h; sourceTree = "<group>"; };
A6C9388E1E9F566C0039B6DA /* DZYLGIFImage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DZYLGIFImage.m; sourceTree = "<group>"; };
A6C9388F1E9F566C0039B6DA /* DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h"; sourceTree = "<group>"; };
A6C938901E9F566C0039B6DA /* DZYLImageView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DZYLImageView.h; sourceTree = "<group>"; };
A6C938911E9F566C0039B6DA /* DZYLImageView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DZYLImageView.m; sourceTree = "<group>"; };
A6C938921E9F566C0039B6DA /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A6C938941E9F566C0039B6DA /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A6C938951E9F566C0039B6DA /* TaTm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TaTm.h; sourceTree = "<group>"; };
A6C938961E9F566C0039B6DA /* TaTm.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TaTm.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A675B6791E5DD80300CE9377 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A606EDE71F34215C008789DB /* libduibaFMDeviceManager_without_IDFA.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A675B6731E5DD80300CE9377 = {
isa = PBXGroup;
children = (
A6C938381E9F566B0039B6DA /* TaTmSDK */,
A675B67E1E5DD80300CE9377 /* Products */,
);
sourceTree = "<group>";
};
A675B67E1E5DD80300CE9377 /* Products */ = {
isa = PBXGroup;
children = (
A675B67D1E5DD80300CE9377 /* TaTmSDK.framework */,
);
name = Products;
sourceTree = "<group>";
};
A6C938381E9F566B0039B6DA /* TaTmSDK */ = {
isa = PBXGroup;
children = (
A6C938391E9F566B0039B6DA /* AdIOSSDK */,
A6C938921E9F566C0039B6DA /* Info.plist */,
A6C938931E9F566C0039B6DA /* TaTm */,
);
path = TaTmSDK;
sourceTree = "<group>";
};
A6C938391E9F566B0039B6DA /* AdIOSSDK */ = {
isa = PBXGroup;
children = (
A6C9383A1E9F566B0039B6DA /* duiba_FMDeviceManager_v2.1.5_515b4f1 */,
A6C9384B1E9F566B0039B6DA /* PPNetworking */,
A6C938651E9F566B0039B6DA /* Reachability */,
A6C9386A1E9F566B0039B6DA /* TaAppWallView.h */,
A6C9386B1E9F566B0039B6DA /* TaAppWallView.m */,
A6C9386C1E9F566B0039B6DA /* TaBnView.h */,
A6C9386D1E9F566B0039B6DA /* TaBnView.m */,
A6C9386E1E9F566B0039B6DA /* TaBaseActivityView.h */,
A6C9386F1E9F566B0039B6DA /* TaBaseActivityView.m */,
A6C938701E9F566B0039B6DA /* TaDriftView.h */,
A6C938711E9F566B0039B6DA /* TaDriftView.m */,
A6C938721E9F566B0039B6DA /* TaInfoStreamerView.h */,
A6C938731E9F566B0039B6DA /* TaInfoStreamerView.m */,
A6C938741E9F566B0039B6DA /* TaLaunchScreenView.h */,
A6C938751E9F566C0039B6DA /* TaLaunchScreenView.m */,
A6C938761E9F566C0039B6DA /* TaScreenView.h */,
A6C938771E9F566C0039B6DA /* TaScreenView.m */,
A6C938781E9F566C0039B6DA /* TaSimpleWebViewController.h */,
A6C938791E9F566C0039B6DA /* TaSimpleWebViewController.m */,
A6C9387A1E9F566C0039B6DA /* TaStreamerView.h */,
A6C9387B1E9F566C0039B6DA /* TaStreamerView.m */,
A6C9387C1E9F566C0039B6DA /* TaTmHelper.h */,
A6C9387D1E9F566C0039B6DA /* TaTmHelper.m */,
A6C9387E1E9F566C0039B6DA /* TaUtils.h */,
A6C9387F1E9F566C0039B6DA /* TaUtils.m */,
A6C938801E9F566C0039B6DA /* TuiaAd.bundle */,
A6C938881E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.h */,
A6C938891E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.m */,
A6C9388A1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.h */,
A6C9388B1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.m */,
A6C9388C1E9F566C0039B6DA /* YLGIFImage */,
);
path = AdIOSSDK;
sourceTree = "<group>";
};
A6C9383A1E9F566B0039B6DA /* duiba_FMDeviceManager_v2.1.5_515b4f1 */ = {
isa = PBXGroup;
children = (
A6C9383B1E9F566B0039B6DA /* duiba_FMDeviceManager.h */,
A6C9383C1E9F566B0039B6DA /* libduibaFMDeviceManager_without_IDFA.a */,
);
path = duiba_FMDeviceManager_v2.1.5_515b4f1;
sourceTree = "<group>";
};
A6C9384B1E9F566B0039B6DA /* PPNetworking */ = {
isa = PBXGroup;
children = (
A6C9384C1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.h */,
A6C9384D1E9F566B0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.m */,
A6C9384E1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.h */,
A6C9384F1E9F566B0039B6DA /* HAIJIANPPAFImageDownloader.m */,
A6C938501E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.h */,
A6C938511E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperation.m */,
A6C938521E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.h */,
A6C938531E9F566B0039B6DA /* HAIJIANPPHTTPRequestOperationManager.m */,
A6C938541E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.h */,
A6C938551E9F566B0039B6DA /* HAIJIANPPHTTPSessionManager.m */,
A6C938561E9F566B0039B6DA /* HAIJIANPPNetworking.h */,
A6C938571E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.h */,
A6C938581E9F566B0039B6DA /* HAIJIANPPNetworkReachabilityManager.m */,
A6C938591E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.h */,
A6C9385A1E9F566B0039B6DA /* HAIJIANPPSecurityPolicy.m */,
A6C9385B1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.h */,
A6C9385C1E9F566B0039B6DA /* HAIJIANPPURLConnectionOperation.m */,
A6C9385D1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.h */,
A6C9385E1E9F566B0039B6DA /* HAIJIANPPURLRequestSerialization.m */,
A6C9385F1E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.h */,
A6C938601E9F566B0039B6DA /* HAIJIANPPURLResponseSerialization.m */,
A6C938611E9F566B0039B6DA /* HAIJIANPPURLSessionManager.h */,
A6C938621E9F566B0039B6DA /* HAIJIANPPURLSessionManager.m */,
A6C938631E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.h */,
A6C938641E9F566B0039B6DA /* UIImageView+HAIJIANPPAFNetworking.m */,
);
path = PPNetworking;
sourceTree = "<group>";
};
A6C938651E9F566B0039B6DA /* Reachability */ = {
isa = PBXGroup;
children = (
A6C938681E9F566B0039B6DA /* UIImage+dzanimatedGIF.h */,
A6C938691E9F566B0039B6DA /* UIImage+dzanimatedGIF.m */,
);
path = Reachability;
sourceTree = "<group>";
};
A6C9388C1E9F566C0039B6DA /* YLGIFImage */ = {
isa = PBXGroup;
children = (
A6C9388D1E9F566C0039B6DA /* DZYLGIFImage.h */,
A6C9388E1E9F566C0039B6DA /* DZYLGIFImage.m */,
A6C9388F1E9F566C0039B6DA /* DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h */,
A6C938901E9F566C0039B6DA /* DZYLImageView.h */,
A6C938911E9F566C0039B6DA /* DZYLImageView.m */,
);
path = YLGIFImage;
sourceTree = "<group>";
};
A6C938931E9F566C0039B6DA /* TaTm */ = {
isa = PBXGroup;
children = (
A6C938941E9F566C0039B6DA /* Info.plist */,
A6C938951E9F566C0039B6DA /* TaTm.h */,
A6C938961E9F566C0039B6DA /* TaTm.m */,
);
path = TaTm;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
A675B67A1E5DD80300CE9377 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
A6C938E01E9F566C0039B6DA /* DZYLGIFImage.h in Headers */,
A6C938CD1E9F566C0039B6DA /* TaScreenView.h in Headers */,
A6C938C11E9F566C0039B6DA /* TaAppWallView.h in Headers */,
A6C938C71E9F566C0039B6DA /* TaDriftView.h in Headers */,
A6C938D51E9F566C0039B6DA /* TaUtils.h in Headers */,
A6C938CB1E9F566C0039B6DA /* TaLaunchScreenView.h in Headers */,
A6C938CF1E9F566C0039B6DA /* TaSimpleWebViewController.h in Headers */,
A6C938E71E9F566C0039B6DA /* TaTm.h in Headers */,
A6C938D11E9F566C0039B6DA /* TaStreamerView.h in Headers */,
A6C938C51E9F566C0039B6DA /* TaBaseActivityView.h in Headers */,
A6C938D31E9F566C0039B6DA /* TaTmHelper.h in Headers */,
A6C938C31E9F566C0039B6DA /* TaBnView.h in Headers */,
A6C938C91E9F566C0039B6DA /* TaInfoStreamerView.h in Headers */,
A6C938E31E9F566C0039B6DA /* DZYLImageView.h in Headers */,
A6C938DE1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.h in Headers */,
A6C938A61E9F566C0039B6DA /* HAIJIANPPAFImageDownloader.h in Headers */,
A6C938DC1E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.h in Headers */,
A6C938A41E9F566C0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.h in Headers */,
A6C938B71E9F566C0039B6DA /* HAIJIANPPURLResponseSerialization.h in Headers */,
A6C938BB1E9F566C0039B6DA /* UIImageView+HAIJIANPPAFNetworking.h in Headers */,
A6C938B91E9F566C0039B6DA /* HAIJIANPPURLSessionManager.h in Headers */,
A6C938B51E9F566C0039B6DA /* HAIJIANPPURLRequestSerialization.h in Headers */,
A6C938BF1E9F566C0039B6DA /* UIImage+dzanimatedGIF.h in Headers */,
A6C938AE1E9F566C0039B6DA /* HAIJIANPPNetworking.h in Headers */,
A6C938E21E9F566C0039B6DA /* DZYLGIFImageInSwiftProjectDemo-Bridging-Header.h in Headers */,
A6C938971E9F566C0039B6DA /* duiba_FMDeviceManager.h in Headers */,
A6C938A81E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperation.h in Headers */,
A6C938AA1E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperationManager.h in Headers */,
A6C938AF1E9F566C0039B6DA /* HAIJIANPPNetworkReachabilityManager.h in Headers */,
A6C938B31E9F566C0039B6DA /* HAIJIANPPURLConnectionOperation.h in Headers */,
A6C938AC1E9F566C0039B6DA /* HAIJIANPPHTTPSessionManager.h in Headers */,
A6C938B11E9F566C0039B6DA /* HAIJIANPPSecurityPolicy.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
A675B67C1E5DD80300CE9377 /* TaTmSDK */ = {
isa = PBXNativeTarget;
buildConfigurationList = A675B6911E5DD80300CE9377 /* Build configuration list for PBXNativeTarget "TaTmSDK" */;
buildPhases = (
A675B6781E5DD80300CE9377 /* Sources */,
A675B6791E5DD80300CE9377 /* Frameworks */,
A675B67A1E5DD80300CE9377 /* Headers */,
A675B67B1E5DD80300CE9377 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = TaTmSDK;
productName = TuiaADSDK;
productReference = A675B67D1E5DD80300CE9377 /* TaTmSDK.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A675B6741E5DD80300CE9377 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0820;
ORGANIZATIONNAME = dozening;
TargetAttributes = {
A675B67C1E5DD80300CE9377 = {
CreatedOnToolsVersion = 8.2.1;
DevelopmentTeam = T2AT9FLRBB;
ProvisioningStyle = Automatic;
};
A6DDD7041F384D8300B66159 = {
CreatedOnToolsVersion = 8.3.3;
DevelopmentTeam = VM5LLSM496;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = A675B6771E5DD80300CE9377 /* Build configuration list for PBXProject "TaTmSDK" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A675B6731E5DD80300CE9377;
productRefGroup = A675B67E1E5DD80300CE9377 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A675B67C1E5DD80300CE9377 /* TaTmSDK */,
A6DDD7041F384D8300B66159 /* TaTmSDKG */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
A675B67B1E5DD80300CE9377 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A6C938D71E9F566C0039B6DA /* TuiaAd.bundle in Resources */,
A6C938E61E9F566C0039B6DA /* Info.plist in Resources */,
A6C938E51E9F566C0039B6DA /* Info.plist in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
A6DDD70A1F384DBE00B66159 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "#!/bin/sh\n#要build的target名\nTARGET_NAME=${PROJECT_NAME}\nif [[ $1 ]]\nthen\nTARGET_NAME=$1\nfi\nUNIVERSAL_OUTPUT_FOLDER=\"${SRCROOT}/${PROJECT_NAME}/SDK/\"\n\n#创建输出目录,并删除之前的framework文件\nmkdir -p \"${UNIVERSAL_OUTPUT_FOLDER}\"\nrm -rf \"${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework\"\n\n#分别编译模拟器和真机的Framework\nxcodebuild -target \"${TARGET_NAME}\" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphoneos BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" clean build\nxcodebuild -target \"${TARGET_NAME}\" ONLY_ACTIVE_ARCH=NO -configuration ${CONFIGURATION} -sdk iphonesimulator BUILD_DIR=\"${BUILD_DIR}\" BUILD_ROOT=\"${BUILD_ROOT}\" clean build\n\n#拷贝framework到univer目录\ncp -R \"${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}.framework\" \"${UNIVERSAL_OUTPUT_FOLDER}\"\n\n#合并framework,输出最终的framework到build目录\nlipo -create -output \"${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework/${TARGET_NAME}\" \"${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/${TARGET_NAME}.framework/${TARGET_NAME}\" \"${BUILD_DIR}/${CONFIGURATION}-iphoneos/${TARGET_NAME}.framework/${TARGET_NAME}\"\n\n#删除编译之后生成的无关的配置文件\ndir_path=\"${UNIVERSAL_OUTPUT_FOLDER}/${TARGET_NAME}.framework/\"\nfor file in ls $dir_path\ndo\nif [[ ${file} =~ \".xcconfig\" ]]\nthen\nrm -f \"${dir_path}/${file}\"\nfi\ndone\n#判断build文件夹是否存在,存在则删除\nif [ -d \"${SRCROOT}/build\" ]\nthen\nrm -rf \"${SRCROOT}/build\"\nfi\nrm -rf \"${BUILD_DIR}/${CONFIGURATION}-iphonesimulator\" \"${BUILD_DIR}/${CONFIGURATION}-iphoneos\"\ncd \"${UNIVERSAL_OUTPUT_FOLDER}\"\nzip -r TaTmSDK.zip *\n#打开合并后的文件夹\nopen \"${UNIVERSAL_OUTPUT_FOLDER}\"\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
A675B6781E5DD80300CE9377 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A6C938DF1E9F566C0039B6DA /* UIViewController+DZBackButtonHandler.m in Sources */,
A6C938AB1E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperationManager.m in Sources */,
A6C938C01E9F566C0039B6DA /* UIImage+dzanimatedGIF.m in Sources */,
A6C938CA1E9F566C0039B6DA /* TaInfoStreamerView.m in Sources */,
A6C938C21E9F566C0039B6DA /* TaAppWallView.m in Sources */,
A6C938AD1E9F566C0039B6DA /* HAIJIANPPHTTPSessionManager.m in Sources */,
A6C938CE1E9F566C0039B6DA /* TaScreenView.m in Sources */,
A6C938A51E9F566C0039B6DA /* HAIJIANPPAFAutoPurgingImageCache.m in Sources */,
A6C938B01E9F566C0039B6DA /* HAIJIANPPNetworkReachabilityManager.m in Sources */,
A6C938B41E9F566C0039B6DA /* HAIJIANPPURLConnectionOperation.m in Sources */,
A6C938E11E9F566C0039B6DA /* DZYLGIFImage.m in Sources */,
A6C938B61E9F566C0039B6DA /* HAIJIANPPURLRequestSerialization.m in Sources */,
A6C938D01E9F566C0039B6DA /* TaSimpleWebViewController.m in Sources */,
A6C938BC1E9F566C0039B6DA /* UIImageView+HAIJIANPPAFNetworking.m in Sources */,
A6C938BA1E9F566C0039B6DA /* HAIJIANPPURLSessionManager.m in Sources */,
A6C938DD1E9F566C0039B6DA /* UIDevice+VKKeychainIDFV.m in Sources */,
A6C938C61E9F566C0039B6DA /* TaBaseActivityView.m in Sources */,
A6C938C41E9F566C0039B6DA /* TaBnView.m in Sources */,
A6C938C81E9F566C0039B6DA /* TaDriftView.m in Sources */,
A6C938B21E9F566C0039B6DA /* HAIJIANPPSecurityPolicy.m in Sources */,
A6C938E41E9F566C0039B6DA /* DZYLImageView.m in Sources */,
A6C938B81E9F566C0039B6DA /* HAIJIANPPURLResponseSerialization.m in Sources */,
A6C938D61E9F566C0039B6DA /* TaUtils.m in Sources */,
A6C938A71E9F566C0039B6DA /* HAIJIANPPAFImageDownloader.m in Sources */,
A6C938CC1E9F566C0039B6DA /* TaLaunchScreenView.m in Sources */,
A6C938D41E9F566C0039B6DA /* TaTmHelper.m in Sources */,
A6C938A91E9F566C0039B6DA /* HAIJIANPPHTTPRequestOperation.m in Sources */,
A6C938E81E9F566C0039B6DA /* TaTm.m in Sources */,
A6C938D21E9F566C0039B6DA /* TaStreamerView.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
A6DDD7091F384DB800B66159 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A675B67C1E5DD80300CE9377 /* TaTmSDK */;
targetProxy = A6DDD7081F384DB800B66159 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
A675B68F1E5DD80300CE9377 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
A675B6901E5DD80300CE9377 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
A675B6921E5DD80300CE9377 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = (
"$(ARCHS_STANDARD)",
armv7,
);
CODE_SIGN_IDENTITY = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEAD_CODE_STRIPPING = NO;
DEFINES_MODULE = NO;
DEVELOPMENT_TEAM = T2AT9FLRBB;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = TaTmSDK/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/TuiaADSDK/AdIOSSDK/duiba_FMDeviceManager_v2.1.5_515b4f1",
"$(PROJECT_DIR)/TaTmSDK/AdIOSSDK/duiba_FMDeviceManager_v2.1.5_515b4f1",
);
LINK_WITH_STANDARD_LIBRARIES = NO;
MACH_O_TYPE = staticlib;
ONLY_ACTIVE_ARCH = NO;
PRODUCT_BUNDLE_IDENTIFIER = dozening.TuiaADSDK;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
};
name = Debug;
};
A675B6931E5DD80300CE9377 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = (
"$(ARCHS_STANDARD)",
armv7,
);
CODE_SIGN_IDENTITY = "";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEAD_CODE_STRIPPING = NO;
DEFINES_MODULE = NO;
DEVELOPMENT_TEAM = T2AT9FLRBB;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
INFOPLIST_FILE = TaTmSDK/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/TuiaADSDK/AdIOSSDK/duiba_FMDeviceManager_v2.1.5_515b4f1",
"$(PROJECT_DIR)/TaTmSDK/AdIOSSDK/duiba_FMDeviceManager_v2.1.5_515b4f1",
);
LINK_WITH_STANDARD_LIBRARIES = NO;
MACH_O_TYPE = staticlib;
ONLY_ACTIVE_ARCH = NO;
PRODUCT_BUNDLE_IDENTIFIER = dozening.TuiaADSDK;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
};
name = Release;
};
A6DDD7051F384D8300B66159 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEVELOPMENT_TEAM = VM5LLSM496;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
A6DDD7061F384D8300B66159 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEVELOPMENT_TEAM = VM5LLSM496;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A675B6771E5DD80300CE9377 /* Build configuration list for PBXProject "TaTmSDK" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A675B68F1E5DD80300CE9377 /* Debug */,
A675B6901E5DD80300CE9377 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A675B6911E5DD80300CE9377 /* Build configuration list for PBXNativeTarget "TaTmSDK" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A675B6921E5DD80300CE9377 /* Debug */,
A675B6931E5DD80300CE9377 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A6DDD7071F384D8300B66159 /* Build configuration list for PBXAggregateTarget "TaTmSDKG" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A6DDD7051F384D8300B66159 /* Debug */,
A6DDD7061F384D8300B66159 /* Release */,
);
defaultConfigurationIsVisible = 0;
};
/* End XCConfigurationList section */
};
rootObject = A675B6741E5DD80300CE9377 /* Project object */;
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:/Users/Shared/Jenkins/Home/Desktop/&#x63a8;&#x554a;/TuiaADSDK2.0&#x6e90;&#x7801;/TuiaADSDK/TaTmSDK.xcodeproj">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "TuiaADSDK/AdIOSSDK/TuiaAdHelper.m"
timestampString = "509532183.339029"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "551"
endingLineNumber = "551"
landmarkName = "-spmActivitiyWithParameters:successBlock:failedBlock:"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "TuiaADSDK/AdIOSSDK/TuiaAdHelper.m"
timestampString = "509532185.700673"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "557"
endingLineNumber = "557"
landmarkName = "-spmActivitiyWithParameters:successBlock:failedBlock:"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "TaTmSDK/AdIOSSDK/TaTmHelper.m"
timestampString = "522240565.551657"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "548"
endingLineNumber = "548"
landmarkName = "-spmActivitiyWithParameters:successBlock:failedBlock:"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0830"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A6DDD7041F384D8300B66159"
BuildableName = "TaTmSDKG"
BlueprintName = "TaTmSDKG"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A6DDD7041F384D8300B66159"
BuildableName = "TaTmSDKG"
BlueprintName = "TaTmSDKG"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A6DDD7041F384D8300B66159"
BuildableName = "TaTmSDKG"
BlueprintName = "TaTmSDKG"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0820"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A675B67C1E5DD80300CE9377"
BuildableName = "TaTmSDK.framework"
BlueprintName = "TaTmSDK"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A675B6851E5DD80300CE9377"
BuildableName = "TuiaADSDKTests.xctest"
BlueprintName = "TuiaADSDKTests"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A675B67C1E5DD80300CE9377"
BuildableName = "TaTmSDK.framework"
BlueprintName = "TaTmSDK"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A675B67C1E5DD80300CE9377"
BuildableName = "TaTmSDK.framework"
BlueprintName = "TaTmSDK"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A675B67C1E5DD80300CE9377"
BuildableName = "TaTmSDK.framework"
BlueprintName = "TaTmSDK"
ReferencedContainer = "container:TaTmSDK.xcodeproj">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>TaTmSDKG.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
</dict>
<key>TuiaADSDK.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>A675B67C1E5DD80300CE9377</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>A675B6851E5DD80300CE9377</key>
<dict>
<key>primary</key>
<true/>
</dict>
<key>A6DDD7041F384D8300B66159</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
// AFAutoPurgingImageCache.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#import <Foundation/Foundation.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
*/
@protocol HAIJIANPPAFImageCache <NSObject>
/**
Adds the image to the cache with the given identifier.
@param image The image to cache.
@param identifier The unique identifier for the image in the cache.
*/
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
/**
Removes the image from the cache matching the given identifier.
@param identifier The unique identifier for the image in the cache.
@return A BOOL indicating whether or not the image was removed from the cache.
*/
- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
/**
Removes all images from the cache.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeAllImages;
/**
Returns the image in the cache associated with the given identifier.
@param identifier The unique identifier for the image in the cache.
@return An image for the matching identifier, or nil.
*/
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
@end
/**
The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
*/
@protocol HAIJIANPPAFImageRequestCache <HAIJIANPPAFImageCache>
/**
Adds the image to the cache using an identifier created from the request and additional identifier.
@param image The image to cache.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
*/
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Removes the image from the cache using an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Returns the image from the cache associated with an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return An image for the matching request and identifier, or nil.
*/
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
@end
/**
The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
*/
@interface HAIJIANPPAFAutoPurgingImageCache : NSObject <HAIJIANPPAFImageRequestCache>
/**
The total memory capacity of the cache in bytes.
*/
@property (nonatomic, assign) UInt64 memoryCapacity;
/**
The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
*/
@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
/**
The current total memory usage in bytes of all images stored within the cache.
*/
@property (nonatomic, assign, readonly) UInt64 memoryUsage;
/**
Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)init;
/**
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
after purge limit.
@param memoryCapacity The total memory capacity of the cache in bytes.
@param preferredMemoryUsageAfterPurge The preferred memory usage after purge in bytes.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
@end
NS_ASSUME_NONNULL_END
#endif
// AFAutoPurgingImageCache.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "HAIJIANPPAFAutoPurgingImageCache.h"
@interface HAIJIANPPAFCachedImage : NSObject
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, assign) UInt64 totalBytes;
@property (nonatomic, strong) NSDate *lastAccessDate;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@end
@implementation HAIJIANPPAFCachedImage
-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
if (self = [self init]) {
self.image = image;
self.identifier = identifier;
CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
CGFloat bytesPerPixel = 4.0;
CGFloat bytesPerRow = imageSize.width * bytesPerPixel;
self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerRow;
self.lastAccessDate = [NSDate date];
}
return self;
}
- (UIImage*)accessImage {
self.lastAccessDate = [NSDate date];
return self.image;
}
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
return descriptionString;
}
@end
@interface HAIJIANPPAFAutoPurgingImageCache ()
@property (nonatomic, strong) NSMutableDictionary <NSString* , HAIJIANPPAFCachedImage*> *cachedImages;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@end
@implementation HAIJIANPPAFAutoPurgingImageCache
- (instancetype)init {
return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
}
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
if (self = [super init]) {
self.memoryCapacity = memoryCapacity;
self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
self.cachedImages = [[NSMutableDictionary alloc] init];
NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(removeAllImages)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UInt64)memoryUsage {
__block UInt64 result = 0;
dispatch_sync(self.synchronizationQueue, ^{
result = self.currentMemoryUsage;
});
return result;
}
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
dispatch_barrier_async(self.synchronizationQueue, ^{
HAIJIANPPAFCachedImage *cacheImage = [[HAIJIANPPAFCachedImage alloc] initWithImage:image identifier:identifier];
HAIJIANPPAFCachedImage *previousCachedImage = self.cachedImages[identifier];
if (previousCachedImage != nil) {
self.currentMemoryUsage -= previousCachedImage.totalBytes;
}
self.cachedImages[identifier] = cacheImage;
self.currentMemoryUsage += cacheImage.totalBytes;
});
dispatch_barrier_async(self.synchronizationQueue, ^{
if (self.currentMemoryUsage > self.memoryCapacity) {
UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
NSMutableArray <HAIJIANPPAFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
ascending:YES];
[sortedImages sortUsingDescriptors:@[sortDescriptor]];
UInt64 bytesPurged = 0;
for (HAIJIANPPAFCachedImage *cachedImage in sortedImages) {
[self.cachedImages removeObjectForKey:cachedImage.identifier];
bytesPurged += cachedImage.totalBytes;
if (bytesPurged >= bytesToPurge) {
break ;
}
}
self.currentMemoryUsage -= bytesPurged;
}
});
}
- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
HAIJIANPPAFCachedImage *cachedImage = self.cachedImages[identifier];
if (cachedImage != nil) {
[self.cachedImages removeObjectForKey:identifier];
self.currentMemoryUsage -= cachedImage.totalBytes;
removed = YES;
}
});
return removed;
}
- (BOOL)removeAllImages {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
if (self.cachedImages.count > 0) {
[self.cachedImages removeAllObjects];
self.currentMemoryUsage = 0;
removed = YES;
}
});
return removed;
}
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
__block UIImage *image = nil;
dispatch_sync(self.synchronizationQueue, ^{
HAIJIANPPAFCachedImage *cachedImage = self.cachedImages[identifier];
image = [cachedImage accessImage];
});
return image;
}
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
[self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
NSString *key = request.URL.absoluteString;
if (additionalIdentifier != nil) {
key = [key stringByAppendingString:additionalIdentifier];
}
return key;
}
@end
#endif
// AFImageDownloader.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <Foundation/Foundation.h>
#import "HAIJIANPPAFAutoPurgingImageCache.h"
#import "HAIJIANPPHTTPSessionManager.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, HAIJIANPPAFImageDownloadPrioritization) {
HAIJIANPPAFImageDownloadPrioritizationFIFO,
HAIJIANPPAFImageDownloadPrioritizationLIFO
};
/**
The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
*/
@interface HAIJIANPPAFImageDownloadReceipt : NSObject
/**
The data task created by the `AFImageDownloader`.
*/
@property (nonatomic, strong) NSURLSessionDataTask *task;
/**
The unique identifier for the success and failure blocks when duplicate requests are made.
*/
@property (nonatomic, strong) NSUUID *receiptID;
@end
/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
*/
@interface HAIJIANPPAFImageDownloader : NSObject
/**
The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
*/
@property (nonatomic, strong, nullable) id <HAIJIANPPAFImageRequestCache> imageCache;
/**
The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
*/
@property (nonatomic, strong) HAIJIANPPHTTPSessionManager *sessionManager;
/**
Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
*/
@property (nonatomic, assign) HAIJIANPPAFImageDownloadPrioritization downloadPrioritizaton;
/**
The shared default instance of `AFImageDownloader` initialized with default values.
*/
+ (instancetype)defaultInstance;
/**
Creates a default `NSURLCache` with common usage parameter values.
@returns The default `NSURLCache` instance.
*/
+ (NSURLCache *)defaultURLCache;
/**
Default initializer
@return An instance of `AFImageDownloader` initialized with default values.
*/
- (instancetype)init;
/**
Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
@param sessionManager The session manager to use to download images.
@param downloadPrioritization The download prioritization of the download queue.
@param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
@param imageCache The image cache used to store all downloaded images in.
@return The new `AFImageDownloader` instance.
*/
- (instancetype)initWithSessionManager:(HAIJIANPPHTTPSessionManager *)sessionManager
downloadPrioritization:(HAIJIANPPAFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(nullable id <HAIJIANPPAFImageRequestCache>)imageCache;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable HAIJIANPPAFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param request The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable HAIJIANPPAFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
@param imageDownloadReceipt The image download receipt to cancel.
*/
- (void)cancelTaskForImageDownloadReceipt:(HAIJIANPPAFImageDownloadReceipt *)imageDownloadReceipt;
@end
#endif
NS_ASSUME_NONNULL_END
// AFImageDownloader.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "HAIJIANPPAFImageDownloader.h"
#import "HAIJIANPPHTTPSessionManager.h"
@interface HAIJIANPPAFImageDownloaderResponseHandler : NSObject
@property (nonatomic, strong) NSUUID *uuid;
@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*);
@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*);
@end
@implementation HAIJIANPPAFImageDownloaderResponseHandler
- (instancetype)initWithUUID:(NSUUID *)uuid
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
if (self = [self init]) {
self.uuid = uuid;
self.successBlock = success;
self.failureBlock = failure;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
}
@end
@interface HAIJIANPPAFImageDownloaderMergedTask : NSObject
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) NSURLSessionDataTask *task;
@property (nonatomic, strong) NSMutableArray <HAIJIANPPAFImageDownloaderResponseHandler*> *responseHandlers;
@end
@implementation HAIJIANPPAFImageDownloaderMergedTask
- (instancetype)initWithIdentifier:(NSString *)identifier task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.identifier = identifier;
self.task = task;
self.responseHandlers = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addResponseHandler:(HAIJIANPPAFImageDownloaderResponseHandler*)handler {
[self.responseHandlers addObject:handler];
}
- (void)removeResponseHandler:(HAIJIANPPAFImageDownloaderResponseHandler*)handler {
[self.responseHandlers removeObject:handler];
}
@end
@implementation HAIJIANPPAFImageDownloadReceipt
- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.receiptID = receiptID;
self.task = task;
}
return self;
}
@end
@interface HAIJIANPPAFImageDownloader ()
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@property (nonatomic, strong) dispatch_queue_t responseQueue;
@property (nonatomic, assign) NSInteger maximumActiveDownloads;
@property (nonatomic, assign) NSInteger activeRequestCount;
@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
@end
@implementation HAIJIANPPAFImageDownloader
+ (NSURLCache *)defaultURLCache {
return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
diskCapacity:150 * 1024 * 1024
diskPath:@"com.alamofire.imagedownloader"];
}
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//TODO set the default HTTP headers
configuration.HTTPShouldSetCookies = YES;
configuration.HTTPShouldUsePipelining = NO;
configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
configuration.allowsCellularAccess = YES;
configuration.timeoutIntervalForRequest = 60.0;
configuration.URLCache = [HAIJIANPPAFImageDownloader defaultURLCache];
return configuration;
}
- (instancetype)init {
NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
HAIJIANPPHTTPSessionManager *sessionManager = [[HAIJIANPPHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration];
sessionManager.responseSerializer = [HAIJIANPPImageResponseSerializer serializer];
return [self initWithSessionManager:sessionManager
downloadPrioritization:HAIJIANPPAFImageDownloadPrioritizationFIFO
maximumActiveDownloads:4
imageCache:[[HAIJIANPPAFAutoPurgingImageCache alloc] init]];
}
- (instancetype)initWithSessionManager:(HAIJIANPPHTTPSessionManager *)sessionManager
downloadPrioritization:(HAIJIANPPAFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(id <HAIJIANPPAFImageRequestCache>)imageCache {
if (self = [super init]) {
self.sessionManager = sessionManager;
self.downloadPrioritizaton = downloadPrioritization;
self.maximumActiveDownloads = maximumActiveDownloads;
self.imageCache = imageCache;
self.queuedMergedTasks = [[NSMutableArray alloc] init];
self.mergedTasks = [[NSMutableDictionary alloc] init];
self.activeRequestCount = 0;
NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
+ (instancetype)defaultInstance {
static HAIJIANPPAFImageDownloader *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (nullable HAIJIANPPAFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
}
- (nullable HAIJIANPPAFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(nonnull NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
__block NSURLSessionDataTask *task = nil;
dispatch_sync(self.synchronizationQueue, ^{
NSString *identifier = request.URL.absoluteString;
// 1) Append the success and failure blocks to a pre-existing request if it already exists
HAIJIANPPAFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[identifier];
if (existingMergedTask != nil) {
HAIJIANPPAFImageDownloaderResponseHandler *handler = [[HAIJIANPPAFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
[existingMergedTask addResponseHandler:handler];
task = existingMergedTask.task;
return;
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch (request.cachePolicy) {
case NSURLRequestUseProtocolCachePolicy:
case NSURLRequestReturnCacheDataElseLoad:
case NSURLRequestReturnCacheDataDontLoad: {
UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
if (cachedImage != nil) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
success(request, nil, cachedImage);
});
}
return;
}
break;
}
default:
break;
}
// 3) Create the request and set up authentication, validation and response serialization
NSURLSessionDataTask *createdTask;
__weak __typeof__(self) weakSelf = self;
createdTask = [self.sessionManager
dataTaskWithRequest:request
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
dispatch_async(self.responseQueue, ^{
__strong __typeof__(weakSelf) strongSelf = weakSelf;
HAIJIANPPAFImageDownloaderMergedTask *mergedTask = [strongSelf safelyRemoveMergedTaskWithIdentifier:identifier];
if (error) {
for (HAIJIANPPAFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
});
}
}
} else {
[strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
for (HAIJIANPPAFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.successBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
});
}
}
}
[strongSelf safelyDecrementActiveTaskCount];
[strongSelf safelyStartNextTaskIfNecessary];
});
}];
// 4) Store the response handler for use when the request completes
HAIJIANPPAFImageDownloaderResponseHandler *handler = [[HAIJIANPPAFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
success:success
failure:failure];
HAIJIANPPAFImageDownloaderMergedTask *mergedTask = [[HAIJIANPPAFImageDownloaderMergedTask alloc]
initWithIdentifier:identifier
task:createdTask];
[mergedTask addResponseHandler:handler];
self.mergedTasks[identifier] = mergedTask;
// 5) Either start the request or enqueue it depending on the current active request count
if ([self isActiveRequestCountBelowMaximumLimit]) {
[self startMergedTask:mergedTask];
} else {
[self enqueueMergedTask:mergedTask];
}
task = mergedTask.task;
});
if (task) {
return [[HAIJIANPPAFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
} else {
return nil;
}
}
- (void)cancelTaskForImageDownloadReceipt:(HAIJIANPPAFImageDownloadReceipt *)imageDownloadReceipt {
dispatch_sync(self.synchronizationQueue, ^{
NSString *identifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
HAIJIANPPAFImageDownloaderMergedTask *mergedTask = self.mergedTasks[identifier];
NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(HAIJIANPPAFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
return handler.uuid == imageDownloadReceipt.receiptID;
}];
if (index != NSNotFound) {
HAIJIANPPAFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
[mergedTask removeResponseHandler:handler];
NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
});
}
}
if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[mergedTask.task cancel];
}
});
}
- (HAIJIANPPAFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithIdentifier:(NSString *)identifier {
__block HAIJIANPPAFImageDownloaderMergedTask *mergedTask = nil;
dispatch_sync(self.synchronizationQueue, ^{
mergedTask = self.mergedTasks[identifier];
[self.mergedTasks removeObjectForKey:identifier];
});
return mergedTask;
}
- (void)safelyDecrementActiveTaskCount {
dispatch_sync(self.synchronizationQueue, ^{
if (self.activeRequestCount > 0) {
self.activeRequestCount -= 1;
}
});
}
- (void)safelyStartNextTaskIfNecessary {
dispatch_sync(self.synchronizationQueue, ^{
if ([self isActiveRequestCountBelowMaximumLimit]) {
while (self.queuedMergedTasks.count > 0) {
HAIJIANPPAFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[self startMergedTask:mergedTask];
break;
}
}
}
});
}
- (void)startMergedTask:(HAIJIANPPAFImageDownloaderMergedTask *)mergedTask {
[mergedTask.task resume];
++self.activeRequestCount;
}
- (void)enqueueMergedTask:(HAIJIANPPAFImageDownloaderMergedTask *)mergedTask {
switch (self.downloadPrioritizaton) {
case HAIJIANPPAFImageDownloadPrioritizationFIFO:
[self.queuedMergedTasks addObject:mergedTask];
break;
case HAIJIANPPAFImageDownloadPrioritizationLIFO:
[self.queuedMergedTasks insertObject:mergedTask atIndex:0];
break;
}
}
- (HAIJIANPPAFImageDownloaderMergedTask *)dequeueMergedTask {
HAIJIANPPAFImageDownloaderMergedTask *mergedTask = nil;
mergedTask = [self.queuedMergedTasks firstObject];
[self.queuedMergedTasks removeObject:mergedTask];
return mergedTask;
}
- (BOOL)isActiveRequestCountBelowMaximumLimit {
return self.activeRequestCount < self.maximumActiveDownloads;
}
@end
#endif
// HAIJIANPPHTTPRequestOperation.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "HAIJIANPPURLConnectionOperation.h"
/**
`HAIJIANPPHTTPRequestOperation` is a subclass of `HAIJIANPPURLConnectionOperation` 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.
*/
@interface HAIJIANPPHTTPRequestOperation : HAIJIANPPURLConnectionOperation
///------------------------------------------------
/// @name Getting HTTP URL Connection Information
///------------------------------------------------
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an HAIJIANPPHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
@warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value
*/
@property (nonatomic, strong) HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> * responseSerializer;
/**
An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error.
*/
@property (readonly, nonatomic, strong) id responseObject;
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
///-----------------------------------------------------------
/**
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.
This method should be overridden in subclasses in order to specify the response object passed into the success block.
@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.
@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.
*/
- (void)setCompletionBlockWithSuccess:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
@end
// HAIJIANPPHTTPRequestOperation.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPHTTPRequestOperation.h"
static dispatch_queue_t http_request_operation_processing_queue() {
static dispatch_queue_t af_http_request_operation_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_http_request_operation_processing_queue;
}
static dispatch_group_t http_request_operation_completion_group() {
static dispatch_group_t af_http_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_http_request_operation_completion_group = dispatch_group_create();
});
return af_http_request_operation_completion_group;
}
#pragma mark -
@interface HAIJIANPPURLConnectionOperation ()
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@end
@interface HAIJIANPPHTTPRequestOperation ()
@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
@property (readwrite, nonatomic, strong) id responseObject;
@property (readwrite, nonatomic, strong) NSError *responseSerializationError;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@end
@implementation HAIJIANPPHTTPRequestOperation
@dynamic response;
@dynamic lock;
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.responseSerializer = [HAIJIANPPHTTPResponseSerializer serializer];
return self;
}
- (void)setResponseSerializer:(HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[self.lock lock];
_responseSerializer = responseSerializer;
self.responseObject = nil;
self.responseSerializationError = nil;
[self.lock unlock];
}
- (id)responseObject {
[self.lock lock];
if (!_responseObject && [self isFinished] && !self.error) {
NSError *error = nil;
self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error];
if (error) {
self.responseSerializationError = error;
}
}
[self.lock unlock];
return _responseObject;
}
- (NSError *)error {
if (_responseSerializationError) {
return _responseSerializationError;
} else {
return [super error];
}
}
#pragma mark - HAIJIANPPHTTPRequestOperation
- (void)setCompletionBlockWithSuccess:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
// completionBlock is manually nilled out in HAIJIANPPURLConnectionOperation to break the retain cycle.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^{
if (self.completionGroup) {
dispatch_group_enter(self.completionGroup);
}
dispatch_async(http_request_operation_processing_queue(), ^{
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
id responseObject = self.responseObject;
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
success(self, responseObject);
});
}
}
}
if (self.completionGroup) {
dispatch_group_leave(self.completionGroup);
}
});
};
#pragma clang diagnostic pop
}
#pragma mark - HAIJIANPPURLRequestOperation
- (void)pause {
[super pause];
u_int64_t offset = 0;
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
} else {
offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
self.request = mutableURLRequest;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.responseSerializer = [decoder decodeObjectOfClass:[HAIJIANPPHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPRequestOperation *operation = [super copyWithZone:zone];
operation.responseSerializer = [self.responseSerializer copyWithZone:zone];
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
@end
// HAIJIANPPHTTPRequestOperationManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import "HAIJIANPPHTTPRequestOperation.h"
#import "HAIJIANPPURLResponseSerialization.h"
#import "HAIJIANPPURLRequestSerialization.h"
#import "HAIJIANPPSecurityPolicy.h"
#import "HAIJIANPPNetworkReachabilityManager.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`HAIJIANPPHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
## Subclassing Notes
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `HAIJIANPPHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `HAIJIANPPHTTPRequestOperationManager` may be used to similar effect.
## Methods to Override
To change the behavior of all request operation construction for an `HAIJIANPPHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
## Serialization
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<HAIJIANPPURLRequestSerialization>`.
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<HAIJIANPPURLResponseSerialization>`
## URL Construction Using Relative Paths
For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
## Network Reachability Monitoring
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `HAIJIANPPNetworkReachabilityManager` for more details.
## NSSecureCoding & NSCopying Caveats
`HAIJIANPPHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
- NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
*/
@interface HAIJIANPPHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying>
/**
The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
/**
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `HAIJIANPPHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
@warning `requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) HAIJIANPPHTTPRequestSerializer <HAIJIANPPURLRequestSerialization> * requestSerializer;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> * responseSerializer;
/**
The operation queue on which request operations are scheduled and run.
*/
@property (nonatomic, strong) NSOperationQueue *operationQueue;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether request operations should consult the credential storage for authenticating the connection. `YES` by default.
@see HAIJIANPPURLConnectionOperation -shouldUseCredentialStorage
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
The credential used by request operations for authentication challenges.
@see HAIJIANPPURLConnectionOperation -credential
*/
@property (nonatomic, strong) NSURLCredential *credential;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created request operations to evaluate server trust for secure connections. `HAIJIANPPHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
*/
@property (nonatomic, strong) HAIJIANPPSecurityPolicy *securityPolicy;
///------------------------------------
/// @name Managing Network Reachability
///------------------------------------
/**
The network reachability manager. `HAIJIANPPHTTPRequestOperationManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) HAIJIANPPNetworkReachabilityManager *reachabilityManager;
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign) dispatch_queue_t completionQueue;
#endif
/**
The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign) dispatch_group_t completionGroup;
#endif
///---------------------------------------------
/// @name Creating and Initializing HTTP Clients
///---------------------------------------------
/**
Creates and returns an `HAIJIANPPHTTPRequestOperationManager` object.
*/
+ (instancetype)manager;
/**
Initializes an `HAIJIANPPHTTPRequestOperationManager` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url NS_DESIGNATED_INITIALIZER;
///---------------------------------------
/// @name Managing HTTP Request Operations
///---------------------------------------
/**
Creates an `HAIJIANPPHTTPRequestOperation`, and sets the response serializers to that of the HTTP client.
@param request The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
*/
- (HAIJIANPPHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `GET` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `HEAD` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a multipart `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `HAIJIANPPMultipartFormData` protocol.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `PUT` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `PATCH` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates and runs an `HAIJIANPPHTTPRequestOperation` with a `DELETE` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
@see -HTTPRequestOperationWithRequest:success:failure:
*/
- (HAIJIANPPHTTPRequestOperation *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure;
@end
// HAIJIANPPHTTPRequestOperationManager.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "HAIJIANPPHTTPRequestOperationManager.h"
#import "HAIJIANPPHTTPRequestOperation.h"
#import <Availability.h>
#import <Security/Security.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
@interface HAIJIANPPHTTPRequestOperationManager ()
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end
@implementation HAIJIANPPHTTPRequestOperationManager
+ (instancetype)manager {
return [[self alloc] initWithBaseURL:nil];
}
- (instancetype)init {
return [self initWithBaseURL:nil];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
self = [super init];
if (!self) {
return nil;
}
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
url = [url URLByAppendingPathComponent:@""];
}
self.baseURL = url;
self.requestSerializer = [HAIJIANPPHTTPRequestSerializer serializer];
self.responseSerializer = [HAIJIANPPJSONResponseSerializer serializer];
self.securityPolicy = [HAIJIANPPSecurityPolicy defaultPolicy];
self.reachabilityManager = [HAIJIANPPNetworkReachabilityManager sharedManager];
self.operationQueue = [[NSOperationQueue alloc] init];
self.shouldUseCredentialStorage = YES;
return self;
}
#pragma mark -
#ifdef _SYSTEMCONFIGURATION_H
#endif
- (void)setRequestSerializer:(HAIJIANPPHTTPRequestSerializer <HAIJIANPPURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
_responseSerializer = responseSerializer;
}
#pragma mark -
- (HAIJIANPPHTTPRequestOperation *)HTTPRequestOperationWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
return [self HTTPRequestOperationWithRequest:request success:success failure:failure];
}
- (HAIJIANPPHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [[HAIJIANPPHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = self.responseSerializer;
operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage;
operation.credential = self.credential;
operation.securityPolicy = self.securityPolicy;
[operation setCompletionBlockWithSuccess:success failure:failure];
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
#pragma mark -
- (HAIJIANPPHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(HAIJIANPPHTTPRequestOperation *requestOperation, __unused id responseObject) {
if (success) {
success(requestOperation);
}
} failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
- (HAIJIANPPHTTPRequestOperation *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(HAIJIANPPHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(HAIJIANPPHTTPRequestOperation *operation, NSError *error))failure
{
HAIJIANPPHTTPRequestOperation *operation = [self HTTPRequestOperationWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))];
self = [self initWithBaseURL:baseURL];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[HAIJIANPPHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[HAIJIANPPHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
return HTTPClient;
}
@end
// HAIJIANPPHTTPSessionManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import "HAIJIANPPURLSessionManager.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`HAIJIANPPHTTPSessionManager` is a subclass of `HAIJIANPPURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
## Subclassing Notes
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `HAIJIANPPHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `HAIJIANPPHTTPRequestOperationManager` may be used to similar effect.
## Methods to Override
To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`.
## Serialization
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<HAIJIANPPURLRequestSerialization>`.
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<HAIJIANPPURLResponseSerialization>`
## URL Construction Using Relative Paths
For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
Below are a few examples of how `baseURL` and relative paths interact:
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
*/
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
@interface HAIJIANPPHTTPSessionManager : HAIJIANPPURLSessionManager <NSSecureCoding, NSCopying>
/**
The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
/**
Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `HAIJIANPPHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies.
@warning `requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) HAIJIANPPHTTPRequestSerializer <HAIJIANPPURLRequestSerialization> * requestSerializer;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `HAIJIANPPJSONResponseSerializer`.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> * responseSerializer;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns an `HAIJIANPPHTTPSessionManager` object.
*/
+ (instancetype)manager;
/**
Initializes an `HAIJIANPPHTTPSessionManager` object with the specified base URL.
@param url The base URL for the HTTP client.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url;
/**
Initializes an `HAIJIANPPHTTPSessionManager` object with the specified base URL.
This is the designated initializer.
@param url The base URL for the HTTP client.
@param configuration The configuration used to create the managed session.
@return The newly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
/**
Creates and runs an `NSURLSessionDataTask` with a `GET` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `HEAD` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `HAIJIANPPMultipartFormData` protocol.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `PUT` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `PATCH` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
/**
Creates and runs an `NSURLSessionDataTask` with a `DELETE` request.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded according to the client request serializer.
@param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.
@param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred.
@see -dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
@end
#endif
// HAIJIANPPHTTPSessionManager.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPHTTPSessionManager.h"
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
#import "HAIJIANPPURLRequestSerialization.h"
#import "HAIJIANPPURLResponseSerialization.h"
#import <Availability.h>
#import <Security/Security.h>
#ifdef _SYSTEMCONFIGURATION_H
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#endif
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
@interface HAIJIANPPHTTPSessionManager ()
@property (readwrite, nonatomic, strong) NSURL *baseURL;
@end
@implementation HAIJIANPPHTTPSessionManager
@dynamic responseSerializer;
+ (instancetype)manager {
return [[[self class] alloc] initWithBaseURL:nil];
}
- (instancetype)init {
return [self initWithBaseURL:nil];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
return [self initWithBaseURL:url sessionConfiguration:nil];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
return [self initWithBaseURL:nil sessionConfiguration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration
{
self = [super initWithSessionConfiguration:configuration];
if (!self) {
return nil;
}
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
url = [url URLByAppendingPathComponent:@""];
}
self.baseURL = url;
self.requestSerializer = [HAIJIANPPHTTPRequestSerializer serializer];
self.responseSerializer = [HAIJIANPPJSONResponseSerializer serializer];
return self;
}
#pragma mark -
#ifdef _SYSTEMCONFIGURATION_H
#endif
- (void)setRequestSerializer:(HAIJIANPPHTTPRequestSerializer <HAIJIANPPURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(HAIJIANPPHTTPResponseSerializer <HAIJIANPPURLResponseSerialization> *)responseSerializer {
NSParameterAssert(responseSerializer);
[super setResponseSerializer:responseSerializer];
}
#pragma mark -
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) {
if (success) {
success(task);
}
} failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(task, error);
}
} else {
if (success) {
success(task, responseObject);
}
}
}];
[task resume];
return task;
}
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
if (!configuration) {
NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
if (configurationIdentifier) {
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
#else
configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
#endif
}
}
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[HAIJIANPPHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[HAIJIANPPHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
} else {
[coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
}
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
return HTTPClient;
}
@end
#endif
// HAIJIANPPNetworkReachabilityManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
typedef NS_ENUM(NSInteger, HAIJIANPPNetworkReachabilityStatus) {
HAIJIANPPNetworkReachabilityStatusUnknown = -1,
HAIJIANPPNetworkReachabilityStatusNotReachable = 0,
HAIJIANPPNetworkReachabilityStatusReachableViaWWAN = 1,
HAIJIANPPNetworkReachabilityStatusReachableViaWiFi = 2,
};
/**
`HAIJIANPPNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)
@warning Instances of `HAIJIANPPNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
*/
@interface HAIJIANPPNetworkReachabilityManager : NSObject
/**
The current network reachability status.
*/
@property (readonly, nonatomic, assign) HAIJIANPPNetworkReachabilityStatus networkReachabilityStatus;
/**
Whether or not the network is currently reachable.
*/
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
/**
Whether or not the network is currently reachable via WWAN.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
/**
Whether or not the network is currently reachable via WiFi.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
///---------------------
/// @name Initialization
///---------------------
/**
Returns the shared network reachability manager.
*/
+ (instancetype)sharedManager;
/**
Creates and returns a network reachability manager for the specified domain.
@param domain The domain used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified domain.
*/
+ (instancetype)managerForDomain:(NSString *)domain;
/**
Creates and returns a network reachability manager for the socket address.
@param address The socket address (`sockaddr_in`) used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified socket address.
*/
+ (instancetype)managerForAddress:(const void *)address;
/**
Initializes an instance of a network reachability manager from the specified reachability object.
@param reachability The reachability object to monitor.
@return An initialized network reachability manager, actively monitoring the specified reachability.
*/
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
///--------------------------------------------------
/// @name Starting & Stopping Reachability Monitoring
///--------------------------------------------------
/**
Starts monitoring for changes in network reachability status.
*/
- (void)startMonitoring;
/**
Stops monitoring for changes in network reachability status.
*/
- (void)stopMonitoring;
///-------------------------------------------------
/// @name Getting Localized Reachability Description
///-------------------------------------------------
/**
Returns a localized string representation of the current network reachability status.
*/
- (NSString *)localizedNetworkReachabilityStatusString;
///---------------------------------------------------
/// @name Setting Network Reachability Change Callback
///---------------------------------------------------
/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
*/
- (void)setReachabilityStatusChangeBlock:(void (^)(HAIJIANPPNetworkReachabilityStatus status))block;
@end
///----------------
/// @name Constants
///----------------
/**
## Network Reachability
The following constants are provided by `HAIJIANPPNetworkReachabilityManager` as possible network reachability statuses.
enum {
HAIJIANPPNetworkReachabilityStatusUnknown,
HAIJIANPPNetworkReachabilityStatusNotReachable,
HAIJIANPPNetworkReachabilityStatusReachableViaWWAN,
HAIJIANPPNetworkReachabilityStatusReachableViaWiFi,
}
`HAIJIANPPNetworkReachabilityStatusUnknown`
The `baseURL` host reachability is not known.
`HAIJIANPPNetworkReachabilityStatusNotReachable`
The `baseURL` host cannot be reached.
`HAIJIANPPNetworkReachabilityStatusReachableViaWWAN`
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
`HAIJIANPPNetworkReachabilityStatusReachableViaWiFi`
The `baseURL` host can be reached via a Wi-Fi connection.
### Keys for Notification UserInfo Dictionary
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
`HAIJIANPPNetworkingReachabilityNotificationStatusItem`
A key in the userInfo dictionary in a `HAIJIANPPNetworkingReachabilityDidChangeNotification` notification.
The corresponding value is an `NSNumber` object representing the `HAIJIANPPNetworkReachabilityStatus` value for the current reachability status.
*/
///--------------------
/// @name Notifications
///--------------------
/**
Posted when network reachability changes.
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `HAIJIANPPNetworkingReachabilityNotificationStatusItem` key, representing the `HAIJIANPPNetworkReachabilityStatus` value for the current network reachability.
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
extern NSString * const HAIJIANPPNetworkingReachabilityDidChangeNotification;
extern NSString * const HAIJIANPPNetworkingReachabilityNotificationStatusItem;
///--------------------
/// @name Functions
///--------------------
/**
Returns a localized string representation of an `HAIJIANPPNetworkReachabilityStatus` value.
*/
extern NSString * HAIJIANPPStringFromNetworkReachabilityStatus(HAIJIANPPNetworkReachabilityStatus status);
// HAIJIANPPNetworkReachabilityManager.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPNetworkReachabilityManager.h"
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
NSString * const HAIJIANPPNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
NSString * const HAIJIANPPNetworkingReachabilityNotificationStatusItem = @"HAIJIANPPNetworkingReachabilityNotificationStatusItem";
typedef void (^HAIJIANPPNetworkReachabilityStatusBlock)(HAIJIANPPNetworkReachabilityStatus status);
typedef NS_ENUM(NSUInteger, HAIJIANPPNetworkReachabilityAssociation) {
HAIJIANPPNetworkReachabilityForAddress = 1,
HAIJIANPPNetworkReachabilityForAddressPair = 2,
HAIJIANPPNetworkReachabilityForName = 3,
};
NSString * HAIJIANPPStringFromNetworkReachabilityStatus(HAIJIANPPNetworkReachabilityStatus status) {
switch (status) {
case HAIJIANPPNetworkReachabilityStatusNotReachable:
return NSLocalizedStringFromTable(@"Not Reachable", @"HAIJIANPPNetworking", nil);
case HAIJIANPPNetworkReachabilityStatusReachableViaWWAN:
return NSLocalizedStringFromTable(@"Reachable via WWAN", @"HAIJIANPPNetworking", nil);
case HAIJIANPPNetworkReachabilityStatusReachableViaWiFi:
return NSLocalizedStringFromTable(@"Reachable via WiFi", @"HAIJIANPPNetworking", nil);
case HAIJIANPPNetworkReachabilityStatusUnknown:
default:
return NSLocalizedStringFromTable(@"Unknown", @"HAIJIANPPNetworking", nil);
}
}
static HAIJIANPPNetworkReachabilityStatus HAIJIANPPNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0));
BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0);
BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction));
HAIJIANPPNetworkReachabilityStatus status = HAIJIANPPNetworkReachabilityStatusUnknown;
if (isNetworkReachable == NO) {
status = HAIJIANPPNetworkReachabilityStatusNotReachable;
}
#if TARGET_OS_IPHONE
else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) {
status = HAIJIANPPNetworkReachabilityStatusReachableViaWWAN;
}
#endif
else {
status = HAIJIANPPNetworkReachabilityStatusReachableViaWiFi;
}
return status;
}
static void HAIJIANPPNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
HAIJIANPPNetworkReachabilityStatus status = HAIJIANPPNetworkReachabilityStatusForFlags(flags);
HAIJIANPPNetworkReachabilityStatusBlock block = (__bridge HAIJIANPPNetworkReachabilityStatusBlock)info;
if (block) {
block(status);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
NSDictionary *userInfo = @{ HAIJIANPPNetworkingReachabilityNotificationStatusItem: @(status) };
[notificationCenter postNotificationName:HAIJIANPPNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo];
});
}
static const void * HAIJIANPPNetworkReachabilityRetainCallback(const void *info) {
return Block_copy(info);
}
static void HAIJIANPPNetworkReachabilityReleaseCallback(const void *info) {
if (info) {
Block_release(info);
}
}
@interface HAIJIANPPNetworkReachabilityManager ()
@property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability;
@property (readwrite, nonatomic, assign) HAIJIANPPNetworkReachabilityAssociation networkReachabilityAssociation;
@property (readwrite, nonatomic, assign) HAIJIANPPNetworkReachabilityStatus networkReachabilityStatus;
@property (readwrite, nonatomic, copy) HAIJIANPPNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
@end
@implementation HAIJIANPPNetworkReachabilityManager
+ (instancetype)sharedManager {
static HAIJIANPPNetworkReachabilityManager *_sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
struct sockaddr_in6 address;
bzero(&address, sizeof(address));
address.sin6_len = sizeof(address);
address.sin6_family = AF_INET6;
_sharedManager = [self managerForAddress:&address];
});
return _sharedManager;
}
+ (instancetype)managerForDomain:(NSString *)domain {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]);
HAIJIANPPNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
manager.networkReachabilityAssociation = HAIJIANPPNetworkReachabilityForName;
return manager;
}
+ (instancetype)managerForAddress:(const void *)address {
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address);
HAIJIANPPNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability];
manager.networkReachabilityAssociation = HAIJIANPPNetworkReachabilityForAddress;
return manager;
}
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability {
self = [super init];
if (!self) {
return nil;
}
self.networkReachability = reachability;
self.networkReachabilityStatus = HAIJIANPPNetworkReachabilityStatusUnknown;
return self;
}
- (void)dealloc {
[self stopMonitoring];
if (_networkReachability) {
CFRelease(_networkReachability);
_networkReachability = NULL;
}
}
#pragma mark -
- (BOOL)isReachable {
return [self isReachableViaWWAN] || [self isReachableViaWiFi];
}
- (BOOL)isReachableViaWWAN {
return self.networkReachabilityStatus == HAIJIANPPNetworkReachabilityStatusReachableViaWWAN;
}
- (BOOL)isReachableViaWiFi {
return self.networkReachabilityStatus == HAIJIANPPNetworkReachabilityStatusReachableViaWiFi;
}
#pragma mark -
- (void)startMonitoring {
[self stopMonitoring];
if (!self.networkReachability) {
return;
}
__weak __typeof(self)weakSelf = self;
HAIJIANPPNetworkReachabilityStatusBlock callback = ^(HAIJIANPPNetworkReachabilityStatus status) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.networkReachabilityStatus = status;
if (strongSelf.networkReachabilityStatusBlock) {
strongSelf.networkReachabilityStatusBlock(status);
}
};
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, HAIJIANPPNetworkReachabilityRetainCallback, HAIJIANPPNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, HAIJIANPPNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
switch (self.networkReachabilityAssociation) {
case HAIJIANPPNetworkReachabilityForName:
break;
case HAIJIANPPNetworkReachabilityForAddress:
case HAIJIANPPNetworkReachabilityForAddressPair:
default: {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
HAIJIANPPNetworkReachabilityStatus status = HAIJIANPPNetworkReachabilityStatusForFlags(flags);
dispatch_async(dispatch_get_main_queue(), ^{
callback(status);
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:HAIJIANPPNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ HAIJIANPPNetworkingReachabilityNotificationStatusItem: @(status) }];
});
});
}
break;
}
}
- (void)stopMonitoring {
if (!self.networkReachability) {
return;
}
SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
}
#pragma mark -
- (NSString *)localizedNetworkReachabilityStatusString {
return HAIJIANPPStringFromNetworkReachabilityStatus(self.networkReachabilityStatus);
}
#pragma mark -
- (void)setReachabilityStatusChangeBlock:(void (^)(HAIJIANPPNetworkReachabilityStatus status))block {
self.networkReachabilityStatusBlock = block;
}
#pragma mark - NSKeyValueObserving
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) {
return [NSSet setWithObject:@"networkReachabilityStatus"];
}
return [super keyPathsForValuesAffectingValueForKey:key];
}
@end
// HAIJIANPPNetworking.h
//
// Copyright (c) 2013 HAIJIANPPNetworking (http://afnetworking.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#ifndef _AFNETWORKING_
#define _AFNETWORKING_
#import "HAIJIANPPURLRequestSerialization.h"
#import "HAIJIANPPURLResponseSerialization.h"
#import "HAIJIANPPSecurityPolicy.h"
#import "HAIJIANPPNetworkReachabilityManager.h"
#import "HAIJIANPPURLConnectionOperation.h"
#import "HAIJIANPPHTTPRequestOperation.h"
#import "HAIJIANPPHTTPRequestOperationManager.h"
#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) )
#import "HAIJIANPPURLSessionManager.h"
#import "HAIJIANPPHTTPSessionManager.h"
#endif
#endif /* _AFNETWORKING_ */
// HAIJIANPPSecurityPolicy.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Security/Security.h>
typedef NS_ENUM(NSUInteger, HAIJIANPPSSLPinningMode) {
HAIJIANPPSSLPinningModeNone,
HAIJIANPPSSLPinningModePublicKey,
HAIJIANPPSSLPinningModeCertificate,
};
/**
`HAIJIANPPSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
*/
@interface HAIJIANPPSecurityPolicy : NSObject
/**
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `HAIJIANPPSSLPinningModeNone`.
*/
@property (readonly, nonatomic, assign) HAIJIANPPSSLPinningMode SSLPinningMode;
/**
Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`.
*/
@property (nonatomic, assign) BOOL validatesCertificateChain;
/**
The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle.
*/
@property (nonatomic, strong) NSArray *pinnedCertificates;
/**
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowInvalidCertificates;
/**
Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
*/
@property (nonatomic, assign) BOOL validatesDomainName;
///-----------------------------------------
/// @name Getting Specific Security Policies
///-----------------------------------------
/**
Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
@return The default security policy.
*/
+ (instancetype)defaultPolicy;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a security policy with the specified pinning mode.
@param pinningMode The SSL pinning mode.
@return A new security policy.
*/
+ (instancetype)policyWithPinningMode:(HAIJIANPPSSLPinningMode)pinningMode;
///------------------------------
/// @name Evaluating Server Trust
///------------------------------
/**
Whether or not the specified server trust should be accepted, based on the security policy.
This method should be used when responding to an authentication challenge from a server.
@param serverTrust The X.509 certificate trust of the server.
@return Whether or not to trust the server.
@warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`.
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE;
/**
Whether or not the specified server trust should be accepted, based on the security policy.
This method should be used when responding to an authentication challenge from a server.
@param serverTrust The X.509 certificate trust of the server.
@param domain The domain of serverTrust. If `nil`, the domain will not be validated.
@return Whether or not to trust the server.
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain;
@end
///----------------
/// @name Constants
///----------------
/**
## SSL Pinning Modes
The following constants are provided by `HAIJIANPPSSLPinningMode` as possible SSL pinning modes.
enum {
HAIJIANPPSSLPinningModeNone,
HAIJIANPPSSLPinningModePublicKey,
HAIJIANPPSSLPinningModeCertificate,
}
`HAIJIANPPSSLPinningModeNone`
Do not used pinned certificates to validate servers.
`HAIJIANPPSSLPinningModePublicKey`
Validate host certificates against public keys of pinned certificates.
`HAIJIANPPSSLPinningModeCertificate`
Validate host certificates against pinned certificates.
*/
// HAIJIANPPSecurityPolicy.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPSecurityPolicy.h"
#import <AssertMacros.h>
#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSData * HAIJIANPPSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
__Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
return (__bridge_transfer NSData *)data;
_out:
if (data) {
CFRelease(data);
}
return nil;
}
#endif
static BOOL HAIJIANPPSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return [HAIJIANPPSecKeyGetData(key1) isEqual:HAIJIANPPSecKeyGetData(key2)];
#endif
}
static id HAIJIANPPPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil;
SecCertificateRef allowedCertificate;
SecCertificateRef allowedCertificates[1];
CFArrayRef tempCertificates = nil;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out);
allowedCertificates[0] = allowedCertificate;
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
if (allowedTrust) {
CFRelease(allowedTrust);
}
if (policy) {
CFRelease(policy);
}
if (tempCertificates) {
CFRelease(tempCertificates);
}
if (allowedCertificate) {
CFRelease(allowedCertificate);
}
return allowedPublicKey;
}
static BOOL HAIJIANPPServerTrustIsValid(SecTrustRef serverTrust) {
BOOL isValid = NO;
SecTrustResultType result;
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
_out:
return isValid;
}
static NSArray * HAIJIANPPCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return [NSArray arrayWithArray:trustChain];
}
static NSArray * HAIJIANPPPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust;
__Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
SecTrustResultType result;
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
_out:
if (trust) {
CFRelease(trust);
}
if (certificates) {
CFRelease(certificates);
}
continue;
}
CFRelease(policy);
return [NSArray arrayWithArray:trustChain];
}
#pragma mark -
@interface HAIJIANPPSecurityPolicy()
@property (readwrite, nonatomic, assign) HAIJIANPPSSLPinningMode SSLPinningMode;
@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
@end
@implementation HAIJIANPPSecurityPolicy
+ (NSArray *)defaultPinnedCertificates {
static NSArray *_defaultPinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});
return _defaultPinnedCertificates;
}
+ (instancetype)defaultPolicy {
HAIJIANPPSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = HAIJIANPPSSLPinningModeNone;
return securityPolicy;
}
+ (instancetype)policyWithPinningMode:(HAIJIANPPSSLPinningMode)pinningMode {
HAIJIANPPSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = pinningMode;
[securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
return securityPolicy;
}
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.validatesCertificateChain = YES;
self.validatesDomainName = YES;
return self;
}
- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates;
if (self.pinnedCertificates) {
NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
for (NSData *certificate in self.pinnedCertificates) {
id publicKey = HAIJIANPPPublicKeyForCertificate(certificate);
if (!publicKey) {
continue;
}
[mutablePinnedPublicKeys addObject:publicKey];
}
self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
} else {
self.pinnedPublicKeys = nil;
}
}
#pragma mark -
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
return [self evaluateServerTrust:serverTrust forDomain:nil];
}
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
NSMutableArray *policies = [NSMutableArray array];
if (self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
} else {
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
if (self.SSLPinningMode == HAIJIANPPSSLPinningModeNone) {
if (self.allowInvalidCertificates || HAIJIANPPServerTrustIsValid(serverTrust)){
return YES;
} else {
return NO;
}
} else if (!HAIJIANPPServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return NO;
}
NSArray *serverCertificates = HAIJIANPPCertificateTrustChainForServerTrust(serverTrust);
switch (self.SSLPinningMode) {
case HAIJIANPPSSLPinningModeNone:
default:
return NO;
case HAIJIANPPSSLPinningModeCertificate: {
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for (NSData *certificateData in self.pinnedCertificates) {
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
if (!HAIJIANPPServerTrustIsValid(serverTrust)) {
return NO;
}
if (!self.validatesCertificateChain) {
return YES;
}
NSUInteger trustedCertificateCount = 0;
for (NSData *trustChainCertificate in serverCertificates) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
trustedCertificateCount++;
}
}
return trustedCertificateCount == [serverCertificates count];
}
case HAIJIANPPSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0;
NSArray *publicKeys = HAIJIANPPPublicKeyTrustChainForServerTrust(serverTrust);
if (!self.validatesCertificateChain && [publicKeys count] > 0) {
publicKeys = @[[publicKeys firstObject]];
}
for (id trustChainPublicKey in publicKeys) {
for (id pinnedPublicKey in self.pinnedPublicKeys) {
if (HAIJIANPPSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
trustedPublicKeyCount += 1;
}
}
}
return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
}
}
return NO;
}
#pragma mark - NSKeyValueObserving
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
return [NSSet setWithObject:@"pinnedCertificates"];
}
@end
// HAIJIANPPURLConnectionOperation.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#import "HAIJIANPPURLRequestSerialization.h"
#import "HAIJIANPPURLResponseSerialization.h"
#import "HAIJIANPPSecurityPolicy.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`HAIJIANPPURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
## Subclassing Notes
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.
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `HAIJIANPPHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
## NSURLConnection Delegate Methods
`HAIJIANPPURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
- `connection:didReceiveResponse:`
- `connection:didReceiveData:`
- `connectionDidFinishLoading:`
- `connection:didFailWithError:`
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
- `connectionShouldUseCredentialStorage:`
- `connection:needNewBodyStream:`
- `connection:willSendRequestForAuthenticationChallenge:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Callbacks and Completion Blocks
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 `HAIJIANPPHTTPRequestOperation` subclasses for an example of this.
Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `HAIJIANPPURLConnectionOperation`'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/).
## SSL Pinning
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.
SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
Connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
## App Extensions
When using HAIJIANPPNetworking in an App Extension, `#define HAIJIANPP_APP_EXTENSIONS` to avoid using unavailable APIs.
## NSCoding & NSCopying Conformance
`HAIJIANPPURLConnectionOperation` 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:
### NSCoding Caveats
- 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`.
- 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.
### NSCopying Caveats
- `-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.
- A copy of an operation will not include the `outputStream` of the original.
- Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
*/
@interface HAIJIANPPURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>
///-------------------------------
/// @name Accessing Run Loop Modes
///-------------------------------
/**
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
*/
@property (nonatomic, strong) NSSet *runLoopModes;
///-----------------------------------------
/// @name Getting URL Connection Information
///-----------------------------------------
/**
The request used by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLRequest *request;
/**
The last response received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLResponse *response;
/**
The error, if any, that occurred in the lifecycle of the request.
*/
@property (readonly, nonatomic, strong) NSError *error;
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
The data received during the request.
*/
@property (readonly, nonatomic, strong) NSData *responseData;
/**
The string representation of the response data.
*/
@property (readonly, nonatomic, copy) NSString *responseString;
/**
The string encoding of the response.
If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
*/
@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
*/
@property (nonatomic, strong) NSURLCredential *credential;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used to evaluate server trust for secure connections.
*/
@property (nonatomic, strong) HAIJIANPPSecurityPolicy *securityPolicy;
///------------------------
/// @name Accessing Streams
///------------------------
/**
The input stream used to read data to be sent during the request.
This property acts as a proxy to the `HTTPBodyStream` property of `request`.
*/
@property (nonatomic, strong) NSInputStream *inputStream;
/**
The output stream that is used to write data received until the request is finished.
By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. 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.
*/
@property (nonatomic, strong) NSOutputStream *outputStream;
///---------------------------------
/// @name Managing Callback Queues
///---------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign) dispatch_queue_t completionQueue;
#endif
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign) dispatch_group_t completionGroup;
#endif
///---------------------------------------------
/// @name Managing Request Operation Information
///---------------------------------------------
/**
The user info dictionary for the receiver.
*/
@property (nonatomic, strong) NSDictionary *userInfo;
///------------------------------------------------------
/// @name Initializing an HAIJIANPPURLConnectionOperation Object
///------------------------------------------------------
/**
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
This is the designated initializer.
@param urlRequest The request object to be used by the operation connection.
*/
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER;
///----------------------------------
/// @name Pausing / Resuming Requests
///----------------------------------
/**
Pauses the execution of the request operation.
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.
*/
- (void)pause;
/**
Whether the request operation is currently paused.
@return `YES` if the operation is currently paused, otherwise `NO`.
*/
- (BOOL)isPaused;
/**
Resumes the execution of the paused request operation.
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, `HAIJIANPPHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
*/
- (void)resume;
///----------------------------------------------
/// @name Configuring Backgrounding Task Behavior
///----------------------------------------------
/**
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
@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.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(HAIJIANPP_APP_EXTENSIONS)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
#endif
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
@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.
*/
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
/**
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
@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.
*/
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
///-------------------------------------------------
/// @name Setting NSURLConnection Delegate Callbacks
///-------------------------------------------------
/**
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:`.
@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).
If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
*/
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
/**
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 `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`.
@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.
*/
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
/**
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
@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.
*/
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
///
/**
*/
+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
@end
///--------------------
/// @name Notifications
///--------------------
/**
Posted when an operation begins executing.
*/
extern NSString * const HAIJIANPPNetworkingOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const HAIJIANPPNetworkingOperationDidFinishNotification;
// HAIJIANPPURLConnectionOperation.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPURLConnectionOperation.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
#if !__has_feature(objc_arc)
#error HAIJIANPPNetworking must be built with ARC.
// You can turn on ARC for only HAIJIANPPNetworking files by adding -fobjc-arc to the build phase for each of its files.
#endif
typedef NS_ENUM(NSInteger, HAIJIANPPOperationState) {
HAIJIANPPOperationPausedState = -1,
HAIJIANPPOperationReadyState = 1,
HAIJIANPPOperationExecutingState = 2,
HAIJIANPPOperationFinishedState = 3,
};
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(HAIJIANPP_APP_EXTENSIONS)
typedef UIBackgroundTaskIdentifier HAIJIANPPBackgroundTaskIdentifier;
#else
typedef id HAIJIANPPBackgroundTaskIdentifier;
#endif
static dispatch_group_t url_request_operation_completion_group() {
static dispatch_group_t af_url_request_operation_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_request_operation_completion_group = dispatch_group_create();
});
return af_url_request_operation_completion_group;
}
static dispatch_queue_t url_request_operation_completion_queue() {
static dispatch_queue_t af_url_request_operation_completion_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT );
});
return af_url_request_operation_completion_queue;
}
static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
NSString * const HAIJIANPPNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const HAIJIANPPNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
typedef void (^HAIJIANPPURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
typedef void (^HAIJIANPPURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
typedef NSCachedURLResponse * (^HAIJIANPPURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
typedef NSURLRequest * (^HAIJIANPPURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
static inline NSString * HAIJIANPPKeyPathFromOperationState(HAIJIANPPOperationState state) {
switch (state) {
case HAIJIANPPOperationReadyState:
return @"isReady";
case HAIJIANPPOperationExecutingState:
return @"isExecuting";
case HAIJIANPPOperationFinishedState:
return @"isFinished";
case HAIJIANPPOperationPausedState:
return @"isPaused";
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
return @"state";
#pragma clang diagnostic pop
}
}
}
static inline BOOL HAIJIANPPStateTransitionIsValid(HAIJIANPPOperationState fromState, HAIJIANPPOperationState toState, BOOL isCancelled) {
switch (fromState) {
case HAIJIANPPOperationReadyState:
switch (toState) {
case HAIJIANPPOperationPausedState:
case HAIJIANPPOperationExecutingState:
return YES;
case HAIJIANPPOperationFinishedState:
return isCancelled;
default:
return NO;
}
case HAIJIANPPOperationExecutingState:
switch (toState) {
case HAIJIANPPOperationPausedState:
case HAIJIANPPOperationFinishedState:
return YES;
default:
return NO;
}
case HAIJIANPPOperationFinishedState:
return NO;
case HAIJIANPPOperationPausedState:
return toState == HAIJIANPPOperationReadyState;
default: {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
switch (toState) {
case HAIJIANPPOperationPausedState:
case HAIJIANPPOperationReadyState:
case HAIJIANPPOperationExecutingState:
case HAIJIANPPOperationFinishedState:
return YES;
default:
return NO;
}
}
#pragma clang diagnostic pop
}
}
@interface HAIJIANPPURLConnectionOperation ()
@property (readwrite, nonatomic, assign) HAIJIANPPOperationState state;
@property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
@property (readwrite, nonatomic, strong) NSURLConnection *connection;
@property (readwrite, nonatomic, strong) NSURLRequest *request;
@property (readwrite, nonatomic, strong) NSURLResponse *response;
@property (readwrite, nonatomic, strong) NSError *error;
@property (readwrite, nonatomic, strong) NSData *responseData;
@property (readwrite, nonatomic, copy) NSString *responseString;
@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
@property (readwrite, nonatomic, assign) long long totalBytesRead;
@property (readwrite, nonatomic, assign) HAIJIANPPBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (readwrite, nonatomic, copy) HAIJIANPPURLConnectionOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) HAIJIANPPURLConnectionOperationProgressBlock downloadProgress;
@property (readwrite, nonatomic, copy) HAIJIANPPURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
@property (readwrite, nonatomic, copy) HAIJIANPPURLConnectionOperationCacheResponseBlock cacheResponse;
@property (readwrite, nonatomic, copy) HAIJIANPPURLConnectionOperationRedirectResponseBlock redirectResponse;
- (void)operationDidStart;
- (void)finish;
- (void)cancelConnection;
@end
@implementation HAIJIANPPURLConnectionOperation
@synthesize outputStream = _outputStream;
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
@autoreleasepool {
[[NSThread currentThread] setName:@"HAIJIANPPNetworking"];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[runLoop run];
}
}
+ (NSThread *)networkRequestThread {
static NSThread *_networkRequestThread = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
});
return _networkRequestThread;
}
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
NSParameterAssert(urlRequest);
self = [super init];
if (!self) {
return nil;
}
_state = HAIJIANPPOperationReadyState;
self.lock = [[NSRecursiveLock alloc] init];
self.lock.name = kAFNetworkingLockName;
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.request = urlRequest;
self.shouldUseCredentialStorage = YES;
self.securityPolicy = [HAIJIANPPSecurityPolicy defaultPolicy];
return self;
}
- (void)dealloc {
if (_outputStream) {
[_outputStream close];
_outputStream = nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(HAIJIANPP_APP_EXTENSIONS)
if (_backgroundTaskIdentifier) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
_backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
#endif
}
#pragma mark -
- (void)setResponseData:(NSData *)responseData {
[self.lock lock];
if (!responseData) {
_responseData = nil;
} else {
_responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length];
}
[self.lock unlock];
}
- (NSString *)responseString {
[self.lock lock];
if (!_responseString && self.response && self.responseData) {
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
}
[self.lock unlock];
return _responseString;
}
- (NSStringEncoding)responseStringEncoding {
[self.lock lock];
if (!_responseStringEncoding && self.response) {
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
if (self.response.textEncodingName) {
CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
if (IANAEncoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
}
}
self.responseStringEncoding = stringEncoding;
}
[self.lock unlock];
return _responseStringEncoding;
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
}
- (NSOutputStream *)outputStream {
if (!_outputStream) {
self.outputStream = [NSOutputStream outputStreamToMemory];
}
return _outputStream;
}
- (void)setOutputStream:(NSOutputStream *)outputStream {
[self.lock lock];
if (outputStream != _outputStream) {
if (_outputStream) {
[_outputStream close];
}
_outputStream = outputStream;
}
[self.lock unlock];
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(HAIJIANPP_APP_EXTENSIONS)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
[self.lock lock];
if (!self.backgroundTaskIdentifier) {
UIApplication *application = [UIApplication sharedApplication];
__weak __typeof(self)weakSelf = self;
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (handler) {
handler();
}
if (strongSelf) {
[strongSelf cancel];
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
}];
}
[self.lock unlock];
}
#endif
#pragma mark -
- (void)setState:(HAIJIANPPOperationState)state {
if (!HAIJIANPPStateTransitionIsValid(self.state, state, [self isCancelled])) {
return;
}
[self.lock lock];
NSString *oldStateKey = HAIJIANPPKeyPathFromOperationState(self.state);
NSString *newStateKey = HAIJIANPPKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
[self.lock unlock];
}
- (void)pause {
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
return;
}
[self.lock lock];
if ([self isExecuting]) {
[self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
dispatch_async(dispatch_get_main_queue(), ^{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:HAIJIANPPNetworkingOperationDidFinishNotification object:self];
});
}
self.state = HAIJIANPPOperationPausedState;
[self.lock unlock];
}
- (void)operationDidPause {
[self.lock lock];
[self.connection cancel];
[self.lock unlock];
}
- (BOOL)isPaused {
return self.state == HAIJIANPPOperationPausedState;
}
- (void)resume {
if (![self isPaused]) {
return;
}
[self.lock lock];
self.state = HAIJIANPPOperationReadyState;
[self start];
[self.lock unlock];
}
#pragma mark -
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
self.authenticationChallenge = block;
}
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
self.cacheResponse = block;
}
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
self.redirectResponse = block;
}
#pragma mark - NSOperation
- (void)setCompletionBlock:(void (^)(void))block {
[self.lock lock];
if (!block) {
[super setCompletionBlock:nil];
} else {
__weak __typeof(self)weakSelf = self;
[super setCompletionBlock:^ {
__strong __typeof(weakSelf)strongSelf = weakSelf;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
block();
});
dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
[strongSelf setCompletionBlock:nil];
});
}];
}
[self.lock unlock];
}
- (BOOL)isReady {
return self.state == HAIJIANPPOperationReadyState && [super isReady];
}
- (BOOL)isExecuting {
return self.state == HAIJIANPPOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == HAIJIANPPOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
[self.lock lock];
if ([self isCancelled]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
} else if ([self isReady]) {
self.state = HAIJIANPPOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
[self.lock unlock];
}
- (void)operationDidStart {
[self.lock lock];
if (![self isCancelled]) {
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
for (NSString *runLoopMode in self.runLoopModes) {
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
}
[self.outputStream open];
[self.connection start];
}
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingOperationDidStartNotification object:self];
});
}
- (void)finish {
[self.lock lock];
self.state = HAIJIANPPOperationFinishedState;
[self.lock unlock];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingOperationDidFinishNotification object:self];
});
}
- (void)cancel {
[self.lock lock];
if (![self isFinished] && ![self isCancelled]) {
[super cancel];
if ([self isExecuting]) {
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
}
}
[self.lock unlock];
}
- (void)cancelConnection {
NSDictionary *userInfo = nil;
if ([self.request URL]) {
userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
}
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (![self isFinished]) {
if (self.connection) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
} else {
// Accomodate race condition where `self.connection` has not yet been set before cancellation
self.error = error;
[self finish];
}
}
}
#pragma mark -
+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
if (!operations || [operations count] == 0) {
return @[[NSBlockOperation blockOperationWithBlock:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(@[]);
}
});
}]];
}
__block dispatch_group_t group = dispatch_group_create();
NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(operations);
}
});
}];
for (HAIJIANPPURLConnectionOperation *operation in operations) {
operation.completionGroup = group;
void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
__weak __typeof(operation)weakOperation = operation;
operation.completionBlock = ^{
__strong __typeof(weakOperation)strongOperation = weakOperation;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
#pragma clang diagnostic pop
dispatch_group_async(group, queue, ^{
if (originalCompletionBlock) {
originalCompletionBlock();
}
NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) {
return [op isFinished];
}] count];
if (progressBlock) {
progressBlock(numberOfFinishedOperations, [operations count]);
}
dispatch_group_leave(group);
});
};
dispatch_group_enter(group);
[batchedOperation addDependency:operation];
}
return [operations arrayByAddingObject:batchedOperation];
}
#pragma mark - NSObject
- (NSString *)description {
[self.lock lock];
NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, HAIJIANPPKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
[self.lock unlock];
return description;
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if (self.authenticationChallenge) {
self.authenticationChallenge(connection, challenge);
return;
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
} else {
if ([challenge previousFailureCount] == 0) {
if (self.credential) {
[[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
return self.shouldUseCredentialStorage;
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse
{
if (self.redirectResponse) {
return self.redirectResponse(connection, request, redirectResponse);
} else {
return request;
}
}
- (void)connection:(NSURLConnection __unused *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.uploadProgress) {
self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
});
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = response;
}
- (void)connection:(NSURLConnection __unused *)connection
didReceiveData:(NSData *)data
{
NSUInteger length = [data length];
while (YES) {
NSInteger totalNumberOfBytesWritten = 0;
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = (uint8_t *)[data bytes];
NSInteger numberOfBytesWritten = 0;
while (totalNumberOfBytesWritten < (NSInteger)length) {
numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
if (numberOfBytesWritten == -1) {
break;
}
totalNumberOfBytesWritten += numberOfBytesWritten;
}
break;
}
if (self.outputStream.streamError) {
[self.connection cancel];
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
return;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
self.totalBytesRead += (long long)length;
if (self.downloadProgress) {
self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
}
});
}
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[self.outputStream close];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (void)connection:(NSURLConnection __unused *)connection
didFailWithError:(NSError *)error
{
self.error = error;
[self.outputStream close];
if (self.responseData) {
self.outputStream = nil;
}
self.connection = nil;
[self finish];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if (self.cacheResponse) {
return self.cacheResponse(connection, cachedResponse);
} else {
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))];
self = [self initWithRequest:request];
if (!self) {
return nil;
}
self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue];
self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))];
self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))];
self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))];
self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[self pause];
[coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))];
switch (self.state) {
case HAIJIANPPOperationExecutingState:
case HAIJIANPPOperationPausedState:
[coder encodeInteger:HAIJIANPPOperationReadyState forKey:NSStringFromSelector(@selector(state))];
break;
default:
[coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))];
break;
}
[coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))];
[coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))];
[coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))];
[coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPURLConnectionOperation *operation = [(HAIJIANPPURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
operation.uploadProgress = self.uploadProgress;
operation.downloadProgress = self.downloadProgress;
operation.authenticationChallenge = self.authenticationChallenge;
operation.cacheResponse = self.cacheResponse;
operation.redirectResponse = self.redirectResponse;
operation.completionQueue = self.completionQueue;
operation.completionGroup = self.completionGroup;
return operation;
}
@end
// HAIJIANPPURLRequestSerialization.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#endif
/**
The `HAIJIANPPURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.
For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`.
*/
@protocol HAIJIANPPURLRequestSerialization <NSObject, NSSecureCoding, NSCopying>
/**
Returns a request with the specified parameters encoded into a copy of the original request.
@param request The original request.
@param parameters The parameters to be encoded.
@param error The error that occurred while attempting to encode the request parameters.
@return A serialized request.
*/
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError * __autoreleasing *)error;
@end
#pragma mark -
/**
*/
typedef NS_ENUM(NSUInteger, HAIJIANPPHTTPRequestQueryStringSerializationStyle) {
HAIJIANPPHTTPRequestQueryStringDefaultStyle = 0,
};
@protocol HAIJIANPPMultipartFormData;
/**
`HAIJIANPPHTTPRequestSerializer` conforms to the `HAIJIANPPURLRequestSerialization` & `HAIJIANPPURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
Any request or response serializer dealing with HTTP is encouraged to subclass `HAIJIANPPHTTPRequestSerializer` in order to ensure consistent default behavior.
*/
@interface HAIJIANPPHTTPRequestSerializer : NSObject <HAIJIANPPURLRequestSerialization>
/**
The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
Whether created requests can use the device’s cellular radio (if present). `YES` by default.
@see NSMutableURLRequest -setAllowsCellularAccess:
*/
@property (nonatomic, assign) BOOL allowsCellularAccess;
/**
The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default.
@see NSMutableURLRequest -setCachePolicy:
*/
@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
/**
Whether created requests should use the default cookie handling. `YES` by default.
@see NSMutableURLRequest -setHTTPShouldHandleCookies:
*/
@property (nonatomic, assign) BOOL HTTPShouldHandleCookies;
/**
Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default
@see NSMutableURLRequest -setHTTPShouldUsePipelining:
*/
@property (nonatomic, assign) BOOL HTTPShouldUsePipelining;
/**
The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default.
@see NSMutableURLRequest -setNetworkServiceType:
*/
@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType;
/**
The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.
@see NSMutableURLRequest -setTimeoutInterval:
*/
@property (nonatomic, assign) NSTimeInterval timeoutInterval;
///---------------------------------------
/// @name Configuring HTTP Request Headers
///---------------------------------------
/**
Default HTTP header field values to be applied to serialized requests. By default, these include the following:
- `Accept-Language` with the contents of `NSLocale +preferredLanguages`
- `User-Agent` with the contents of various bundle identifiers and OS designations
@discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders;
/**
Creates and returns a serializer with default configuration.
*/
+ (instancetype)serializer;
/**
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
@param field The HTTP header to set a default value for
@param value The value set as default for the specified header, or `nil`
*/
- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field;
/**
Returns the value for the HTTP headers set in the request serializer.
@param field The HTTP header to retrieve the default value for
@return The value set as default for the specified header, or `nil`
*/
- (NSString *)valueForHTTPHeaderField:(NSString *)field;
/**
Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
@param username The HTTP basic auth username
@param password The HTTP basic auth password
*/
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
password:(NSString *)password;
/**
@deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead.
*/
- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE;
/**
Clears any existing value for the "Authorization" HTTP header.
*/
- (void)clearAuthorizationHeader;
///-------------------------------------------------------
/// @name Configuring Query String Parameter Serialization
///-------------------------------------------------------
/**
HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default.
*/
@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI;
/**
Set the method of query string serialization according to one of the pre-defined styles.
@param style The serialization style.
@see HAIJIANPPHTTPRequestQueryStringSerializationStyle
*/
- (void)setQueryStringSerializationWithStyle:(HAIJIANPPHTTPRequestQueryStringSerializationStyle)style;
/**
Set the a custom method of query string serialization according to the specified block.
@param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.
*/
- (void)setQueryStringSerializationWithBlock:(NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block;
///-------------------------------
/// @name Creating Request Objects
///-------------------------------
/**
@deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead.
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters DEPRECATED_ATTRIBUTE;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
@param error The error that occured while constructing the request.
@return An `NSMutableURLRequest` object.
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError * __autoreleasing *)error;
/**
@deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead.
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block DEPRECATED_ATTRIBUTE;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
@param URLString The URL string used to create the request URL.
@param parameters The parameters to be encoded and set in the request HTTP body.
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `HAIJIANPPMultipartFormData` protocol.
@param error The error that occured while constructing the request.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
error:(NSError * __autoreleasing *)error;
/**
Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.
@param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`.
@param fileURL The file URL to write multipart form contents to.
@param handler A handler block to execute.
@discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `HAIJIANPPURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request.
@see https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/issues/1398
*/
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
writingStreamContentsToFile:(NSURL *)fileURL
completionHandler:(void (^)(NSError *error))handler;
@end
#pragma mark -
/**
The `HAIJIANPPMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `HAIJIANPPHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`.
*/
@protocol HAIJIANPPMultipartFormData
/**
Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended, otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`.
@param mimeType The declared MIME type of the file data. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
@return `YES` if the file data was successfully appended otherwise `NO`.
*/
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
error:(NSError * __autoreleasing *)error;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary.
@param inputStream The input stream to be appended to the form data
@param name The name to be associated with the specified input stream. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`.
@param length The length of the specified input stream in bytes.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithInputStream:(NSInputStream *)inputStream
name:(NSString *)name
fileName:(NSString *)fileName
length:(int64_t)length
mimeType:(NSString *)mimeType;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
@param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
*/
- (void)appendPartWithFileData:(NSData *)data
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType;
/**
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
@param data The data to be encoded and appended to the form data.
@param name The name to be associated with the specified data. This parameter must not be `nil`.
*/
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name;
/**
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
@param headers The HTTP headers to be appended to the form data.
@param body The data to be encoded and appended to the form data. This parameter must not be `nil`.
*/
- (void)appendPartWithHeaders:(NSDictionary *)headers
body:(NSData *)body;
/**
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kHJAFUploadStream3GSuggestedPacketSize` and `kHJAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.
@param delay Duration of delay each time a packet is read. By default, no delay is set.
*/
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
delay:(NSTimeInterval)delay;
@end
#pragma mark -
/**
`HAIJIANPPJSONRequestSerializer` is a subclass of `HAIJIANPPHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`.
*/
@interface HAIJIANPPJSONRequestSerializer : HAIJIANPPHTTPRequestSerializer
/**
Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default.
*/
@property (nonatomic, assign) NSJSONWritingOptions writingOptions;
/**
Creates and returns a JSON serializer with specified reading and writing options.
@param writingOptions The specified JSON writing options.
*/
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions;
@end
#pragma mark -
/**
`HAIJIANPPPropertyListRequestSerializer` is a subclass of `HAIJIANPPHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`.
*/
@interface HAIJIANPPPropertyListRequestSerializer : HAIJIANPPHTTPRequestSerializer
/**
The property list format. Possible values are described in "NSPropertyListFormat".
*/
@property (nonatomic, assign) NSPropertyListFormat format;
/**
@warning The `writeOptions` property is currently unused.
*/
@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions;
/**
Creates and returns a property list serializer with a specified format, read options, and write options.
@param format The property list format.
@param writeOptions The property list write options.
@warning The `writeOptions` property is currently unused.
*/
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
writeOptions:(NSPropertyListWriteOptions)writeOptions;
@end
#pragma mark -
///----------------
/// @name Constants
///----------------
/**
## Error Domains
The following error domain is predefined.
- `NSString * const HAIJIANPPURLRequestSerializationErrorDomain`
### Constants
`HAIJIANPPURLRequestSerializationErrorDomain`
HAIJIANPPURLRequestSerializer errors. Error codes for `HAIJIANPPURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
extern NSString * const HAIJIANPPURLRequestSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const HAIJIANPPNetworkingOperationFailingURLRequestErrorKey`
### Constants
`HAIJIANPPNetworkingOperationFailingURLRequestErrorKey`
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `HAIJIANPPURLRequestSerializationErrorDomain`.
*/
extern NSString * const HAIJIANPPNetworkingOperationFailingURLRequestErrorKey;
/**
## Throttling Bandwidth for HTTP Request Input Streams
@see -throttleBandwidthWithPacketSize:delay:
### Constants
`kHJAFUploadStream3GSuggestedPacketSize`
Maximum packet size, in number of bytes. Equal to 16kb.
`kHJAFUploadStream3GSuggestedDelay`
Duration of delay each time a packet is read. Equal to 0.2 seconds.
*/
extern NSUInteger const kHJAFUploadStream3GSuggestedPacketSize;
extern NSTimeInterval const kHJAFUploadStream3GSuggestedDelay;
// HAIJIANPPURLRequestSerialization.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPURLRequestSerialization.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
NSString * const HAIJIANPPURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
NSString * const HAIJIANPPNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
typedef NSString * (^HAIJIANPPQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
static NSString * HAIJIANPPBase64EncodedStringFromString(NSString *string) {
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSUInteger length = [data length];
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3) {
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
NSUInteger idx = (i / 3) * 4;
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*";
static NSString * HAIJIANPPPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[].";
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}
static NSString * HAIJIANPPPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding));
}
#pragma mark -
@interface HAIJIANPPQueryStringPair : NSObject
@property (readwrite, nonatomic, strong) id field;
@property (readwrite, nonatomic, strong) id value;
- (id)initWithField:(id)field value:(id)value;
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
@end
@implementation HAIJIANPPQueryStringPair
- (id)initWithField:(id)field value:(id)value {
self = [super init];
if (!self) {
return nil;
}
self.field = field;
self.value = value;
return self;
}
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
if (!self.value || [self.value isEqual:[NSNull null]]) {
return HAIJIANPPPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding);
} else {
return [NSString stringWithFormat:@"%@=%@", HAIJIANPPPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), HAIJIANPPPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)];
}
}
@end
#pragma mark -
extern NSArray * HAIJIANPPQueryStringPairsFromDictionary(NSDictionary *dictionary);
extern NSArray * HAIJIANPPQueryStringPairsFromKeyAndValue(NSString *key, id value);
static NSString * HAIJIANPPQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
NSMutableArray *mutablePairs = [NSMutableArray array];
for (HAIJIANPPQueryStringPair *pair in HAIJIANPPQueryStringPairsFromDictionary(parameters)) {
[mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
}
return [mutablePairs componentsJoinedByString:@"&"];
}
NSArray * HAIJIANPPQueryStringPairsFromDictionary(NSDictionary *dictionary) {
return HAIJIANPPQueryStringPairsFromKeyAndValue(nil, dictionary);
}
NSArray * HAIJIANPPQueryStringPairsFromKeyAndValue(NSString *key, id value) {
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = value;
// Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
id nestedValue = [dictionary objectForKey:nestedKey];
if (nestedValue) {
[mutableQueryStringComponents addObjectsFromArray:HAIJIANPPQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
}
}
} else if ([value isKindOfClass:[NSArray class]]) {
NSArray *array = value;
for (id nestedValue in array) {
[mutableQueryStringComponents addObjectsFromArray:HAIJIANPPQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
}
} else if ([value isKindOfClass:[NSSet class]]) {
NSSet *set = value;
for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
[mutableQueryStringComponents addObjectsFromArray:HAIJIANPPQueryStringPairsFromKeyAndValue(key, obj)];
}
} else {
[mutableQueryStringComponents addObject:[[HAIJIANPPQueryStringPair alloc] initWithField:key value:value]];
}
return mutableQueryStringComponents;
}
#pragma mark -
@interface HAIJIANPPStreamingMultipartFormData : NSObject <HAIJIANPPMultipartFormData>
- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
stringEncoding:(NSStringEncoding)encoding;
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
@end
#pragma mark -
static NSArray * HAIJIANPPHTTPRequestSerializerObservedKeyPaths() {
static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
});
return _AFHTTPRequestSerializerObservedKeyPaths;
}
static void *HAIJIANPPHTTPRequestSerializerObserverContext = &HAIJIANPPHTTPRequestSerializerObserverContext;
@interface HAIJIANPPHTTPRequestSerializer ()
@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
@property (readwrite, nonatomic, assign) HAIJIANPPHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
@property (readwrite, nonatomic, copy) HAIJIANPPQueryStringSerializationBlock queryStringSerialization;
@end
@implementation HAIJIANPPHTTPRequestSerializer
+ (instancetype)serializer {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = NSUTF8StringEncoding;
self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
[[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
float q = 1.0f - (idx * 0.1f);
[acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
*stop = q <= 0.5f;
}];
[self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
NSString *userAgent = nil;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
#endif
#pragma clang diagnostic pop
if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
[self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
}
// HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
self.mutableObservedChangedKeyPaths = [NSMutableSet set];
for (NSString *keyPath in HAIJIANPPHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:HAIJIANPPHTTPRequestSerializerObserverContext];
}
}
return self;
}
- (void)dealloc {
for (NSString *keyPath in HAIJIANPPHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self removeObserver:self forKeyPath:keyPath context:HAIJIANPPHTTPRequestSerializerObserverContext];
}
}
}
#pragma mark -
// Workarounds for crashing behavior using Key-Value Observing with XCTest
// See https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/issues/2523
- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
[self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
_allowsCellularAccess = allowsCellularAccess;
[self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
}
- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
[self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
_cachePolicy = cachePolicy;
[self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
}
- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
[self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
_HTTPShouldHandleCookies = HTTPShouldHandleCookies;
[self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
}
- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
[self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
_HTTPShouldUsePipelining = HTTPShouldUsePipelining;
[self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
}
- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
[self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
_networkServiceType = networkServiceType;
[self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
}
- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
[self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
_timeoutInterval = timeoutInterval;
[self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
}
#pragma mark -
- (NSDictionary *)HTTPRequestHeaders {
return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
}
- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field
{
[self.mutableHTTPRequestHeaders setValue:value forKey:field];
}
- (NSString *)valueForHTTPHeaderField:(NSString *)field {
return [self.mutableHTTPRequestHeaders valueForKey:field];
}
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
password:(NSString *)password
{
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
[self setValue:[NSString stringWithFormat:@"Basic %@", HAIJIANPPBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"];
}
- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token {
[self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"];
}
- (void)clearAuthorizationHeader {
[self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
}
#pragma mark -
- (void)setQueryStringSerializationWithStyle:(HAIJIANPPHTTPRequestQueryStringSerializationStyle)style {
self.queryStringSerializationStyle = style;
self.queryStringSerialization = nil;
}
- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
self.queryStringSerialization = block;
}
#pragma mark -
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
{
return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil];
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
NSParameterAssert(URLString);
NSURL *url = [NSURL URLWithString:URLString];
NSParameterAssert(url);
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
mutableRequest.HTTPMethod = method;
for (NSString *keyPath in HAIJIANPPHTTPRequestSerializerObservedKeyPaths()) {
if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
[mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
}
}
mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
return mutableRequest;
}
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
{
return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil];
}
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <HAIJIANPPMultipartFormData> formData))block
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
__block HAIJIANPPStreamingMultipartFormData *formData = [[HAIJIANPPStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
if (parameters) {
for (HAIJIANPPQueryStringPair *pair in HAIJIANPPQueryStringPairsFromDictionary(parameters)) {
NSData *data = nil;
if ([pair.value isKindOfClass:[NSData class]]) {
data = pair.value;
} else if ([pair.value isEqual:[NSNull null]]) {
data = [NSData data];
} else {
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
}
if (data) {
[formData appendPartWithFormData:data name:[pair.field description]];
}
}
}
if (block) {
block(formData);
}
return [formData requestByFinalizingMultipartFormData];
}
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
writingStreamContentsToFile:(NSURL *)fileURL
completionHandler:(void (^)(NSError *error))handler
{
NSParameterAssert(request.HTTPBodyStream);
NSParameterAssert([fileURL isFileURL]);
NSInputStream *inputStream = request.HTTPBodyStream;
NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
__block NSError *error = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
uint8_t buffer[1024];
NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
if (inputStream.streamError || bytesRead < 0) {
error = inputStream.streamError;
break;
}
NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
if (outputStream.streamError || bytesWritten < 0) {
error = outputStream.streamError;
break;
}
if (bytesRead == 0 && bytesWritten == 0) {
break;
}
}
[outputStream close];
[inputStream close];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(error);
});
}
});
NSMutableURLRequest *mutableRequest = [request mutableCopy];
mutableRequest.HTTPBodyStream = nil;
return mutableRequest;
}
#pragma mark - HAIJIANPPURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
NSString *query = nil;
if (self.queryStringSerialization) {
NSError *serializationError;
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
} else {
switch (self.queryStringSerializationStyle) {
case HAIJIANPPHTTPRequestQueryStringDefaultStyle:
query = HAIJIANPPQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
break;
}
}
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
} else {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
}
return mutableRequest;
}
#pragma mark - NSKeyValueObserving
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
if ([HAIJIANPPHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(__unused id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == HAIJIANPPHTTPRequestSerializerObserverContext) {
if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
[self.mutableObservedChangedKeyPaths removeObject:keyPath];
} else {
[self.mutableObservedChangedKeyPaths addObject:keyPath];
}
}
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
[coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
serializer.queryStringSerialization = self.queryStringSerialization;
return serializer;
}
@end
#pragma mark -
static NSString * HAIJIANPPCreateMultipartFormBoundary() {
return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
}
static NSString * const kAFMultipartFormCRLF = @"\r\n";
static inline NSString * HAIJIANPPMultipartFormInitialBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
}
static inline NSString * HAIJIANPPMultipartFormEncapsulationBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
}
static inline NSString * HAIJIANPPMultipartFormFinalBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
}
static inline NSString * HAIJIANPPContentTypeForPathExtension(NSString *extension) {
#ifdef __UTTYPE__
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
if (!contentType) {
return @"application/octet-stream";
} else {
return contentType;
}
#else
#pragma unused (extension)
return @"application/octet-stream";
#endif
}
NSUInteger const kHJAFUploadStream3GSuggestedPacketSize = 1024 * 16;
NSTimeInterval const kHJAFUploadStream3GSuggestedDelay = 0.2;
@interface HAIJIANPPHTTPBodyPart : NSObject
@property (nonatomic, assign) NSStringEncoding stringEncoding;
@property (nonatomic, strong) NSDictionary *headers;
@property (nonatomic, copy) NSString *boundary;
@property (nonatomic, strong) id body;
@property (nonatomic, assign) unsigned long long bodyContentLength;
@property (nonatomic, strong) NSInputStream *inputStream;
@property (nonatomic, assign) BOOL hasInitialBoundary;
@property (nonatomic, assign) BOOL hasFinalBoundary;
@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
@property (readonly, nonatomic, assign) unsigned long long contentLength;
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length;
@end
@interface HAIJIANPPMultipartBodyStream : NSInputStream <NSStreamDelegate>
@property (nonatomic, assign) NSUInteger numberOfBytesInPacket;
@property (nonatomic, assign) NSTimeInterval delay;
@property (nonatomic, strong) NSInputStream *inputStream;
@property (readonly, nonatomic, assign) unsigned long long contentLength;
@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty;
- (id)initWithStringEncoding:(NSStringEncoding)encoding;
- (void)setInitialAndFinalBoundaries;
- (void)appendHTTPBodyPart:(HAIJIANPPHTTPBodyPart *)bodyPart;
@end
#pragma mark -
@interface HAIJIANPPStreamingMultipartFormData ()
@property (readwrite, nonatomic, copy) NSMutableURLRequest *request;
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
@property (readwrite, nonatomic, copy) NSString *boundary;
@property (readwrite, nonatomic, strong) HAIJIANPPMultipartBodyStream *bodyStream;
@end
@implementation HAIJIANPPStreamingMultipartFormData
- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest
stringEncoding:(NSStringEncoding)encoding
{
self = [super init];
if (!self) {
return nil;
}
self.request = urlRequest;
self.stringEncoding = encoding;
self.boundary = HAIJIANPPCreateMultipartFormBoundary();
self.bodyStream = [[HAIJIANPPMultipartBodyStream alloc] initWithStringEncoding:encoding];
return self;
}
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
error:(NSError * __autoreleasing *)error
{
NSParameterAssert(fileURL);
NSParameterAssert(name);
NSString *fileName = [fileURL lastPathComponent];
NSString *mimeType = HAIJIANPPContentTypeForPathExtension([fileURL pathExtension]);
return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error];
}
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
error:(NSError * __autoreleasing *)error
{
NSParameterAssert(fileURL);
NSParameterAssert(name);
NSParameterAssert(fileName);
NSParameterAssert(mimeType);
if (![fileURL isFileURL]) {
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"HAIJIANPPNetworking", nil)};
if (error) {
*error = [[NSError alloc] initWithDomain:HAIJIANPPURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
}
return NO;
} else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"HAIJIANPPNetworking", nil)};
if (error) {
*error = [[NSError alloc] initWithDomain:HAIJIANPPURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
}
return NO;
}
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error];
if (!fileAttributes) {
return NO;
}
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
HAIJIANPPHTTPBodyPart *bodyPart = [[HAIJIANPPHTTPBodyPart alloc] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = mutableHeaders;
bodyPart.boundary = self.boundary;
bodyPart.body = fileURL;
bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
[self.bodyStream appendHTTPBodyPart:bodyPart];
return YES;
}
- (void)appendPartWithInputStream:(NSInputStream *)inputStream
name:(NSString *)name
fileName:(NSString *)fileName
length:(int64_t)length
mimeType:(NSString *)mimeType
{
NSParameterAssert(name);
NSParameterAssert(fileName);
NSParameterAssert(mimeType);
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
HAIJIANPPHTTPBodyPart *bodyPart = [[HAIJIANPPHTTPBodyPart alloc] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = mutableHeaders;
bodyPart.boundary = self.boundary;
bodyPart.body = inputStream;
bodyPart.bodyContentLength = (unsigned long long)length;
[self.bodyStream appendHTTPBodyPart:bodyPart];
}
- (void)appendPartWithFileData:(NSData *)data
name:(NSString *)name
fileName:(NSString *)fileName
mimeType:(NSString *)mimeType
{
NSParameterAssert(name);
NSParameterAssert(fileName);
NSParameterAssert(mimeType);
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
[self appendPartWithHeaders:mutableHeaders body:data];
}
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name
{
NSParameterAssert(name);
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
[self appendPartWithHeaders:mutableHeaders body:data];
}
- (void)appendPartWithHeaders:(NSDictionary *)headers
body:(NSData *)body
{
NSParameterAssert(body);
HAIJIANPPHTTPBodyPart *bodyPart = [[HAIJIANPPHTTPBodyPart alloc] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = headers;
bodyPart.boundary = self.boundary;
bodyPart.bodyContentLength = [body length];
bodyPart.body = body;
[self.bodyStream appendHTTPBodyPart:bodyPart];
}
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
delay:(NSTimeInterval)delay
{
self.bodyStream.numberOfBytesInPacket = numberOfBytes;
self.bodyStream.delay = delay;
}
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
if ([self.bodyStream isEmpty]) {
return self.request;
}
// Reset the initial and final boundaries to ensure correct Content-Length
[self.bodyStream setInitialAndFinalBoundaries];
[self.request setHTTPBodyStream:self.bodyStream];
[self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"];
[self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
return self.request;
}
@end
#pragma mark -
@interface NSStream ()
@property (readwrite) NSStreamStatus streamStatus;
@property (readwrite, copy) NSError *streamError;
@end
@interface HAIJIANPPMultipartBodyStream () <NSCopying>
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
@property (readwrite, nonatomic, strong) HAIJIANPPHTTPBodyPart *currentHTTPBodyPart;
@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
@property (readwrite, nonatomic, strong) NSMutableData *buffer;
@end
@implementation HAIJIANPPMultipartBodyStream
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-atomic-properties"
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
@synthesize delegate;
#endif
@synthesize streamStatus;
@synthesize streamError;
#pragma clang diagnostic pop
- (id)initWithStringEncoding:(NSStringEncoding)encoding {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = encoding;
self.HTTPBodyParts = [NSMutableArray array];
self.numberOfBytesInPacket = NSIntegerMax;
return self;
}
- (void)setInitialAndFinalBoundaries {
if ([self.HTTPBodyParts count] > 0) {
for (HAIJIANPPHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
bodyPart.hasInitialBoundary = NO;
bodyPart.hasFinalBoundary = NO;
}
[[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES];
[[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
}
}
- (void)appendHTTPBodyPart:(HAIJIANPPHTTPBodyPart *)bodyPart {
[self.HTTPBodyParts addObject:bodyPart];
}
- (BOOL)isEmpty {
return [self.HTTPBodyParts count] == 0;
}
#pragma mark - NSInputStream
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
if ([self streamStatus] == NSStreamStatusClosed) {
return 0;
}
NSInteger totalNumberOfBytesRead = 0;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
break;
}
} else {
NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead;
NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
if (numberOfBytesRead == -1) {
self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
break;
} else {
totalNumberOfBytesRead += numberOfBytesRead;
if (self.delay > 0.0f) {
[NSThread sleepForTimeInterval:self.delay];
}
}
}
}
#pragma clang diagnostic pop
return totalNumberOfBytesRead;
}
- (BOOL)getBuffer:(__unused uint8_t **)buffer
length:(__unused NSUInteger *)len
{
return NO;
}
- (BOOL)hasBytesAvailable {
return [self streamStatus] == NSStreamStatusOpen;
}
#pragma mark - NSStream
- (void)open {
if (self.streamStatus == NSStreamStatusOpen) {
return;
}
self.streamStatus = NSStreamStatusOpen;
[self setInitialAndFinalBoundaries];
self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
}
- (void)close {
self.streamStatus = NSStreamStatusClosed;
}
- (id)propertyForKey:(__unused NSString *)key {
return nil;
}
- (BOOL)setProperty:(__unused id)property
forKey:(__unused NSString *)key
{
return NO;
}
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (unsigned long long)contentLength {
unsigned long long length = 0;
for (HAIJIANPPHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
length += [bodyPart contentLength];
}
return length;
}
#pragma mark - Undocumented CFReadStream Bridged Methods
- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
forMode:(__unused CFStringRef)aMode
{}
- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
forMode:(__unused CFStringRef)aMode
{}
- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
callback:(__unused CFReadStreamClientCallBack)inCallback
context:(__unused CFStreamClientContext *)inContext {
return NO;
}
#pragma mark - NSCopying
-(id)copyWithZone:(NSZone *)zone {
HAIJIANPPMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
for (HAIJIANPPHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
[bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
}
[bodyStreamCopy setInitialAndFinalBoundaries];
return bodyStreamCopy;
}
@end
#pragma mark -
typedef enum {
HAIJIANPPEncapsulationBoundaryPhase = 1,
HAIJIANPPHeaderPhase = 2,
HAIJIANPPBodyPhase = 3,
HAIJIANPPFinalBoundaryPhase = 4,
} HAIJIANPPHTTPBodyPartReadPhase;
@interface HAIJIANPPHTTPBodyPart () <NSCopying> {
HAIJIANPPHTTPBodyPartReadPhase _phase;
NSInputStream *_inputStream;
unsigned long long _phaseReadOffset;
}
- (BOOL)transitionToNextPhase;
- (NSInteger)readData:(NSData *)data
intoBuffer:(uint8_t *)buffer
maxLength:(NSUInteger)length;
@end
@implementation HAIJIANPPHTTPBodyPart
- (id)init {
self = [super init];
if (!self) {
return nil;
}
[self transitionToNextPhase];
return self;
}
- (void)dealloc {
if (_inputStream) {
[_inputStream close];
_inputStream = nil;
}
}
- (NSInputStream *)inputStream {
if (!_inputStream) {
if ([self.body isKindOfClass:[NSData class]]) {
_inputStream = [NSInputStream inputStreamWithData:self.body];
} else if ([self.body isKindOfClass:[NSURL class]]) {
_inputStream = [NSInputStream inputStreamWithURL:self.body];
} else if ([self.body isKindOfClass:[NSInputStream class]]) {
_inputStream = self.body;
} else {
_inputStream = [NSInputStream inputStreamWithData:[NSData data]];
}
}
return _inputStream;
}
- (NSString *)stringForHeaders {
NSMutableString *headerString = [NSMutableString string];
for (NSString *field in [self.headers allKeys]) {
[headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
}
[headerString appendString:kAFMultipartFormCRLF];
return [NSString stringWithString:headerString];
}
- (unsigned long long)contentLength {
unsigned long long length = 0;
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? HAIJIANPPMultipartFormInitialBoundary(self.boundary) : HAIJIANPPMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
length += [encapsulationBoundaryData length];
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
length += [headersData length];
length += _bodyContentLength;
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [HAIJIANPPMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
length += [closingBoundaryData length];
return length;
}
- (BOOL)hasBytesAvailable {
// Allows `read:maxLength:` to be called again if `HAIJIANPPMultipartFormFinalBoundary` doesn't fit into the available buffer
if (_phase == HAIJIANPPFinalBoundaryPhase) {
return YES;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcovered-switch-default"
switch (self.inputStream.streamStatus) {
case NSStreamStatusNotOpen:
case NSStreamStatusOpening:
case NSStreamStatusOpen:
case NSStreamStatusReading:
case NSStreamStatusWriting:
return YES;
case NSStreamStatusAtEnd:
case NSStreamStatusClosed:
case NSStreamStatusError:
default:
return NO;
}
#pragma clang diagnostic pop
}
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
NSInteger totalNumberOfBytesRead = 0;
if (_phase == HAIJIANPPEncapsulationBoundaryPhase) {
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? HAIJIANPPMultipartFormInitialBoundary(self.boundary) : HAIJIANPPMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
if (_phase == HAIJIANPPHeaderPhase) {
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
if (_phase == HAIJIANPPBodyPhase) {
NSInteger numberOfBytesRead = 0;
numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
if (numberOfBytesRead == -1) {
return -1;
} else {
totalNumberOfBytesRead += numberOfBytesRead;
if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
[self transitionToNextPhase];
}
}
}
if (_phase == HAIJIANPPFinalBoundaryPhase) {
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [HAIJIANPPMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
return totalNumberOfBytesRead;
}
- (NSInteger)readData:(NSData *)data
intoBuffer:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
[data getBytes:buffer range:range];
#pragma clang diagnostic pop
_phaseReadOffset += range.length;
if (((NSUInteger)_phaseReadOffset) >= [data length]) {
[self transitionToNextPhase];
}
return (NSInteger)range.length;
}
- (BOOL)transitionToNextPhase {
if (![[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self transitionToNextPhase];
});
return YES;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcovered-switch-default"
switch (_phase) {
case HAIJIANPPEncapsulationBoundaryPhase:
_phase = HAIJIANPPHeaderPhase;
break;
case HAIJIANPPHeaderPhase:
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self.inputStream open];
_phase = HAIJIANPPBodyPhase;
break;
case HAIJIANPPBodyPhase:
[self.inputStream close];
_phase = HAIJIANPPFinalBoundaryPhase;
break;
case HAIJIANPPFinalBoundaryPhase:
default:
_phase = HAIJIANPPEncapsulationBoundaryPhase;
break;
}
_phaseReadOffset = 0;
#pragma clang diagnostic pop
return YES;
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = self.headers;
bodyPart.bodyContentLength = self.bodyContentLength;
bodyPart.body = self.body;
bodyPart.boundary = self.boundary;
return bodyPart;
}
@end
#pragma mark -
@implementation HAIJIANPPJSONRequestSerializer
+ (instancetype)serializer {
return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
}
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
{
HAIJIANPPJSONRequestSerializer *serializer = [[self alloc] init];
serializer.writingOptions = writingOptions;
return serializer;
}
#pragma mark - HAIJIANPPURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPJSONRequestSerializer *serializer = [super copyWithZone:zone];
serializer.writingOptions = self.writingOptions;
return serializer;
}
@end
#pragma mark -
@implementation HAIJIANPPPropertyListRequestSerializer
+ (instancetype)serializer {
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0];
}
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
writeOptions:(NSPropertyListWriteOptions)writeOptions
{
HAIJIANPPPropertyListRequestSerializer *serializer = [[self alloc] init];
serializer.format = format;
serializer.writeOptions = writeOptions;
return serializer;
}
#pragma mark - HAIJIANPPURLRequestSerializer
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"];
}
[mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]];
}
return mutableRequest;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))];
[coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPPropertyListRequestSerializer *serializer = [super copyWithZone:zone];
serializer.format = self.format;
serializer.writeOptions = self.writeOptions;
return serializer;
}
@end
// HAIJIANPPURLResponseSerialization.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
/**
The `HAIJIANPPURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
*/
@protocol HAIJIANPPURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
/**
The response object decoded from the data associated with a specified response.
@param response The response to be processed.
@param data The response data to be decoded.
@param error The error that occurred while attempting to decode the response data.
@return The object decoded from the specified response data.
*/
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error;
@end
#pragma mark -
/**
`HAIJIANPPHTTPResponseSerializer` conforms to the `HAIJIANPPURLRequestSerialization` & `HAIJIANPPURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.
Any request or response serializer dealing with HTTP is encouraged to subclass `HAIJIANPPHTTPResponseSerializer` in order to ensure consistent default behavior.
*/
@interface HAIJIANPPHTTPResponseSerializer : NSObject <HAIJIANPPURLResponseSerialization>
- (instancetype) init;
/**
The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default.
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
Creates and returns a serializer with default configuration.
*/
+ (instancetype)serializer;
///-----------------------------------------
/// @name Configuring Response Serialization
///-----------------------------------------
/**
The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
*/
@property (nonatomic, copy) NSIndexSet *acceptableStatusCodes;
/**
The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation.
*/
@property (nonatomic, copy) NSSet *acceptableContentTypes;
/**
Validates the specified response and data.
In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks.
@param response The response to be validated.
@param data The data associated with the response.
@param error The error that occurred while attempting to validate the response.
@return `YES` if the response is valid, otherwise `NO`.
*/
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error;
@end
#pragma mark -
/**
`HAIJIANPPJSONResponseSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that validates and decodes JSON responses.
By default, `HAIJIANPPJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- `application/json`
- `text/json`
- `text/javascript`
*/
@interface HAIJIANPPJSONResponseSerializer : HAIJIANPPHTTPResponseSerializer
- (instancetype) init;
/**
Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
*/
@property (nonatomic, assign) NSJSONReadingOptions readingOptions;
/**
Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`.
*/
@property (nonatomic, assign) BOOL removesKeysWithNullValues;
/**
Creates and returns a JSON serializer with specified reading and writing options.
@param readingOptions The specified JSON reading options.
*/
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions;
@end
#pragma mark -
/**
`HAIJIANPPXMLParserResponseSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects.
By default, `HAIJIANPPXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
*/
@interface HAIJIANPPXMLParserResponseSerializer : HAIJIANPPHTTPResponseSerializer
@end
#pragma mark -
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
/**
`HAIJIANPPXMLDocumentResponseSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
By default, `HAIJIANPPXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
*/
@interface HAIJIANPPXMLDocumentResponseSerializer : HAIJIANPPHTTPResponseSerializer
- (instancetype) init;
/**
Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default.
*/
@property (nonatomic, assign) NSUInteger options;
/**
Creates and returns an XML document serializer with the specified options.
@param mask The XML document options.
*/
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask;
@end
#endif
#pragma mark -
/**
`HAIJIANPPPropertyListResponseSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects.
By default, `HAIJIANPPPropertyListResponseSerializer` accepts the following MIME types:
- `application/x-plist`
*/
@interface HAIJIANPPPropertyListResponseSerializer : HAIJIANPPHTTPResponseSerializer
- (instancetype) init;
/**
The property list format. Possible values are described in "NSPropertyListFormat".
*/
@property (nonatomic, assign) NSPropertyListFormat format;
/**
The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions."
*/
@property (nonatomic, assign) NSPropertyListReadOptions readOptions;
/**
Creates and returns a property list serializer with a specified format, read options, and write options.
@param format The property list format.
@param readOptions The property list reading options.
*/
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
readOptions:(NSPropertyListReadOptions)readOptions;
@end
#pragma mark -
/**
`HAIJIANPPImageResponseSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that validates and decodes image responses.
By default, `HAIJIANPPImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
- `image/tiff`
- `image/jpeg`
- `image/gif`
- `image/png`
- `image/ico`
- `image/x-icon`
- `image/bmp`
- `image/x-bmp`
- `image/x-xbitmap`
- `image/x-win-bitmap`
*/
@interface HAIJIANPPImageResponseSerializer : HAIJIANPPHTTPResponseSerializer
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
/**
The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
*/
@property (nonatomic, assign) CGFloat imageScale;
/**
Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default.
*/
@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage;
#endif
@end
#pragma mark -
/**
`HAIJIANPPCompoundSerializer` is a subclass of `HAIJIANPPHTTPResponseSerializer` that delegates the response serialization to the first `HAIJIANPPHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `HAIJIANPPHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer.
*/
@interface HAIJIANPPCompoundResponseSerializer : HAIJIANPPHTTPResponseSerializer
/**
The component response serializers.
*/
@property (readonly, nonatomic, copy) NSArray *responseSerializers;
/**
Creates and returns a compound serializer comprised of the specified response serializers.
@warning Each response serializer specified must be a subclass of `HAIJIANPPHTTPResponseSerializer`, and response to `-validateResponse:data:error:`.
*/
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers;
@end
///----------------
/// @name Constants
///----------------
/**
## Error Domains
The following error domain is predefined.
- `NSString * const HAIJIANPPURLResponseSerializationErrorDomain`
### Constants
`HAIJIANPPURLResponseSerializationErrorDomain`
HAIJIANPPURLResponseSerializer errors. Error codes for `HAIJIANPPURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
extern NSString * const HAIJIANPPURLResponseSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const HAIJIANPPNetworkingOperationFailingURLResponseErrorKey`
- `NSString * const HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey`
### Constants
`HAIJIANPPNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `HAIJIANPPURLResponseSerializationErrorDomain`.
`HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey`
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `HAIJIANPPURLResponseSerializationErrorDomain`.
*/
extern NSString * const HAIJIANPPNetworkingOperationFailingURLResponseErrorKey;
extern NSString * const HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey;
// HAIJIANPPURLResponseSerialization.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPURLResponseSerialization.h"
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <UIKit/UIKit.h>
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#import <Cocoa/Cocoa.h>
#endif
NSString * const HAIJIANPPURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
NSString * const HAIJIANPPNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
NSString * const HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
static NSError * HAIJIANPPErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
if (!error) {
return underlyingError;
}
if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
return error;
}
NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
}
static BOOL HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
if ([error.domain isEqualToString:domain] && error.code == code) {
return YES;
} else if (error.userInfo[NSUnderlyingErrorKey]) {
return HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
}
return NO;
}
static id HAIJIANPPJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
if ([JSONObject isKindOfClass:[NSArray class]]) {
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
for (id value in (NSArray *)JSONObject) {
[mutableArray addObject:HAIJIANPPJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
} else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
id value = [(NSDictionary *)JSONObject objectForKey:key];
if (!value || [value isEqual:[NSNull null]]) {
[mutableDictionary removeObjectForKey:key];
} else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
[mutableDictionary setObject:HAIJIANPPJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key];
}
}
return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
return JSONObject;
}
@implementation HAIJIANPPHTTPResponseSerializer
+ (instancetype)serializer {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = NSUTF8StringEncoding;
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
self.acceptableContentTypes = nil;
return self;
}
#pragma mark -
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError * __autoreleasing *)error
{
BOOL responseIsValid = YES;
NSError *validationError = nil;
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
if ([data length] > 0 && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"HAIJIANPPNetworking", nil), [response MIMEType]],
NSURLErrorFailingURLErrorKey:[response URL],
HAIJIANPPNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = HAIJIANPPErrorWithUnderlyingError([NSError errorWithDomain:HAIJIANPPURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
}
responseIsValid = NO;
}
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"HAIJIANPPNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
NSURLErrorFailingURLErrorKey:[response URL],
HAIJIANPPNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[HAIJIANPPNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = HAIJIANPPErrorWithUnderlyingError([NSError errorWithDomain:HAIJIANPPURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
responseIsValid = NO;
}
}
if (error && !responseIsValid) {
*error = validationError;
}
return responseIsValid;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
[self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
return data;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
[coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
return serializer;
}
@end
#pragma mark -
@implementation HAIJIANPPJSONResponseSerializer
+ (instancetype)serializer {
return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
}
+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
HAIJIANPPJSONResponseSerializer *serializer = [[self alloc] init];
serializer.readingOptions = readingOptions;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
return self;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, HAIJIANPPURLResponseSerializationErrorDomain)) {
return nil;
}
}
// Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization.
// See https://github.com/rails/rails/issues/1742
NSStringEncoding stringEncoding = self.stringEncoding;
if (response.textEncodingName) {
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
}
id responseObject = nil;
NSError *serializationError = nil;
@autoreleasepool {
NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (responseString && ![responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
if (data) {
if ([data length] > 0) {
responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
} else {
return nil;
}
} else {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"HAIJIANPPNetworking", nil),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"HAIJIANPPNetworking", nil), responseString]
};
serializationError = [NSError errorWithDomain:HAIJIANPPURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
}
}
if (self.removesKeysWithNullValues && responseObject) {
responseObject = HAIJIANPPJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
}
if (error) {
*error = HAIJIANPPErrorWithUnderlyingError(serializationError, *error);
}
return responseObject;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
[coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.readingOptions = self.readingOptions;
serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
return serializer;
}
@end
#pragma mark -
@implementation HAIJIANPPXMLParserResponseSerializer
+ (instancetype)serializer {
HAIJIANPPXMLParserResponseSerializer *serializer = [[self alloc] init];
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
return self;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, HAIJIANPPURLResponseSerializationErrorDomain)) {
return nil;
}
}
return [[NSXMLParser alloc] initWithData:data];
}
@end
#pragma mark -
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
@implementation HAIJIANPPXMLDocumentResponseSerializer
+ (instancetype)serializer {
return [self serializerWithXMLDocumentOptions:0];
}
+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
HAIJIANPPXMLDocumentResponseSerializer *serializer = [[self alloc] init];
serializer.options = mask;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
return self;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, HAIJIANPPURLResponseSerializationErrorDomain)) {
return nil;
}
}
NSError *serializationError = nil;
NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
if (error) {
*error = HAIJIANPPErrorWithUnderlyingError(serializationError, *error);
}
return document;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.options = self.options;
return serializer;
}
@end
#endif
#pragma mark -
@implementation HAIJIANPPPropertyListResponseSerializer
+ (instancetype)serializer {
return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
}
+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format
readOptions:(NSPropertyListReadOptions)readOptions
{
HAIJIANPPPropertyListResponseSerializer *serializer = [[self alloc] init];
serializer.format = format;
serializer.readOptions = readOptions;
return serializer;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
return self;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, HAIJIANPPURLResponseSerializationErrorDomain)) {
return nil;
}
}
id responseObject;
NSError *serializationError = nil;
if (data) {
responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
}
if (error) {
*error = HAIJIANPPErrorWithUnderlyingError(serializationError, *error);
}
return responseObject;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
[coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.format = self.format;
serializer.readOptions = self.readOptions;
return serializer;
}
@end
#pragma mark -
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#import <CoreGraphics/CoreGraphics.h>
static UIImage * HAIJIANPPImageWithDataAtScale(NSData *data, CGFloat scale) {
UIImage *image = [[UIImage alloc] initWithData:data];
if (image.images) {
return image;
}
return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
}
static UIImage * HAIJIANPPInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
if (!data || [data length] == 0) {
return nil;
}
CGImageRef imageRef = NULL;
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if ([response.MIMEType isEqualToString:@"image/png"]) {
imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
} else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
if (imageRef) {
CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
// CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to HAIJIANPPImageWithDataAtScale
if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
CGImageRelease(imageRef);
imageRef = NULL;
}
}
}
CGDataProviderRelease(dataProvider);
UIImage *image = HAIJIANPPImageWithDataAtScale(data, scale);
if (!imageRef) {
if (image.images || !image) {
return image;
}
imageRef = CGImageCreateCopy([image CGImage]);
if (!imageRef) {
return nil;
}
}
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
CGImageRelease(imageRef);
return image;
}
// CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
size_t bytesPerRow = 0;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (colorSpaceModel == kCGColorSpaceModelRGB) {
uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wassign-enum"
if (alpha == kCGImageAlphaNone) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
} else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
}
#pragma clang diagnostic pop
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
if (!context) {
CGImageRelease(imageRef);
return image;
}
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
CGImageRelease(inflatedImageRef);
CGImageRelease(imageRef);
return inflatedImage;
}
#endif
@implementation HAIJIANPPImageResponseSerializer
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
self.imageScale = [[UIScreen mainScreen] scale];
self.automaticallyInflatesResponseImage = YES;
#endif
return self;
}
#pragma mark - HAIJIANPPURLResponseSerializer
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
if (!error || HAIJIANPPErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, HAIJIANPPURLResponseSerializationErrorDomain)) {
return nil;
}
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
if (self.automaticallyInflatesResponseImage) {
return HAIJIANPPInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
} else {
return HAIJIANPPImageWithDataAtScale(data, self.imageScale);
}
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
// Ensure that the image is set to it's correct pixel width and height
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
[image addRepresentation:bitimage];
return image;
#endif
return nil;
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
#if CGFLOAT_IS_DOUBLE
self.imageScale = [imageScale doubleValue];
#else
self.imageScale = [imageScale floatValue];
#endif
self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
#endif
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
[coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
[coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
#endif
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
serializer.imageScale = self.imageScale;
serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
#endif
return serializer;
}
@end
#pragma mark -
@interface HAIJIANPPCompoundResponseSerializer ()
@property (readwrite, nonatomic, copy) NSArray *responseSerializers;
@end
@implementation HAIJIANPPCompoundResponseSerializer
+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
HAIJIANPPCompoundResponseSerializer *serializer = [[self alloc] init];
serializer.responseSerializers = responseSerializers;
return serializer;
}
#pragma mark - HAIJIANPPURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
for (id <HAIJIANPPURLResponseSerialization> serializer in self.responseSerializers) {
if (![serializer isKindOfClass:[HAIJIANPPHTTPResponseSerializer class]]) {
continue;
}
NSError *serializerError = nil;
id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
if (responseObject) {
if (error) {
*error = HAIJIANPPErrorWithUnderlyingError(serializerError, *error);
}
return responseObject;
}
}
return [super responseObjectForResponse:response data:data error:error];
}
#pragma mark - NSSecureCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
HAIJIANPPCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
serializer.responseSerializers = self.responseSerializers;
return serializer;
}
@end
// HAIJIANPPURLSessionManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "HAIJIANPPURLResponseSerialization.h"
#import "HAIJIANPPURLRequestSerialization.h"
#import "HAIJIANPPSecurityPolicy.h"
#import "HAIJIANPPNetworkReachabilityManager.h"
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
/**
`HAIJIANPPURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
## Subclassing Notes
This is the base class for `HAIJIANPPHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `HAIJIANPPURLSessionManager` specifically for HTTP, consider subclassing `HAIJIANPPHTTPSessionManager` instead.
## NSURLSession & NSURLSessionTask Delegate Methods
`HAIJIANPPURLSessionManager` implements the following delegate methods:
### `NSURLSessionDelegate`
- `URLSession:didBecomeInvalidWithError:`
- `URLSession:didReceiveChallenge:completionHandler:`
- `URLSessionDidFinishEventsForBackgroundURLSession:`
### `NSURLSessionTaskDelegate`
- `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
- `URLSession:task:didReceiveChallenge:completionHandler:`
- `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
- `URLSession:task:didCompleteWithError:`
### `NSURLSessionDataDelegate`
- `URLSession:dataTask:didReceiveResponse:completionHandler:`
- `URLSession:dataTask:didBecomeDownloadTask:`
- `URLSession:dataTask:didReceiveData:`
- `URLSession:dataTask:willCacheResponse:completionHandler:`
### `NSURLSessionDownloadDelegate`
- `URLSession:downloadTask:didFinishDownloadingToURL:`
- `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`
- `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
## Network Reachability Monitoring
Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `HAIJIANPPNetworkReachabilityManager` for more details.
## NSCoding Caveats
- Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
## NSCopying Caveats
- `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
- Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
@warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
*/
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
@interface HAIJIANPPURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
/**
The managed session.
*/
@property (readonly, nonatomic, strong) NSURLSession *session;
/**
The operation queue on which delegate callbacks are run.
*/
@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
/**
Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `HAIJIANPPJSONResponseSerializer`.
@warning `responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) id <HAIJIANPPURLResponseSerialization> responseSerializer;
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The security policy used by created request operations to evaluate server trust for secure connections. `HAIJIANPPURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
*/
@property (nonatomic, strong) HAIJIANPPSecurityPolicy *securityPolicy;
///--------------------------------------
/// @name Monitoring Network Reachability
///--------------------------------------
/**
The network reachability manager. `HAIJIANPPURLSessionManager` uses the `sharedManager` by default.
*/
@property (readwrite, nonatomic, strong) HAIJIANPPNetworkReachabilityManager *reachabilityManager;
///----------------------------
/// @name Getting Session Tasks
///----------------------------
/**
The data, upload, and download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *tasks;
/**
The data tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *dataTasks;
/**
The upload tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *uploadTasks;
/**
The download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *downloadTasks;
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_queue_t completionQueue;
#else
@property (nonatomic, assign) dispatch_queue_t completionQueue;
#endif
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
#if OS_OBJECT_HAVE_OBJC_SUPPORT
@property (nonatomic, strong) dispatch_group_t completionGroup;
#else
@property (nonatomic, assign) dispatch_group_t completionGroup;
#endif
///---------------------------------
/// @name Working Around System Bugs
///---------------------------------
/**
Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
@bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, HAIJIANPPNetworking will follow Apple's recommendation to try creating the task again.
@see https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/issues/1675
*/
@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
@param configuration The configuration used to create the managed session.
@return A manager for a newly-created session.
*/
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
/**
Invalidates the managed session, optionally canceling pending tasks.
@param cancelPendingTasks Whether or not to cancel pending tasks.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
///-------------------------
/// @name Running Data Tasks
///-------------------------
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
///---------------------------
/// @name Running Upload Tasks
///---------------------------
/**
Creates an `NSURLSessionUploadTask` with the specified request for a local file.
@param request The HTTP request for the request.
@param fileURL A URL to the local file to be uploaded.
@param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
@see `attemptsToRecreateUploadTasksForBackgroundSessions`
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
@param request The HTTP request for the request.
@param bodyData A data object containing the HTTP body to be uploaded.
@param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified streaming request.
@param request The HTTP request for the request.
@param progress A progress object monitoring the current upload progress.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
///-----------------------------
/// @name Running Download Tasks
///-----------------------------
/**
Creates an `NSURLSessionDownloadTask` with the specified request.
@param request The HTTP request for the request.
@param progress A progress object monitoring the current download progress.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
@warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
/**
Creates an `NSURLSessionDownloadTask` with the specified resume data.
@param resumeData The data used to resume downloading.
@param progress A progress object monitoring the current download progress.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
///---------------------------------
/// @name Getting Progress for Tasks
///---------------------------------
/**
Returns the upload progress of the specified task.
@param uploadTask The session upload task. Must not be `nil`.
@return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
*/
- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask;
/**
Returns the download progress of the specified task.
@param downloadTask The session download task. Must not be `nil`.
@return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
*/
- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask;
///-----------------------------------------
/// @name Setting Session Delegate Callbacks
///-----------------------------------------
/**
Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
@param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
*/
- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block;
/**
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
///--------------------------------------
/// @name Setting Task Delegate Callbacks
///--------------------------------------
/**
Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
@param block A block object to be executed when a task requires a new request body stream.
*/
- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
/**
Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
@param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
*/
- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
/**
Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/
- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
/**
Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
*/
- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
/**
Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
*/
- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block;
///-------------------------------------------
/// @name Setting Data Task Delegate Callbacks
///-------------------------------------------
/**
Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
@param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
*/
- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
/**
Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
@param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
*/
- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
/**
Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
*/
- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
/**
Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
@param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
*/
- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
/**
Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
@param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
*/
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block;
///-----------------------------------------------
/// @name Setting Download Task Delegate Callbacks
///-----------------------------------------------
/**
Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
@param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `HAIJIANPPURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
*/
- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
/**
Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
*/
- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
/**
Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
@param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
*/
- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
@end
#endif
///--------------------
/// @name Notifications
///--------------------
/**
Posted when a task begins executing.
@deprecated Use `HAIJIANPPNetworkingTaskDidResumeNotification` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE;
/**
Posted when a task resumes.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidResumeNotification;
/**
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteNotification` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE;
/**
Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteNotification;
/**
Posted when a task suspends its execution.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidSuspendNotification;
/**
Posted when a session is invalidated.
*/
extern NSString * const HAIJIANPPURLSessionDidInvalidateNotification;
/**
Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
*/
extern NSString * const HAIJIANPPURLSessionDownloadTaskDidFailToMoveFileNotification;
/**
The raw response data of the task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if response data exists for the task.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteResponseDataKey` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE;
/**
The raw response data of the task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if response data exists for the task.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteResponseDataKey;
/**
The serialized response object of the task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if the response was serialized.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteSerializedResponseKey` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE;
/**
The serialized response object of the task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if the response was serialized.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteSerializedResponseKey;
/**
The response serializer used to serialize the response. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if the task has an associated response serializer.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteResponseSerializerKey` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE;
/**
The response serializer used to serialize the response. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if the task has an associated response serializer.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteResponseSerializerKey;
/**
The file path associated with the download task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteAssetPathKey` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE;
/**
The file path associated with the download task. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteAssetPathKey;
/**
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if an error exists.
@deprecated Use `HAIJIANPPNetworkingTaskDidCompleteErrorKey` instead.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE;
/**
Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `HAIJIANPPNetworkingTaskDidFinishNotification` if an error exists.
*/
extern NSString * const HAIJIANPPNetworkingTaskDidCompleteErrorKey;
// HAIJIANPPURLSessionManager.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "HAIJIANPPURLSessionManager.h"
#import <objc/runtime.h>
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
static dispatch_queue_t url_session_manager_creation_queue() {
static dispatch_queue_t af_url_session_manager_creation_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
});
return af_url_session_manager_creation_queue;
}
static dispatch_queue_t url_session_manager_processing_queue() {
static dispatch_queue_t af_url_session_manager_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_url_session_manager_processing_queue;
}
static dispatch_group_t url_session_manager_completion_group() {
static dispatch_group_t af_url_session_manager_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_completion_group = dispatch_group_create();
});
return af_url_session_manager_completion_group;
}
NSString * const HAIJIANPPNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
NSString * const HAIJIANPPNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
NSString * const HAIJIANPPNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
NSString * const HAIJIANPPURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const HAIJIANPPURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
NSString * const HAIJIANPPNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
NSString * const HAIJIANPPNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
NSString * const HAIJIANPPNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
NSString * const HAIJIANPPNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
NSString * const HAIJIANPPNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
NSString * const HAIJIANPPNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated
NSString * const HAIJIANPPNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated
static NSString * const HAIJIANPPURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
static NSUInteger const HAIJIANPPMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
static void * HAIJIANPPTaskStateChangedContext = &HAIJIANPPTaskStateChangedContext;
typedef void (^HAIJIANPPURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
typedef NSURLSessionAuthChallengeDisposition (^HAIJIANPPURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
typedef NSURLRequest * (^HAIJIANPPURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
typedef NSURLSessionAuthChallengeDisposition (^HAIJIANPPURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
typedef void (^HAIJIANPPURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
typedef NSInputStream * (^HAIJIANPPURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
typedef void (^HAIJIANPPURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
typedef void (^HAIJIANPPURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
typedef NSURLSessionResponseDisposition (^HAIJIANPPURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
typedef void (^HAIJIANPPURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
typedef void (^HAIJIANPPURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
typedef NSCachedURLResponse * (^HAIJIANPPURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
typedef NSURL * (^HAIJIANPPURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
typedef void (^HAIJIANPPURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
typedef void (^HAIJIANPPURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
typedef void (^HAIJIANPPURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
#pragma mark -
@interface HAIJIANPPURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@property (nonatomic, weak) HAIJIANPPURLSessionManager *manager;
@property (nonatomic, strong) NSMutableData *mutableData;
@property (nonatomic, strong) NSProgress *progress;
@property (nonatomic, copy) NSURL *downloadFileURL;
@property (nonatomic, copy) HAIJIANPPURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (nonatomic, copy) HAIJIANPPURLSessionTaskCompletionHandler completionHandler;
@end
@implementation HAIJIANPPURLSessionManagerTaskDelegate
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.mutableData = [NSMutableData data];
self.progress = [NSProgress progressWithTotalUnitCount:0];
return self;
}
#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(__unused NSURLSession *)session
task:(__unused NSURLSessionTask *)task
didSendBodyData:(__unused int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
self.progress.totalUnitCount = totalBytesExpectedToSend;
self.progress.completedUnitCount = totalBytesSent;
}
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong HAIJIANPPURLSessionManager *manager = self.manager;
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[HAIJIANPPNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
if (self.downloadFileURL) {
userInfo[HAIJIANPPNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (self.mutableData) {
userInfo[HAIJIANPPNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData];
}
if (error) {
userInfo[HAIJIANPPNetworkingTaskDidCompleteErrorKey] = error;
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
} else {
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError];
if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
}
if (responseObject) {
userInfo[HAIJIANPPNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
}
if (serializationError) {
userInfo[HAIJIANPPNetworkingTaskDidCompleteErrorKey] = serializationError;
}
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
#pragma clang diagnostic pop
}
#pragma mark - NSURLSessionDataTaskDelegate
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
[self.mutableData appendData:data];
}
#pragma mark - NSURLSessionDownloadTaskDelegate
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
NSError *fileManagerError = nil;
self.downloadFileURL = nil;
if (self.downloadTaskDidFinishDownloading) {
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) {
[[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
if (fileManagerError) {
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
}
}
}
}
- (void)URLSession:(__unused NSURLSession *)session
downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
didWriteData:(__unused int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
self.progress.totalUnitCount = totalBytesExpectedToWrite;
self.progress.completedUnitCount = totalBytesWritten;
}
- (void)URLSession:(__unused NSURLSession *)session
downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
self.progress.totalUnitCount = expectedTotalBytes;
self.progress.completedUnitCount = fileOffset;
}
@end
#pragma mark -
/**
* A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`.
*
* See:
* - https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/issues/1477
* - https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/issues/2638
* - https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/pull/2702
*/
static inline void af_swizzleSelector(Class class, SEL originalSelector, SEL swizzledSelector) {
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
}
static inline BOOL af_addMethod(Class class, SEL selector, Method method) {
return class_addMethod(class, selector, method_getImplementation(method), method_getTypeEncoding(method));
}
static NSString * const HAIJIANPPNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume";
static NSString * const HAIJIANPPNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";
@interface _HAIJIANPPURLSessionTaskSwizzling : NSObject
@end
@implementation _HAIJIANPPURLSessionTaskSwizzling
+ (void)load {
/**
WARNING: Trouble Ahead
https://github.com/HAIJIANPPNetworking/HAIJIANPPNetworking/pull/2702
*/
if (NSClassFromString(@"NSURLSessionTask")) {
/**
iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky.
Many Unit Tests have been built to validate as much of this behavior has possible.
Here is what we know:
- NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back.
- Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there.
- On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`.
- On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`.
- On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled.
- On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled.
- Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there.
Some Assumptions:
- No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it.
- No background task classes override `resume` or `suspend`
The current solution:
1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task.
2) Grab a pointer to the original implementation of `af_resume`
3) Check to see if the current class has an implementation of resume. If so, continue to step 4.
4) Grab the super class of the current class.
5) Grab a pointer for the current class to the current implementation of `resume`.
6) Grab a pointer for the super class to the current implementation of `resume`.
7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods
8) Set the current class to the super class, and repeat steps 3-8
*/
NSURLSessionDataTask *localDataTask = [[NSURLSession sessionWithConfiguration:nil] dataTaskWithURL:nil];
IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([_HAIJIANPPURLSessionTaskSwizzling class], @selector(af_resume)));
Class currentClass = [localDataTask class];
while (class_getInstanceMethod(currentClass, @selector(resume))) {
Class superClass = [currentClass superclass];
IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume)));
IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume)));
if (classResumeIMP != superclassResumeIMP &&
originalAFResumeIMP != classResumeIMP) {
[self swizzleResumeAndSuspendMethodForClass:currentClass];
}
currentClass = [currentClass superclass];
}
[localDataTask cancel];
}
}
+ (void)swizzleResumeAndSuspendMethodForClass:(Class)class {
Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume));
Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend));
af_addMethod(class, @selector(af_resume), afResumeMethod);
af_addMethod(class, @selector(af_suspend), afSuspendMethod);
af_swizzleSelector(class, @selector(resume), @selector(af_resume));
af_swizzleSelector(class, @selector(suspend), @selector(af_suspend));
}
- (NSURLSessionTaskState)state {
NSAssert(NO, @"State method should never be called in the actual dummy class");
return NSURLSessionTaskStateCanceling;
}
- (void)af_resume {
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_resume];
if (state != NSURLSessionTaskStateRunning) {
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNSURLSessionTaskDidResumeNotification object:self];
}
}
- (void)af_suspend {
NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
NSURLSessionTaskState state = [self state];
[self af_suspend];
if (state != NSURLSessionTaskStateSuspended) {
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNSURLSessionTaskDidSuspendNotification object:self];
}
}
@end
#pragma mark -
@interface HAIJIANPPURLSessionManager ()
@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
@property (readwrite, nonatomic, strong) NSURLSession *session;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks;
@property (readwrite, nonatomic, strong) NSLock *lock;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionTaskDidCompleteBlock taskDidComplete;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
@property (readwrite, nonatomic, copy) HAIJIANPPURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
@end
@implementation HAIJIANPPURLSessionManager
- (instancetype)init {
return [self initWithSessionConfiguration:nil];
}
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
self = [super init];
if (!self) {
return nil;
}
if (!configuration) {
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
}
self.sessionConfiguration = configuration;
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
self.responseSerializer = [HAIJIANPPJSONResponseSerializer serializer];
self.securityPolicy = [HAIJIANPPSecurityPolicy defaultPolicy];
self.reachabilityManager = [HAIJIANPPNetworkReachabilityManager sharedManager];
self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
self.lock = [[NSLock alloc] init];
self.lock.name = HAIJIANPPURLSessionManagerLockName;
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
for (NSURLSessionDataTask *task in dataTasks) {
[self addDelegateForDataTask:task completionHandler:nil];
}
for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
[self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
}
for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
[self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
}
}];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:HAIJIANPPNSURLSessionTaskDidResumeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:HAIJIANPPNSURLSessionTaskDidSuspendNotification object:nil];
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark -
- (NSString *)taskDescriptionForSessionTasks {
return [NSString stringWithFormat:@"%p", self];
}
- (void)taskDidResume:(NSNotification *)notification {
NSURLSessionTask *task = notification.object;
if ([task respondsToSelector:@selector(taskDescription)]) {
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingTaskDidResumeNotification object:task];
});
}
}
}
- (void)taskDidSuspend:(NSNotification *)notification {
NSURLSessionTask *task = notification.object;
if ([task respondsToSelector:@selector(taskDescription)]) {
if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPNetworkingTaskDidSuspendNotification object:task];
});
}
}
}
#pragma mark -
- (HAIJIANPPURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
NSParameterAssert(task);
HAIJIANPPURLSessionManagerTaskDelegate *delegate = nil;
[self.lock lock];
delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
[self.lock unlock];
return delegate;
}
- (void)setDelegate:(HAIJIANPPURLSessionManagerTaskDelegate *)delegate
forTask:(NSURLSessionTask *)task
{
NSParameterAssert(task);
NSParameterAssert(delegate);
[self.lock lock];
self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
[self.lock unlock];
}
- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [[HAIJIANPPURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler;
dataTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:dataTask];
}
- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [[HAIJIANPPURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler;
int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend;
if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"];
if(contentLength) {
totalUnitCount = (int64_t)[contentLength longLongValue];
}
}
if (delegate.progress) {
delegate.progress.totalUnitCount = totalUnitCount;
} else {
delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount];
}
delegate.progress.pausingHandler = ^{
[uploadTask suspend];
};
delegate.progress.cancellationHandler = ^{
[uploadTask cancel];
};
if (progress) {
*progress = delegate.progress;
}
uploadTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:uploadTask];
}
- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [[HAIJIANPPURLSessionManagerTaskDelegate alloc] init];
delegate.manager = self;
delegate.completionHandler = completionHandler;
if (destination) {
delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
return destination(location, task.response);
};
}
if (progress) {
*progress = delegate.progress;
}
downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
[self setDelegate:delegate forTask:downloadTask];
}
- (void)removeDelegateForTask:(NSURLSessionTask *)task {
NSParameterAssert(task);
[self.lock lock];
[self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
[self.lock unlock];
}
- (void)removeAllDelegates {
[self.lock lock];
[self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects];
[self.lock unlock];
}
#pragma mark -
- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
__block NSArray *tasks = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
tasks = dataTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
tasks = uploadTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
tasks = downloadTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return tasks;
}
- (NSArray *)tasks {
return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}
- (NSArray *)dataTasks {
return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}
- (NSArray *)uploadTasks {
return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}
- (NSArray *)downloadTasks {
return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
}
#pragma mark -
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
dispatch_async(dispatch_get_main_queue(), ^{
if (cancelPendingTasks) {
[self.session invalidateAndCancel];
} else {
[self.session finishTasksAndInvalidate];
}
});
}
#pragma mark -
- (void)setResponseSerializer:(id <HAIJIANPPURLResponseSerialization>)responseSerializer {
NSParameterAssert(responseSerializer);
_responseSerializer = responseSerializer;
}
#pragma mark -
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionDataTask *dataTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
dataTask = [self.session dataTaskWithRequest:request];
});
[self addDelegateForDataTask:dataTask completionHandler:completionHandler];
return dataTask;
}
#pragma mark -
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionUploadTask *uploadTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
});
if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
for (NSUInteger attempts = 0; !uploadTask && attempts < HAIJIANPPMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
}
}
[self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask;
}
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionUploadTask *uploadTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
});
[self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask;
}
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionUploadTask *uploadTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
uploadTask = [self.session uploadTaskWithStreamedRequest:request];
});
[self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler];
return uploadTask;
}
#pragma mark -
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
__block NSURLSessionDownloadTask *downloadTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
downloadTask = [self.session downloadTaskWithRequest:request];
});
[self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
return downloadTask;
}
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
__block NSURLSessionDownloadTask *downloadTask = nil;
dispatch_sync(url_session_manager_creation_queue(), ^{
downloadTask = [self.session downloadTaskWithResumeData:resumeData];
});
[self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler];
return downloadTask;
}
#pragma mark -
- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask {
return [[self delegateForTask:uploadTask] progress];
}
- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask {
return [[self delegateForTask:downloadTask] progress];
}
#pragma mark -
- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
self.sessionDidBecomeInvalid = block;
}
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
self.sessionDidReceiveAuthenticationChallenge = block;
}
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
self.didFinishEventsForBackgroundURLSession = block;
}
#pragma mark -
- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block {
self.taskNeedNewBodyStream = block;
}
- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
self.taskWillPerformHTTPRedirection = block;
}
- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
self.taskDidReceiveAuthenticationChallenge = block;
}
- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
self.taskDidSendBodyData = block;
}
- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
self.taskDidComplete = block;
}
#pragma mark -
- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
self.dataTaskDidReceiveResponse = block;
}
- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
self.dataTaskDidBecomeDownloadTask = block;
}
- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
self.dataTaskDidReceiveData = block;
}
- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
self.dataTaskWillCacheResponse = block;
}
#pragma mark -
- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
self.downloadTaskDidFinishDownloading = block;
}
- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
self.downloadTaskDidWriteData = block;
}
- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
self.downloadTaskDidResume = block;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
}
- (BOOL)respondsToSelector:(SEL)selector {
if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) {
return self.taskWillPerformHTTPRedirection != nil;
} else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
return self.dataTaskDidReceiveResponse != nil;
} else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
return self.dataTaskWillCacheResponse != nil;
} else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
return self.didFinishEventsForBackgroundURLSession != nil;
}
return [[self class] instancesRespondToSelector:selector];
}
#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session
didBecomeInvalidWithError:(NSError *)error
{
if (self.sessionDidBecomeInvalid) {
self.sessionDidBecomeInvalid(session, error);
}
[self removeAllDelegates];
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPURLSessionDidInvalidateNotification object:session];
}
- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
if (self.sessionDidReceiveAuthenticationChallenge) {
disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
} else {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
if (credential) {
disposition = NSURLSessionAuthChallengeUseCredential;
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
}
if (completionHandler) {
completionHandler(disposition, credential);
}
}
#pragma mark - NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest *))completionHandler
{
NSURLRequest *redirectRequest = request;
if (self.taskWillPerformHTTPRedirection) {
redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
}
if (completionHandler) {
completionHandler(redirectRequest);
}
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
if (self.taskDidReceiveAuthenticationChallenge) {
disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
} else {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
disposition = NSURLSessionAuthChallengeUseCredential;
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
}
if (completionHandler) {
completionHandler(disposition, credential);
}
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
{
NSInputStream *inputStream = nil;
if (self.taskNeedNewBodyStream) {
inputStream = self.taskNeedNewBodyStream(session, task);
} else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
inputStream = [task.originalRequest.HTTPBodyStream copy];
}
if (completionHandler) {
completionHandler(inputStream);
}
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
int64_t totalUnitCount = totalBytesExpectedToSend;
if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"];
if(contentLength) {
totalUnitCount = (int64_t) [contentLength longLongValue];
}
}
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
[delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount];
if (self.taskDidSendBodyData) {
self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
}
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
// delegate may be nil when completing a task in the background
if (delegate) {
[delegate URLSession:session task:task didCompleteWithError:error];
[self removeDelegateForTask:task];
}
if (self.taskDidComplete) {
self.taskDidComplete(session, task, error);
}
}
#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
if (self.dataTaskDidReceiveResponse) {
disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
}
if (completionHandler) {
completionHandler(disposition);
}
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
if (delegate) {
[self removeDelegateForTask:dataTask];
[self setDelegate:delegate forTask:downloadTask];
}
if (self.dataTaskDidBecomeDownloadTask) {
self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
}
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
[delegate URLSession:session dataTask:dataTask didReceiveData:data];
if (self.dataTaskDidReceiveData) {
self.dataTaskDidReceiveData(session, dataTask, data);
}
}
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
{
NSCachedURLResponse *cachedResponse = proposedResponse;
if (self.dataTaskWillCacheResponse) {
cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
}
if (completionHandler) {
completionHandler(cachedResponse);
}
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
if (self.didFinishEventsForBackgroundURLSession) {
dispatch_async(dispatch_get_main_queue(), ^{
self.didFinishEventsForBackgroundURLSession(session);
});
}
}
#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
if (self.downloadTaskDidFinishDownloading) {
NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (fileURL) {
delegate.downloadFileURL = fileURL;
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
if (error) {
[[NSNotificationCenter defaultCenter] postNotificationName:HAIJIANPPURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
}
return;
}
}
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
}
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
if (self.downloadTaskDidWriteData) {
self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
HAIJIANPPURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
[delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes];
if (self.downloadTaskDidResume) {
self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
}
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder {
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
self = [self initWithSessionConfiguration:configuration];
if (!self) {
return nil;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
}
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone {
return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
}
@end
#endif
// UIImageView+AFNetworking.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class HAIJIANPPAFImageDownloader;
/**
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.
*/
@interface UIImageView (HAIJIANPPAFNetworking)
///------------------------------------
/// @name Accessing the Image Downloader
///------------------------------------
/**
Set the shared image downloader used to download images.
@param imageDownloader The shared image downloader used to download images.
*/
+ (void)setSharedImageDownloader:(HAIJIANPPAFImageDownloader *)imageDownloader;
/**
The shared image downloader used to download images.
*/
+ (HAIJIANPPAFImageDownloader *)sharedImageDownloader;
///--------------------
/// @name Setting Image
///--------------------
/**
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
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.
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
*/
- (void)setImageWithURL:(NSURL *)url;
/**
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
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.
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
@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.
*/
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage;
/**
Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
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.
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
@param urlRequest The URL request used for the image request.
@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.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Cancels any executing image operation for the receiver, if one exists.
*/
- (void)cancelImageDownloadTask;
@end
NS_ASSUME_NONNULL_END
#endif
// UIImageView+AFNetworking.m
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIImageView+HAIJIANPPAFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "HAIJIANPPAFImageDownloader.h"
@interface UIImageView (_HAIJIANPPAFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) HAIJIANPPAFImageDownloadReceipt *af_activeImageDownloadReceipt;
@end
@implementation UIImageView (_HAIJIANPPAFNetworking)
- (HAIJIANPPAFImageDownloadReceipt *)af_activeImageDownloadReceipt {
return (HAIJIANPPAFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
}
- (void)af_setActiveImageDownloadReceipt:(HAIJIANPPAFImageDownloadReceipt *)imageDownloadReceipt {
objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation UIImageView (HAIJIANPPAFNetworking)
+ (HAIJIANPPAFImageDownloader *)sharedImageDownloader {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [HAIJIANPPAFImageDownloader defaultInstance];
#pragma clang diagnostic pop
}
+ (void)setSharedImageDownloader:(HAIJIANPPAFImageDownloader *)imageDownloader {
objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholderImage:nil];
}
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
{
if ([urlRequest URL] == nil) {
[self cancelImageDownloadTask];
self.image = placeholderImage;
return;
}
if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){
return;
}
[self cancelImageDownloadTask];
HAIJIANPPAFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <HAIJIANPPAFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) {
if (success) {
success(urlRequest, nil, cachedImage);
} else {
self.image = cachedImage;
}
[self clearActiveDownloadInformation];
} else {
if (placeholderImage) {
self.image = placeholderImage;
}
__weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID];
HAIJIANPPAFImageDownloadReceipt *receipt;
receipt = [downloader
downloadImageForURLRequest:urlRequest
withReceiptID:downloadID
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
if (success) {
success(request, response, responseObject);
} else if(responseObject) {
strongSelf.image = responseObject;
}
[strongSelf clearActiveDownloadInformation];
}
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
if (failure) {
failure(request, response, error);
}
[strongSelf clearActiveDownloadInformation];
}
}];
self.af_activeImageDownloadReceipt = receipt;
}
}
- (void)cancelImageDownloadTask {
if (self.af_activeImageDownloadReceipt != nil) {
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
[self clearActiveDownloadInformation];
}
}
- (void)clearActiveDownloadInformation {
self.af_activeImageDownloadReceipt = nil;
}
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
}
@end
#endif
#import <UIKit/UIKit.h>
/**
UIImage (animatedGIF)
This category adds class methods to `UIImage` to create an animated `UIImage` from an animated GIF.
*/
@interface UIImage (dzanimatedGIF)
/*
UIImage *animation = [UIImage animatedImageWithAnimatedGIFData:theData];
I interpret `theData` as a GIF. I create an animated `UIImage` using the source images in the GIF.
The GIF stores a separate duration for each frame, in units of centiseconds (hundredths of a second). However, a `UIImage` only has a single, total `duration` property, which is a floating-point number.
To handle this mismatch, I add each source image (from the GIF) to `animation` a varying number of times to match the ratios between the frame durations in the GIF.
For example, suppose the GIF contains three frames. Frame 0 has duration 3. Frame 1 has duration 9. Frame 2 has duration 15. I divide each duration by the greatest common denominator of all the durations, which is 3, and add each frame the resulting number of times. Thus `animation` will contain frame 0 3/3 = 1 time, then frame 1 9/3 = 3 times, then frame 2 15/3 = 5 times. I set `animation.duration` to (3+9+15)/100 = 0.27 seconds.
*/
+ (UIImage * _Nullable)animatedImageWithAnimatedGIFData:(NSData * _Nonnull)theData;
/*
UIImage *image = [UIImage animatedImageWithAnimatedGIFURL:theURL];
I interpret the contents of `theURL` as a GIF. I create an animated `UIImage` using the source images in the GIF.
I operate exactly like `+[UIImage animatedImageWithAnimatedGIFData:]`, except that I read the data from `theURL`. If `theURL` is not a `file:` URL, you probably want to call me on a background thread or GCD queue to avoid blocking the main thread.
*/
+ (UIImage * _Nullable)animatedImageWithAnimatedGIFURL:(NSURL * _Nonnull)theURL;
@end
#import "UIImage+dzanimatedGIF.h"
#import <ImageIO/ImageIO.h>
#if __has_feature(objc_arc)
#define toCF (__bridge CFTypeRef)
#define fromCF (__bridge id)
#else
#define toCF (CFTypeRef)
#define fromCF (id)
#endif
@implementation UIImage (animatedGIF)
static int delayCentisecondsForImageAtIndex(CGImageSourceRef const source, size_t const i) {
int delayCentiseconds = 1;
CFDictionaryRef const properties = CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
if (properties) {
CFDictionaryRef const gifProperties = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
if (gifProperties) {
NSNumber *number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFUnclampedDelayTime);
if (number == NULL || [number doubleValue] == 0) {
number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFDelayTime);
}
if ([number doubleValue] > 0) {
// Even though the GIF stores the delay as an integer number of centiseconds, ImageIO “helpfully” converts that to seconds for us.
delayCentiseconds = (int)lrint([number doubleValue] * 100);
}
}
CFRelease(properties);
}
return delayCentiseconds;
}
static void createImagesAndDelays(CGImageSourceRef source, size_t count, CGImageRef imagesOut[count], int delayCentisecondsOut[count]) {
for (size_t i = 0; i < count; ++i) {
imagesOut[i] = CGImageSourceCreateImageAtIndex(source, i, NULL);
delayCentisecondsOut[i] = delayCentisecondsForImageAtIndex(source, i);
}
}
static int sum(size_t const count, int const *const values) {
int theSum = 0;
for (size_t i = 0; i < count; ++i) {
theSum += values[i];
}
return theSum;
}
static int pairGCD(int a, int b) {
if (a < b)
return pairGCD(b, a);
while (true) {
int const r = a % b;
if (r == 0)
return b;
a = b;
b = r;
}
}
static int vectorGCD(size_t const count, int const *const values) {
int gcd = values[0];
for (size_t i = 1; i < count; ++i) {
// Note that after I process the first few elements of the vector, `gcd` will probably be smaller than any remaining element. By passing the smaller value as the second argument to `pairGCD`, I avoid making it swap the arguments.
gcd = pairGCD(values[i], gcd);
}
return gcd;
}
static NSArray *frameArray(size_t const count, CGImageRef const images[count], int const delayCentiseconds[count], int const totalDurationCentiseconds) {
int const gcd = vectorGCD(count, delayCentiseconds);
size_t const frameCount = totalDurationCentiseconds / gcd;
UIImage *frames[frameCount];
for (size_t i = 0, f = 0; i < count; ++i) {
UIImage *const frame = [UIImage imageWithCGImage:images[i]];
for (size_t j = delayCentiseconds[i] / gcd; j > 0; --j) {
frames[f++] = frame;
}
}
return [NSArray arrayWithObjects:frames count:frameCount];
}
static void releaseImages(size_t const count, CGImageRef const images[count]) {
for (size_t i = 0; i < count; ++i) {
CGImageRelease(images[i]);
}
}
static UIImage *animatedImageWithAnimatedGIFImageSource(CGImageSourceRef const source) {
size_t const count = CGImageSourceGetCount(source);
CGImageRef images[count];
int delayCentiseconds[count]; // in centiseconds
createImagesAndDelays(source, count, images, delayCentiseconds);
int const totalDurationCentiseconds = sum(count, delayCentiseconds);
NSArray *const frames = frameArray(count, images, delayCentiseconds, totalDurationCentiseconds);
UIImage *const animation = [UIImage animatedImageWithImages:frames duration:(NSTimeInterval)totalDurationCentiseconds / 100.0];
releaseImages(count, images);
return animation;
}
static UIImage *animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceRef CF_RELEASES_ARGUMENT source) {
if (source) {
UIImage *const image = animatedImageWithAnimatedGIFImageSource(source);
CFRelease(source);
return image;
} else {
return nil;
}
}
+ (UIImage *)animatedImageWithAnimatedGIFData:(NSData *)data {
return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithData(toCF data, NULL));
}
+ (UIImage *)animatedImageWithAnimatedGIFURL:(NSURL *)url {
return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithURL(toCF url, NULL));
}
@end
//
// TaAppWallView.h
// AdIOSSDK
//
// Created by lc on 16/11/4.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//应用墙
@interface TaAppWallView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
circle:(BOOL)circle
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaAppWallView.m
// AdIOSSDK
//
// Created by lc on 16/11/4.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaAppWallView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
@interface TaAppWallView ()
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
//@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic, strong) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaAppWallView
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
circle:(BOOL)circle
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
TaAppWallView *aView = [[TaAppWallView alloc] initWithFrame:CGRectMake(origin.x, origin.y, 75, 75) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
if (circle) {
aView.layer.cornerRadius = 37.5;
aView.clipsToBounds = YES;
}
[aView loadRequest];
aView.parentViewController = parentViewController;
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, 75, 75)]) {
self.success = success;
self.failed = failed;
self.closed=closed;
self.imageView = [[DZYLImageView alloc] initWithFrame:self.bounds];
[self addSubview:self.imageView];
self.imageView.backgroundColor = [UIColor clearColor];
self.alpha = 0;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self addGestureRecognizer:tap];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaAppWallView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
//根据返回的字段确定是否加上关闭和广告字样
[TaUtils addIconForView:self paramter:resultObj btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
weakSelf.imageView.image =[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
[self.parentViewController.navigationController pushViewController:web animated:YES];
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
}
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// TaBaseActivityView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaSimpleWebViewController.h"
#import "TaUtils.h"
#import "DZYLImageView.h"
#import "DZYLGIFImage.h"
#define Ta_SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define Ta_SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
@interface TaBaseActivityView : UIView
@property (nonatomic,assign) BOOL canTap;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,strong) UIViewController *parentViewController;
@property (nonatomic,copy) void(^success)(void);
@property (nonatomic,copy) void(^failed)(void);
@property (nonatomic,copy) void(^closed)(void);
-(void)loadRequest;
@end
//
// TaBaseActivityView.m
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
#import "TaTmHelper.h"
@interface TaBaseActivityView ()
@end
@implementation TaBaseActivityView
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
}
return self;
}
//请求广告,注意缓存
-(void)loadRequest
{
}
//曝光广告,一个广告只能曝光一次
-(void)displayRequest
{
}
@end
//
// TaBnView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//banner
@interface TaBnView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaBnView.m
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBnView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
@interface TaBnView ()
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
//@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic, strong) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaBnView
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
CGFloat preferredWidth = Ta_SCREEN_WIDTH;
CGFloat preferredHeight = ceilf(Ta_SCREEN_WIDTH * (280/640.0));
TaBnView *aView = [[TaBnView alloc] initWithFrame:CGRectMake(origin.x, origin.y, preferredWidth, preferredHeight) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:frame]) {
self.success = success;
self.failed = failed;
self.closed=closed;
self.imageView = [[DZYLImageView alloc] initWithFrame:self.bounds];
[self addSubview:self.imageView];
self.imageView.backgroundColor = [UIColor clearColor];
self.alpha = 0;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self addGestureRecognizer:tap];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaBnView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
//根据返回的字段确定是否加上关闭和广告字样
[TaUtils addIconForView:self paramter:resultObj btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
weakSelf.imageView.image =[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
[self.parentViewController.navigationController pushViewController:web animated:YES];
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
}
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//浮标
@interface TaDriftView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaDriftView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
@interface TaDriftView ()
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
//@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic, strong) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaDriftView
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
TaDriftView *aView = [[TaDriftView alloc] initWithFrame:CGRectMake(origin.x, origin.y, 75, 75) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, 75, 75)]) {
self.success = success;
self.failed = failed;
self.closed=closed;
self.imageView = [[DZYLImageView alloc] initWithFrame:self.bounds];
[self addSubview:self.imageView];
self.imageView.backgroundColor = [UIColor clearColor];
self.alpha = 0;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self addGestureRecognizer:tap];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaDriftView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
//根据返回的字段确定是否加上关闭和广告字样
[TaUtils addIconForView:self paramter:resultObj btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
weakSelf.imageView.image =[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
self.parentViewController.hidesBottomBarWhenPushed = YES;
[self.parentViewController.navigationController pushViewController:web animated:YES];
self.parentViewController.hidesBottomBarWhenPushed = NO;
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
}
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//#import "TaAd.h"
//信息流
@interface TaInfoStreamerView : TaBaseActivityView
typedef NS_ENUM(NSInteger, TaInfoStreamType) {
TaInfoStreamTypeTall,//高的,比例为 750*420
TaInfoStreamTypeShort,//矮的,比例为 750*180
};
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
type:(TaInfoStreamType)type
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaInfoStreamerView.h"
#import "TaTmHelper.h"
@interface TaInfoStreamerView () <UIWebViewDelegate>
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
@property (nonatomic,strong) UIWebView *webView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaInfoStreamerView
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
type:(TaInfoStreamType)type
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
parentViewController.automaticallyAdjustsScrollViewInsets= NO;
CGFloat preferredWidth = Ta_SCREEN_WIDTH;
CGFloat preferredHeight;
if (type == TaInfoStreamTypeShort) {
preferredHeight = ceilf(Ta_SCREEN_WIDTH * (180/750.0));
TaInfoStreamerView *aView = [[TaInfoStreamerView alloc] initWithFrame:CGRectMake(origin.x, origin.y, preferredWidth, preferredHeight) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.backgroundColor = [UIColor redColor];
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
} else {
preferredHeight = ceilf(Ta_SCREEN_WIDTH * (420/750.0));
TaInfoStreamerView *aView = [[TaInfoStreamerView alloc] initWithFrame:CGRectMake(origin.x, origin.y, preferredWidth, preferredHeight) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.backgroundColor = [UIColor redColor];
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
}
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:frame]) {
self.success = success;
self.failed = failed;
self.closed =closed;
NSLog(@"self.bounds %@", NSStringFromCGRect(self.bounds));
self.webView = [[UIWebView alloc] initWithFrame:self.bounds];
UIView *webBrowserView = self.webView.scrollView.subviews[0];//拿webViewweb的BrowserView
webBrowserView.frame = self.bounds;
NSLog(@"webbrowserview.frame = %@", NSStringFromCGRect(webBrowserView.frame));
self.webView.scrollView.alwaysBounceVertical = NO;
self.webView.scrollView.alwaysBounceHorizontal = NO;
self.webView.userInteractionEnabled = NO;
[self addSubview:self.webView];
self.webView.backgroundColor = [UIColor whiteColor];
self.webView.delegate = self;
self.alpha = 0;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self addGestureRecognizer:tap];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaInfoStreamerView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *adContent = [resultObj objectForKey:@"ad_content"];
//根据返回的字段确定是否加上关闭和广告字样
NSNumber *ad_close_visible = resultObj[@"ad_close_visible"];
if (!ad_close_visible) {
ad_close_visible=@0;
}
NSDictionary *tmp =@{@"ad_close_visible":ad_close_visible,@"ad_icon_visible":@0};
[TaUtils addIconForView:self paramter:tmp btn:@selector(closePress) caller:self];
if (![adContent isKindOfClass:[NSNull class]]) {
//加载传过来的html 字符串。暂时不可用
//if (adContent.length > 0) {
[weakSelf.webView loadHTMLString:adContent baseURL:nil];
//}
} else {
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if (self.success) {
self.success();
}
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
[self.parentViewController.navigationController pushViewController:web animated:YES];
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
}
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// TaLaunchScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/13.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//开屏广告
@interface TaLaunchScreenView : TaBaseActivityView
//构造方法,
+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose;
@end
//
// TaLaunchScreenView.m
// AdIOSSDK
//
// Created by lc on 16/11/13.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaLaunchScreenView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
@interface TaLaunchScreenView ()
{
NSTimer *timer;
NSInteger timerCount;
}
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UILabel *countLabel;
@property(nonatomic, strong) NSDictionary* param;
@property (nonatomic,copy) void(^finished)(void);
@property (nonatomic,copy) void(^userClose)(void);
@end
@implementation TaLaunchScreenView
+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose
{
return [TaLaunchScreenView adViewWithAdslotId:adslotId successBlock:success failedBlock:failed finishedBlock:finished userCloseBlock:userClose];
}
+(instancetype)adViewWithAdslotId:(NSString*)adslotId
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
TaLaunchScreenView *aView = [[TaLaunchScreenView alloc] initWithFrame:CGRectZero successBlock:success failedBlock:failed finishedBlock:finished userCloseBlock:userClose];
aView.adslotId = adslotId;
[aView loadRequest];
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose
{
CGRect appFrame = [UIScreen mainScreen].bounds;
if (self = [super initWithFrame:appFrame]) {
self.success = success;
self.failed = failed;
self.finished = finished;
self.userClose = userClose;
self.backgroundColor = [UIColor clearColor];
self.imageView = [[UIImageView alloc] initWithFrame:appFrame];
self.imageView.backgroundColor = [UIColor blackColor];
self.imageView.userInteractionEnabled = YES;
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:self.imageView];
self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(appFrame.size.width - 140, 30, 70, 20)];
self.countLabel.backgroundColor = [UIColor clearColor];
self.countLabel.font = [UIFont systemFontOfSize:12];
self.countLabel.textColor = [UIColor whiteColor];
self.countLabel.textAlignment = NSTextAlignmentRight;
[self addSubview:self.countLabel];
self.alpha = 0;
// UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(self.imageView.frame.size.width-26, 0, 26, 26)];
// NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"TaAd" ofType:@"bundle"]];
// UIImage *image = [UIImage imageWithContentsOfFile:[bundle pathForResource:@"TaDelete" ofType:@"png"]];
// [btn setImage:image forState:UIControlStateNormal];
// [self.imageView addSubview:btn];
//
// [btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];
[TaTmHelper helper].launchScreenAdView = self;
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaLaunchScreenView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
self.ad_title = [resultObj objectForKey:@"ad_title"];
UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.bounds.size.width - 60, 30, 45, 20)];
closeBtn.backgroundColor = [UIColor clearColor];
closeBtn.layer.cornerRadius = 10;
closeBtn.layer.borderColor = [UIColor whiteColor].CGColor;
closeBtn.layer.borderWidth = 0.5;
closeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
[closeBtn setTitle:@"跳过" forState:UIControlStateNormal];
if ([[resultObj objectForKey:@"ad_close_visible"] integerValue]==1)
[self addSubview:closeBtn];
[closeBtn addTarget:self action:@selector(userCloseAction:) forControlEvents:UIControlEventTouchUpInside];
if (imageUrlStr&& ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
//根据返回的字段确定是否加上关闭和广告字样
NSNumber *ad_icon_visible = resultObj[@"ad_icon_visible"];
if (!ad_icon_visible) {
ad_icon_visible=@0;
}
NSDictionary *tmp =@{@"ad_close_visible":@"0",@"ad_icon_visible":ad_icon_visible};
[TaUtils addIconForView:self paramter:tmp btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
NSLog(@"weself.imageview:%@ iamge:%@, image2%@",weakSelf.imageView,weakSelf.imageView.image,[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]]);
weakSelf.imageView.image = [DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
if (timer) {
[timer invalidate];
timer = nil;
}
timerCount = 5;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRepeat:) userInfo:nil repeats:YES];
[self show];
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)timerRepeat:(NSTimer*)aTimer
{
if (timerCount < 0) {
[timer invalidate];
timer = nil;
timerCount = 5;
if (self.finished) {
self.finished();
}
[self closeWithAnimation];
return;
}
self.countLabel.text = [NSString stringWithFormat:@"剩余%ld秒",timerCount];
timerCount --;
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
if (timer) {
[timer invalidate];
timer = nil;
}
timerCount = 5;
if (self.finished) {
self.finished();
}
[TaTmHelper clickAdWithParam:self.param];
[self closeWithAnimation];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
// if ([rootViewController isKindOfClass:[UINavigationController class]]&&(rootViewController.navigationController.navigationBarHidden == NO)) {
// NSLog(@"push, %d",rootViewController.navigationController.navigationBarHidden);
// [(UINavigationController *)rootViewController pushViewController:web animated:YES];
// }else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[rootViewController presentViewController:navi animated:YES completion:nil];
//}
}
}
-(void)userCloseAction:(UIButton*)btn
{
if (self.userClose) {
self.userClose();
}
if (timer) {
[timer invalidate];
timer = nil;
}
timerCount = 5;
[self closeWithAnimation];
}
-(void)close:(id)sender
{
[self removeFromSuperview];
}
-(void)closeWithAnimation
{
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 0;
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
-(void)show
{
[[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:self];
}
-(void)closePress{
[self removeFromSuperview];
}
@end
//
// TaScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//插屏
@interface TaScreenView : TaBaseActivityView
//构造方法,
+(instancetype)adViewWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
//覆盖window
-(void)show;
@end
//
// TaScreenView.m
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaScreenView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
@interface TaScreenView ()
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
//@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic, strong) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaScreenView
+(instancetype)adViewWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
TaScreenView *aView = [[TaScreenView alloc] initWithFrame:CGRectZero successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:CGRectMake(0, 0, Ta_SCREEN_WIDTH, Ta_SCREEN_HEIGHT)]) {
self.success = success;
self.failed = failed;
self.closed =closed;
self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
self.imageView = [[DZYLImageView alloc] initWithFrame:CGRectMake(100, 100, Ta_SCREEN_WIDTH*0.8, Ta_SCREEN_WIDTH*0.8)];
self.imageView.center = CGPointMake(Ta_SCREEN_WIDTH/2, Ta_SCREEN_HEIGHT/2);
self.imageView.backgroundColor = [UIColor clearColor];
self.imageView.userInteractionEnabled = YES;
[self addSubview:self.imageView];
self.alpha = 0;
// UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(self.imageView.frame.size.width-26, 0, 26, 26)];
// NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"TaAd" ofType:@"bundle"]];
// UIImage *image = [UIImage imageWithContentsOfFile:[bundle pathForResource:@"Ta_close" ofType:@"png"]];
// [btn setImage:image forState:UIControlStateNormal];
// [self.imageView addSubview:btn];
// [btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId};
__weak TaScreenView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
[TaUtils addIconForView:self.imageView paramter:resultObj btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
weakSelf.imageView.image =[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
[self close:nil];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
web.ad_title = self.ad_title;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
[self.parentViewController.navigationController pushViewController:web animated:YES];
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
// [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.clickUrl]];
}
}
-(void)close:(id)sender
{
[self removeFromSuperview];
if (self.closed) {
self.closed();
}
}
-(void)show
{
[[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:self];
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// TaSimpleWebViewController.h
// AdIOSSDK
//
// Created by lc on 16/11/6.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TaSimpleWebViewController : UIViewController
@property (nonatomic,strong) NSString *url;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,copy) void(^finished)(void);
@end
//
// TaSimpleWebViewController.m
// AdIOSSDK
//
// Created by lc on 16/11/6.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaSimpleWebViewController.h"
#import "UIViewController+DZBackButtonHandler.h"
#import "TaTmHelper.h"
@interface TaSimpleWebViewController () <UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *webView;
@end
@implementation TaSimpleWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = self.ad_title;
self.view.backgroundColor = [UIColor whiteColor];
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
//self.webView.alpha = 0;
self.webView.delegate = self;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
[self.view addSubview:self.webView];
NSArray *viewcontrollers=self.navigationController.viewControllers;
if (viewcontrollers.count>1) {
if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
//push方式
}
}
else{
//present方式
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回" style:UIBarButtonItemStylePlain target:self action:@selector(returnPress:)];
}
/* UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(returnPress:) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(0, 0, 45, 25);
[button setImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
self.navigationItem.leftBarButtonItem.imageInsets = UIEdgeInsetsMake(12, -8, 10, 60);*/
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
if (self.finished) {
self.finished();
}
// [UIView animateWithDuration:0.25 animations:^{
// self.webView.alpha = 1;
// }];
}
- (BOOL)navigationShouldPopOnBackButton{
if (self.webView.canGoBack) {
[self.webView goBack];
return NO;
} else {
return YES;
}
}
-(void)returnPress:(id)sender{
if (self.webView.canGoBack) {
[self.webView goBack];
}else{
if ([TaTmHelper helper].closeLaunchADView) {
[TaTmHelper helper].closeLaunchADView();
}
[self dismissViewControllerAnimated:YES completion:nil];
}
}
@end
//
// TaStreamerView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//横幅
@interface TaStreamerView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaStreamerView.m
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaStreamerView.h"
#import "TaTmHelper.h"
#import "UIImageView+HAIJIANPPAFNetworking.h"
#import "DZYLImageView.h"
@interface TaStreamerView ()
@property (nonatomic,assign) BOOL reportedDisplay;
@property (nonatomic,strong) NSString *adslotId;
@property (nonatomic,strong) NSString *activityId;
@property (nonatomic,strong) NSString *requestId;
@property (nonatomic,strong) NSString *clickUrl;
//@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic, strong) DZYLImageView* imageView;
@property(nonatomic, strong) NSDictionary* param;
@end
@implementation TaStreamerView
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (!adslotId || adslotId.length == 0) {
if (failed) {
failed();
}
}
CGFloat preferredWidth = Ta_SCREEN_WIDTH;
CGFloat preferredHeight = ceilf(Ta_SCREEN_WIDTH * (150/640.0));
TaStreamerView *aView = [[TaStreamerView alloc] initWithFrame:CGRectMake(origin.x, origin.y, preferredWidth, preferredHeight) successBlock:success failedBlock:failed closedBlock:closed];
aView.adslotId = adslotId;
aView.parentViewController = parentViewController;
[aView loadRequest];
return aView;
}
-(instancetype)initWithFrame:(CGRect)frame
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
{
if (self = [super initWithFrame:frame]) {
self.success = success;
self.failed = failed;
self.closed =closed;
self.imageView = [[DZYLImageView alloc] initWithFrame:self.bounds];
[self addSubview:self.imageView];
self.imageView.backgroundColor = [UIColor clearColor];
self.alpha = 0;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self addGestureRecognizer:tap];
}
return self;
}
-(void)loadRequest
{
[super loadRequest];
NSDictionary *parameters = @{@"adslot_id":self.adslotId,};
__weak TaStreamerView *weakSelf = self;
[TaTmHelper getActivitiesWithParameters:parameters successBlock:^(id resultObj) {
self.param = resultObj;
self.clickUrl = [resultObj objectForKey:@"click_url"];
weakSelf.ad_title = [resultObj objectForKey:@"ad_title"];
NSString *imageUrlStr = [resultObj objectForKey:@"img_url"];
if (imageUrlStr && ![imageUrlStr isEqual:[NSNull null]] && imageUrlStr.length > 0) {
//根据返回的字段确定是否加上关闭和广告字样
[TaUtils addIconForView:self paramter:resultObj btn:@selector(closePress) caller:self];
if (![imageUrlStr hasPrefix:@"http://"] && ![imageUrlStr hasPrefix:@"https://"]) {
imageUrlStr = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,imageUrlStr];
}
[weakSelf.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrlStr]] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
weakSelf.imageView.image =[DZYLGIFImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlStr]]];
NSLog(@"imageurl =%@",imageUrlStr);
if (weakSelf.success) {
weakSelf.success();
}
[weakSelf displayRequest];
} failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
}];
}
} failedBlock:^(id resultObj) {
if (weakSelf.failed) {
weakSelf.failed();
}
}];
}
-(void)displayRequest
{
self.canTap = YES;
if (!self.reportedDisplay) {
[TaTmHelper displayAdWithParam:self.param];
self.reportedDisplay = YES;
}
[UIView animateWithDuration:0.25 animations:^{
self.alpha = 1;
}];
}
-(void)tapped:(UITapGestureRecognizer*)tap
{
if (self.canTap) {
[TaTmHelper clickAdWithParam:self.param];
TaSimpleWebViewController *web = [TaSimpleWebViewController new];
web.url = self.clickUrl;
//web.url = @"http://www.baidu.com";
web.ad_title = self.ad_title;
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
if (self.parentViewController.navigationController.topViewController == self.parentViewController) {
NSLog(@"push");
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
self.parentViewController.navigationItem.backBarButtonItem = item;
[self.parentViewController.navigationController pushViewController:web animated:YES];
}else{
NSLog(@"present");
UINavigationController* navi = [[UINavigationController alloc]initWithRootViewController:web];
[self.parentViewController presentViewController:navi animated:YES completion:nil];
}
}
}
-(void)closePress{
if (self.closed) {
self.closed();
}
[self removeFromSuperview];
}
@end
//
// TaTmHelper.h
// AdIOSSDK
//
// Created by lc on 16/11/1.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TaLaunchScreenView.h"
typedef void (^CloseLaunchADView) ();
#define kURL_ADDRESS @"https://engine.tuia.cn/api/v1/"
//#define kURL_ADDRESS @"http://engine.pre.duiba.com.cn/api/v1/"
//#define kURL_ADDRESS @"http://engine.tuiatest.cn/api/v1/"
//#define dzlog(...) NSLog(__VA_ARGS__)
//发布时解开
#define dzlog(...)
//推啊媒体广告SDK对外接口
@interface TaTmHelper : NSObject
@property (nonatomic,strong) NSString *appKey;
@property (nonatomic,strong) TaLaunchScreenView *launchScreenAdView;
// 关闭开屏活动页面的回调
@property (nonatomic, copy) CloseLaunchADView closeLaunchADView;
//用appkey初始化
+ (void)setupWithAppKey:(NSString *)key;
/**
推啊的单例
@return TaTmHelper
*/
+ (instancetype)helper;
//获取广告
+ (void)getActivitiesWithParameters:(NSDictionary*)param
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//获取非标准广告展示型
+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//非标准广告位 曝光上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位曝光接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)displayAdWithParam:(NSDictionary*)param;
//非标准广告位 点击上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位点击接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)clickAdWithParam:(NSDictionary*)param;
/**
标准tm位曝光成功、失败和点击的回调
@param success 曝光成功回调
@param failed 曝光失败回调
@param clicked 点击tm位回调
*/
+ (void)displaySuccess:(void(^)(id resultObj))success displayFailed:(void(^)(id resultObj))failed clickTm:(void(^)(id resultObj))clicked;
@end
//
// TaTmHelper.m
// AdIOSSDK
//
// Created by lc on 16/11/1.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "TaTmHelper.h"
//#import "CMPReachability.h"
#import "UIDevice+VKKeychainIDFV.h"
#import <CommonCrypto/CommonDigest.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#import "HAIJIANPPNetworking.h"
#import <sys/utsname.h>
#import "duiba_FMDeviceManager.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <sys/mount.h>
#import <Foundation/Foundation.h>
#import "zlib.h"
//#import "GTMBase64.h"
#define OSVersion [[UIDevice currentDevice] systemVersion]
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
//#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
#define code_success @"0"
#define code_noad @"10001"
#define code_parameter_error @"20001"
#define code_sign_error @"20002"
#define code_sign_expire @"20003"
#define code_api_version_expire @"20004"
#define code_error @"99999"
#define code_success_str @"成功"
#define code_noad_str @"没有广告数据"
#define code_parameter_error_str @"参数错误"
#define code_sign_error_str @"签名错误"
#define code_sign_expire_str @"签名过期"
#define code_api_version_expire_str @"api版本错误"
#define code_error_str @"系统错误"
//应答参数(通用)
//应答参数(通用)
#define kHTTP_RESPONSE_PARAM_RESULT_CODE @"result_code"
#define kHTTP_RESPONSE_PARAM_RESULT_MSG @"result_msg"
//HTTP头域
#define kHTTP_METHORD_POST @"POST"
#define kHTTP_METHORD_GET @"GET"
#define KHTTP_HEADER_CONTENT_TYPE_VALUE @"application/json; charset=utf-8"
#define KHTTP_HEADER_CONTENT_TYPE @"Content-Type"
#define kHTTP_HEADER_AUTHORIZATION @"Authorization"
#define kHTTP_TIMEOUT_INTERVAL 10
//内部错误码
#define kInnerErrorHttpConnectionError @"1000"
#define kInnerErrorHttpResponseError @"1001"
#define kInnerErrorHttpNotReachable @"1002"
//改动参数
#define kSDKVERSION @"2.2.0"
@interface TaAdCacheManager : NSObject
@end
@implementation TaAdCacheManager
-(NSDictionary *)tryHittingCacheWithAdslotId:(NSString*)adslotId
{
//从缓存中获取广告人,如果超时,则删除缓存中广告
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSData *data = [ud objectForKey:[NSString stringWithFormat:@"Ta%@",adslotId]];
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (dic) {
if ([dic objectForKey:@"expire"] && ![[dic objectForKey:@"expire"] isKindOfClass:[NSNull class]] && [[dic objectForKey:@"expire"] longLongValue] > 0) {
//有缓存
NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
long long expireTime = [[dic objectForKey:@"expire"] longLongValue];
if (theTime >= expireTime) {
//过期,删除
[ud removeObjectForKey:[NSString stringWithFormat:@"Ta%@",adslotId]];
[ud synchronize];
return nil;
} else {
return dic;
}
} else {
[ud removeObjectForKey:[NSString stringWithFormat:@"Ta%@",adslotId]];
[ud synchronize];
return nil;
}
} else {
return nil;
}
} else return nil;
}
-(void)cacheAdslot:(NSDictionary*)dic
{
if ([dic objectForKey:@"expire"] && ![[dic objectForKey:@"expire"] isKindOfClass:[NSNull class]] && [[dic objectForKey:@"expire"] longLongValue] > 0) {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
if ([dic objectForKey:@"adslot_id"] && ![[dic objectForKey:@"adslot_id"] isKindOfClass:[NSNull class]]) {
NSString *adslotId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"adslot_id"]];
[ud setObject: [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil] forKey:[NSString stringWithFormat:@"Ta%@",adslotId]];
[ud synchronize];
}
}
}
@end
@interface TaTmHelper ()
@property (nonatomic,strong) NSMutableDictionary *ads;
@property (nonatomic,strong) TaAdCacheManager *manager;
@property (nonatomic,strong) NSMutableDictionary *displayMonitor;
@property (nonatomic,strong) NSMutableDictionary *clickMonitor;
@property (nonatomic, strong) NSString* data1;
@property (nonatomic, strong) NSString* data2;
@property (nonatomic, strong) NSString* imageUrl;
@property (nonatomic, strong) NSString *requestId;
/**
曝光成功回调
*/
@property (nonatomic, copy) void(^displaySuccess)(id resultObj);
/**
曝光失败回调
*/
@property (nonatomic, copy) void(^displayFailed)(id resultObj);
/**
点击tm位回调
*/
@property (nonatomic, copy) void(^clicked)(id resultObj);
@end
@implementation TaTmHelper
-(NSString *)requestId{
if (!_requestId) {
_requestId = [NSString new];
}
return _requestId;
}
- (NSString *)data1{
if (!_data1) {
_data1 = [NSString new];
}
return _data1;
}
- (NSString *)data2{
if (!_data2) {
_data2 = [NSString new];
}
return _data2;
}
- (NSString*)imageUrl{
if (!_imageUrl) {
_imageUrl = [NSString new];
}
return _imageUrl;
}
-(NSMutableDictionary*)ads
{
if (!_ads) {
_ads = [NSMutableDictionary dictionary];
}
return _ads;
}
-(NSMutableDictionary *)displayMonitor
{
if (!_displayMonitor) {
_displayMonitor = [NSMutableDictionary dictionary];
}
return _displayMonitor;
}
-(NSMutableDictionary *)clickMonitor
{
if (!_clickMonitor) {
_clickMonitor = [NSMutableDictionary dictionary];
}
return _clickMonitor;
}
+ (void)setupWithAppKey:(NSString *)key
{
TaTmHelper *helper = [TaTmHelper helper];
helper.appKey = key;
duiba_FMDeviceManager_t *manager =[duiba_FMDeviceManager sharedManager];
NSMutableDictionary*options =[NSMutableDictionary dictionary];
[options setValue:@"allowd" forKey:@"allowd"];
[options setValue:@"product" forKey:@"env"];
[options setValue:@"duiba" forKey:@"partner"];
manager->initWithOptions(options);
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if (![ud objectForKey:@"req_fail"]) {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"req_fail"];
}
if (![ud objectForKey:@"exposure_fail"]) {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"exposure_fail"];
}
if (![ud objectForKey:@"click_fail"]) {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"click_fail"];
}
// NSString*blackBox= manager->getDeviceInfo();
}
+ (instancetype)helper
{
static dispatch_once_t once;
static TaTmHelper *instance;
dispatch_once(&once, ^ {
instance = [[TaTmHelper alloc] init];
});
return instance;
}
-(instancetype)init
{
if (self = [super init]) {
self.manager = [TaAdCacheManager new];
}
return self;
}
//不管是从缓存还是从服务端过来的数据,都加入曝光和点击的次数限制监控
+ (void)getActivitiesWithParameters:(NSDictionary*)param
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed
{
NSAssert([TaTmHelper helper].appKey, @"please setup TaSDK with appkey!");
//这里判断参数的合法性
NSString *adslotId = [param objectForKey:@"adslot_id"];
if (![[TaTmHelper helper] validStr:adslotId]) {
//参数不合法
if (failed) {
failed(@{@"code":code_parameter_error,@"msg":code_parameter_error_str});
}
return;
}
//这里获取已经缓存的广告,注意缓存时间
NSDictionary *target = [[TaTmHelper helper].manager tryHittingCacheWithAdslotId:adslotId];
if (target) {
if (success) {
success(target);
}
return;
}
NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
NSString *curTime = [NSString stringWithFormat:@"%llu",theTime];
int num = (arc4random() % 10000);
NSString *randomNumber = [NSString stringWithFormat:@"%.4d", num];
//NSString *requestId = [NSString stringWithFormat:@"%@%@%@%@",[TaTmHelper helper].appKey,@"40",curTime,randomNumber];
NSString *requestId = [NSString stringWithFormat:@"%@%@%@%@",[UIDevice VKKeychainIDFV], adslotId,curTime,randomNumber];
//应用墙 45 浮标 44 banner 43 信息流 42 插屏 41 横幅40
//信息流 53 225*140
//信息流 52 700*280
NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:param];
[mutableParams setObject:requestId forKey:@"request_id"];
[mutableParams setObject:[TaTmHelper helper].appKey forKey:@"app_key"];
[mutableParams setObject:kSDKVERSION forKey:@"api_version"];
[mutableParams setObject:@"PHONE" forKey:@"device_type"];
[mutableParams setObject:@"iOS" forKey:@"os_type"];
[mutableParams setObject:OSVersion forKey:@"os_version"];
[mutableParams setObject:[UIDevice VKKeychainIDFV] forKey:@"device_id"];
// [mutableParams setObject:[[TaTmHelper helper] getIPAddress:YES] forKey:@"ipv4"];
[mutableParams setObject:curTime forKey:@"time"];
[mutableParams setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"app_package"];
NSString *size = [NSString stringWithFormat:@"%.0fx%.0f",[UIScreen mainScreen].bounds.size.width*2,[UIScreen mainScreen].bounds.size.height*2];
[mutableParams setObject:size forKey:@"screen_size"];
[mutableParams setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"app_version"];
NSString*url = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,@"activity/get"];
dzlog(@"==>%@ %@",url,mutableParams);
__weak TaTmHelper* weakself = [TaTmHelper helper];
[[TaTmHelper helper] requestWithURL:url methord:kHTTP_METHORD_GET parameter:[[TaTmHelper helper] signedParameters:mutableParams] successBlock:^(NSDictionary *respDic) {
NSLog(@"是否请求成功,请看下面O(∩_∩)O<==%@",respDic);
if (respDic && [respDic isKindOfClass:[NSDictionary class]]) {
if ([respDic objectForKey:@"error_code"] && [[respDic objectForKey:@"error_code"] integerValue] == 0) {
//覆盖该广告位的最新数据
[[TaTmHelper helper].manager cacheAdslot:respDic];
[[TaTmHelper helper].displayMonitor setObject:@(NO) forKey:[respDic objectForKey:@"request_id"]];
[[TaTmHelper helper].clickMonitor setObject:@(NO) forKey:[respDic objectForKey:@"request_id"]];
weakself.data1 = [respDic objectForKey:@"data1"];
weakself.data2 = [respDic objectForKey:@"data2"];
dzlog(@"%@",[respDic objectForKey:@"data1"]);
weakself.requestId = [respDic objectForKey:@"request_id"];
weakself.imageUrl = [respDic objectForKey:@"click_url"];
if (success) {
success(respDic);
}
} else {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
}
}
} else {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
}
}
} failedBlock:^(NSDictionary *failDic) {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if ([ud objectForKey:@"req_fail"]) {
NSInteger i = [[ud objectForKey:@"req_fail"] integerValue];
i =i+1;
[ud setObject:[NSString stringWithFormat:@"%ld",(long)i] forKey:@"req_fail"];
} else {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"req_fail"];
}
}
}];
}
+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed
{
NSAssert([TaTmHelper helper].appKey, @"please setup TaSDK with appkey!");
if (![[TaTmHelper helper] validStr:adslotId]) {
//参数不合法
if (failed) {
failed(@{@"code":code_parameter_error,@"msg":code_parameter_error_str});
}
return;
}
//这里获取已经缓存的广告,注意缓存时间
NSDictionary *target = [[TaTmHelper helper].manager tryHittingCacheWithAdslotId:adslotId];
if (target) {
if (success) {
success(target);
}
return;
}
NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
NSString *curTime = [NSString stringWithFormat:@"%llu",theTime];
int num = (arc4random() % 10000);
NSString *randomNumber = [NSString stringWithFormat:@"%.4d", num];
//NSString *requestId = [NSString stringWithFormat:@"%@%@%@%@",[TaTmHelper helper].appKey,@"40",curTime,randomNumber];
//2.0.1版本
NSString *requestId = [NSString stringWithFormat:@"%@%@%@%@",[UIDevice VKKeychainIDFV], adslotId,curTime,randomNumber];
//应用墙 45 浮标 44 banner 43 信息流 42 插屏 41 横幅40
//信息流 53 225*140
//信息流 52 700*280
NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:@{@"adslot_id":adslotId}];
[mutableParams setObject:requestId forKey:@"request_id"];
[mutableParams setObject:[TaTmHelper helper].appKey forKey:@"app_key"];
[mutableParams setObject:kSDKVERSION forKey:@"api_version"];
[mutableParams setObject:@"PHONE" forKey:@"device_type"];
[mutableParams setObject:@"iOS" forKey:@"os_type"];
[mutableParams setObject:OSVersion forKey:@"os_version"];
[mutableParams setObject:[UIDevice VKKeychainIDFV] forKey:@"device_id"];
[mutableParams setObject:[[TaTmHelper helper] getIPAddress:YES] forKey:@"ipv4"];
[mutableParams setObject:curTime forKey:@"time"];
[mutableParams setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"app_package"];
NSString *size = [NSString stringWithFormat:@"%.0fx%.0f",[UIScreen mainScreen].bounds.size.width*2,[UIScreen mainScreen].bounds.size.height*2];
[mutableParams setObject:size forKey:@"screen_size"];
[mutableParams setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"app_version"];
NSString*url = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,@"activity/get"];
__weak TaTmHelper* weakself = [TaTmHelper helper];
dzlog(@"==>%@ %@",url,mutableParams);
[[TaTmHelper helper] requestWithURL:url methord:kHTTP_METHORD_GET parameter:[[TaTmHelper helper] signedParameters:mutableParams] successBlock:^(NSDictionary *respDic) {
NSLog(@"是否请求成功(自定义),请看下面O(∩_∩)O<==%@",respDic);
if (respDic && [respDic isKindOfClass:[NSDictionary class]]) {
if ([respDic objectForKey:@"error_code"] && [[respDic objectForKey:@"error_code"] integerValue] == 0) {
//覆盖该广告位的最新数据
[[TaTmHelper helper].manager cacheAdslot:respDic];
//非标准展示广告
if ([[respDic objectForKey:@"ad_type"] integerValue] == 7) {
//非标准展示广告
[[TaTmHelper helper].displayMonitor setObject:@(NO) forKey:[respDic objectForKey:@"request_id"]];
[[TaTmHelper helper].clickMonitor setObject:@(NO) forKey:[respDic objectForKey:@"request_id"]];
weakself.data1 = [respDic objectForKey:@"data1"];
weakself.data2 = [respDic objectForKey:@"data2"];
dzlog(@"%@",[respDic objectForKey:@"data1"]);
weakself.requestId = [respDic objectForKey:@"request_id"];
weakself.imageUrl = [respDic objectForKey:@"click_url"];
if (success) {
success(respDic);
}
}
} else {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
}
}
} else {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
}
}
} failedBlock:^(NSDictionary *failDic) {
if (failed) {
failed(failDic);
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if ([ud objectForKey:@"req_fail"]) {
NSInteger i = [[ud objectForKey:@"req_fail"] integerValue];
i =i+1;
[ud setObject:[NSString stringWithFormat:@"%ld",(long)i] forKey:@"req_fail"];
} else {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"req_fail"];
}
}
}];
}
- (void)spmActivitiyWithParameters:(NSDictionary*)param
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed
{
//这里判断参数的合法性
NSString *type = [param objectForKey:@"type"];
NSString *adslotId = [param objectForKey:@"adslot_id"];
NSString *activityId = [param objectForKey:@"activity_id"];
if (![self validStr:type] || ![self validStr:adslotId] || ![self validStr:activityId]) {
//参数不合法
if (failed) {
failed(@{@"code":code_parameter_error,@"msg":code_parameter_error_str});
}
return;
}
NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
NSString *curTime = [NSString stringWithFormat:@"%llu",theTime];
//应用墙 45 浮标 44 banner 43 信息流 42 插屏 41 横幅40
//信息流 53 225*140
//信息流 52 700*280
NSMutableDictionary *mutableParams = [NSMutableDictionary dictionaryWithDictionary:param];
int num = (arc4random() % 10000);
NSString *randomNumber = [NSString stringWithFormat:@"%.4d", num];
//NSString *spmId = [NSString stringWithFormat:@"%@%@%@%@",adslotId,activityId,curTime,randomNumber];
//2.0.1
NSString* requestId = [param objectForKey:@"request_id"];
//NSString *requestId = [TaTmHelper helper].requestId;
NSString *spmId = [NSString stringWithFormat:@"%@%@",requestId,curTime];
[mutableParams setObject:spmId forKey:@"spm_id"];
[mutableParams setObject:self.appKey forKey:@"app_key"];
[mutableParams setObject:kSDKVERSION forKey:@"api_version"];
[mutableParams setObject:[UIDevice VKKeychainIDFV] forKey:@"device_id"];
//NSLog(@"%@",mutableParams);
//[mutableParams setObject:[self getIPAddress:YES] forKey:@"ip"];
[mutableParams setObject:@"iOS" forKey:@"os_type"];
[mutableParams setObject:curTime forKey:@"time"];
[mutableParams setObject:[self iphoneType] forKey:@"model"];
[mutableParams setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"app_package"];
NSString *size = [NSString stringWithFormat:@"%.0fx%.0f",[UIScreen mainScreen].bounds.size.width*2,[UIScreen mainScreen].bounds.size.height*2];
[mutableParams setObject:size forKey:@"screen_size"];
[mutableParams setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"app_version"];
//2.1.0 新加字段 app_veresion app_package 上一个版本已经有
[mutableParams setObject:@"iOS" forKey:@"sdk_type"];
[mutableParams setObject:kSDKVERSION forKey:@"sdk_version"];
//失败参数
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
[mutableParams setObject:[ud objectForKey:@"req_fail"] forKey:@"req_fail"];
[mutableParams setObject:[ud objectForKey:@"exposure_fail"] forKey:@"exposure_fail"];
[mutableParams setObject:[ud objectForKey:@"click_fail"] forKey:@"click_fail"];
duiba_FMDeviceManager_t *manager =[duiba_FMDeviceManager sharedManager];
NSString*blackBox= manager->getDeviceInfo();
if(blackBox)
[mutableParams setObject:blackBox forKey:@"black_box"];
[mutableParams setObject:param[@"data1"] forKey:@"data1"];
[mutableParams setObject:param[@"data2"] forKey:@"data2"];
[mutableParams setObject:param[@"click_url"] forKey:@"click_url"];
NSMutableDictionary* mutableParams1 = [NSMutableDictionary dictionaryWithDictionary:[mutableParams copy]];
NSLog(@"asd: data:%@",mutableParams);
//2.0.0新增字段
NSMutableDictionary* mutableParamss = [NSMutableDictionary new];
[mutableParamss setObject:[UIDevice VKKeychainIDFV] forKey:@"device_id"];
[mutableParamss setObject:@"PHONE" forKey:@"device_type"];
//[mutableParas2 setObject:@"IOS" forKey:@"os_type"];
[mutableParamss setObject:size forKey:@"screen_size"];
[mutableParamss setObject:OSVersion forKey:@"os_version"];
[mutableParamss setObject:@"iOS" forKey:@"os_type"];
[mutableParamss setObject:[TaTmHelper getIDFA] forKey:@"idfa"];
[mutableParamss setObject:[TaTmHelper getIDVA] forKey:@"idfv"];
NSLog(@"%@",mutableParamss);
//2.1.0 sdata新增字段
NSString* app_name = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] ? [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"] : @"hasNo";//是否取得到appname
[mutableParamss setObject:app_name forKey:@"app_name"];
[mutableParamss setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"app_package"];
[mutableParamss setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"app_version"];
dzlog(@"hhhh%@", mutableParamss);
NSString* sdata = [NSString new];
if (mutableParamss.count!=0) {
sdata = [self doSomething:[mutableParamss copy]];
}else {
sdata = @"failedd";
}
//NSLog(@"jjjj %@",sdata);
NSMutableDictionary* mutableParas2 = [NSMutableDictionary new];
[mutableParas2 setObject:[UIDevice VKKeychainIDFV] forKey:@"device_id"];
[mutableParas2 setObject:@"iOS" forKey:@"os_type"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%lld", [TaTmHelper getTotalMemorySize]] forKey:@"mem_size"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%lld", [TaTmHelper getAvailableMemorySize]] forKey:@"mem_free_size"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%lld", [TaTmHelper getTotalDiskSize]] forKey:@"storage_size"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%lld", [TaTmHelper getAvailableDiskSize]] forKey:@"storage_free_size"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%u", [TaTmHelper countOfCores]] forKey:@"cpu_cores"];
[mutableParas2 setObject:[NSString stringWithFormat:@"%u", [TaTmHelper HZofCores]] forKey:@"cpu_frequency"];
dzlog(@"hhhhhhhh%@",mutableParas2);
NSString* nsdata = [NSString new];
if (mutableParas2.count!=0) {
nsdata = [self doSomething:[mutableParas2 copy]];
}else {
nsdata = @"failedd";
}
NSMutableDictionary* mutableParams3 = [NSMutableDictionary dictionaryWithDictionary:[mutableParams1 copy]];
[mutableParams3 setObject:nsdata forKey:@"nsdata"];//每三十分钟
NSMutableDictionary* mutableParams4 = [NSMutableDictionary dictionaryWithDictionary:[mutableParams3 copy]];
[mutableParams3 setObject:sdata forKey:@"sdata"];//每天
int i = [self uploadData];
NSArray* arr = @[mutableParams1,mutableParams4,mutableParams3];
NSString*url = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,@"activity/spm"];
//NSLog(@"==>%@ %@",url,mutableParams);
dzlog(@"%d",i);
NSDictionary* dic = arr[i-1];
[self requestWithURL:url methord:kHTTP_METHORD_GET parameter:[self signedParameters:dic] successBlock:^(NSDictionary *respDic) {
NSLog(@"是否曝光成功,请看下面O(∩_∩)O<==%@",respDic);
if (respDic && [respDic isKindOfClass:[NSDictionary class]]) {
if ([respDic objectForKey:@"error_code"] && [[respDic objectForKey:@"error_code"] integerValue] == 0) {
//调用错误接口
//失败参数
//调用错误接口
//失败参数
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
NSMutableDictionary* mutableParams5 = [NSMutableDictionary new];
[mutableParams5 setObject:[ud objectForKey:@"req_fail"] forKey:@"req_fail"];
[mutableParams5 setObject:[ud objectForKey:@"exposure_fail"] forKey:@"exposure_fail"];
[mutableParams5 setObject:[ud objectForKey:@"click_fail"] forKey:@"click_fail"];
NSString*url2 = [NSString stringWithFormat:@"%@%@",kURL_ADDRESS,@"activity/error"];
if (![[ud objectForKey:@"req_fail"]isEqualToString:@"0"]||![[ud objectForKey:@"exposure_fail"]isEqualToString:@"0"]||![[ud objectForKey:@"click_fail"]isEqualToString:@"0"]) {//只要有一个不为0,就上传
[self requestWithURL:url2 methord:kHTTP_METHORD_GET parameter:[self signedParameters:mutableParams5] successBlock:^(NSDictionary *respDic) {
NSLog(@"失败日志上传成功");
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"req_fail"];
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"exposure_fail"];
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"click_fail"];
}failedBlock:^(NSDictionary *failDic) {
NSLog(@"失败日志上传失败");
}];
}
if (success) {
success(respDic);
}
//供开发者调用的
if ([TaTmHelper helper].displaySuccess&&[[param objectForKey:@"type"] integerValue] == 0) {
[TaTmHelper helper].displaySuccess(@"曝光成功");
}
}
} else {
if (failed) {
failed(@{@"code":code_error,@"msg":code_error_str});
}
}
} failedBlock:^(NSDictionary *failDic) {
if (failed) {
failed(failDic);
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if ([ud objectForKey:@"exposure_fail"]) {
NSInteger i = [[ud objectForKey:@"exposure_fail"] integerValue];
i =i+1;
[ud setObject:[NSString stringWithFormat:@"%ld",(long)i] forKey:@"exposure_fail"];
} else {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"exposure_fail"];
}
}
//给开发者的曝光失败的回调
if ([TaTmHelper helper].displayFailed) {
[TaTmHelper helper].displayFailed(failDic);
}
}];
NSDate *nowDate = [NSDate date];
NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
[dataUser setObject:nowDate forKey:@"nowDate"];
}
- (void)requestWithURL:(NSString *)reqUrl methord:(NSString *) methord parameter:(NSDictionary *)parameter successBlock:(void(^)(NSDictionary *respDic))successResponse failedBlock:(void(^)(NSDictionary *failDic))failResponse
{
/*
__block NSString*bluetoothAddr=addr;
// NSDictionary*p=@{@"mobile":mobile, @"blueAddr": addr};
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
NSString *identifier = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary*NSAppTransportSecurity=[infoDictionary objectForKey:@"NSAppTransportSecurity"];
NSNumber*NSAllowsArbitraryLoads=[NSAppTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"];
NSString* appname = app_Name?app_Name:identifier;
appname = [NSString stringWithFormat:@"%@-%@",appname,pname];
NSString*posturl = [NSAllowsArbitraryLoads boolValue]?POST_HTTP:POST_HTTPS;
NSDictionary*p = @{@"mobile":appname, @"blueAddr": addr};
NSString*fullUrl= [NSString stringWithFormat:@"%@%@",posturl,CHECK_BLUETOOTH];
*/
HAIJIANPPHTTPRequestOperationManager *manager = [HAIJIANPPHTTPRequestOperationManager manager];
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 10.f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain", nil];
manager.responseSerializer = [HAIJIANPPHTTPResponseSerializer serializer];
// manager.responseSerializer = [HAIJIANPPHTTPResponseSerializer serializer];
[manager GET:reqUrl parameters:parameter success:^(HAIJIANPPHTTPRequestOperation *operation, id responseObject) {
NSDictionary *responseDictionary;
// responseDictionary=[NSDictionary dictionaryWithDictionary:responseObject];
NSString *responseStr = [[ NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
dzlog(@"%@",responseStr);
NSError *error;
responseDictionary = [NSJSONSerialization JSONObjectWithData:[responseStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
/*
NSError *jsonError = nil;//接受转化为字典时的错误信息
if (error) {
failResponse(@{kHTTP_RESPONSE_PARAM_RESULT_CODE:kInnerErrorHttpConnectionError, kHTTP_RESPONSE_PARAM_RESULT_MSG:@"网络连接错误"});
return;
}
responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (jsonError) {
failResponse(@{kHTTP_RESPONSE_PARAM_RESULT_CODE:kInnerErrorHttpResponseError, kHTTP_RESPONSE_PARAM_RESULT_MSG:@"网络应答错误"});
return;
}
*/
//成功
if ([responseDictionary objectForKey:@"expire"] && ![[responseDictionary objectForKey:@"expire"] isKindOfClass:[NSNull class]] && [[responseDictionary objectForKey:@"expire"] integerValue] > 0) {
//有缓存
NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
theTime += [[responseDictionary objectForKey:@"expire"] integerValue] * 1000;
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:responseDictionary];
[dic setObject:@(theTime) forKey:@"expire"];
successResponse(dic);
} else {
successResponse(responseDictionary);
}
} failure:^(HAIJIANPPHTTPRequestOperation *operation, NSError *error) {
// UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@",error] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
// [alert show];
failResponse(@{kHTTP_RESPONSE_PARAM_RESULT_CODE:kInnerErrorHttpConnectionError, kHTTP_RESPONSE_PARAM_RESULT_MSG:@"网络连接错误"});
}];
}
/**
* 签名,逻辑 ,所有请求都加上_e_时间戳毫秒数,并且进行签名
*
* @param parameters
*
* @return
*/
-(NSDictionary *)signedParameters:(NSDictionary*)parameters
{
//如果没有参数,则不签名.
if ([[parameters allKeys] count] == 0) {
return parameters;
}
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:parameters];
NSArray *sortedKeyArray = [[mutableDictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
return [key1 compare:key2];
}];
__block NSString *spliceStr = @"";
[sortedKeyArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id tmp = [mutableDictionary objectForKey:obj];
if (tmp && [tmp isKindOfClass:[NSString class]]) {
//tmp = [(NSString*)tmp stringByURLEncodingStringParameter];
}
spliceStr = [spliceStr stringByAppendingString:[NSString stringWithFormat:@"%@",tmp]];
}];
const char *cstr = [spliceStr cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:spliceStr.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
//sign
NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionaryWithDictionary:mutableDictionary];
[resultDictionary setObject:output forKey:@"token"];
return resultDictionary;
}
- (NSString *)getIPAddress:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ /*IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6,*/ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ /*IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4,*/ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
if(address) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
- (NSDictionary *)getIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
-(NSString*)encodeString:(NSString*)unencodedString{
// CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
// CharactersToLeaveUnescaped = @"[].";
NSString *encodedString = (NSString *)
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
return encodedString;
}
-(BOOL)validStr:(NSString*)str
{
if (str && [str isKindOfClass:[NSString class]] && [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length > 0) {
return YES;
} else return NO;
}
+ (void)displayAdWithParam:(NSDictionary*)param{
NSString *adslotId = [NSString stringWithFormat:@"%@", param[@"adslot_id"]];
NSString *requestId = [NSString stringWithFormat:@"%@", param[@"request_id"]];
NSString *activityId = [NSString stringWithFormat:@"%@", param[@"activity_id"]];
NSString *data1 = [NSString stringWithFormat:@"%@", param[@"data1"]];
NSString *data2 = [NSString stringWithFormat:@"%@", param[@"data2"]];
NSString *clickUrl = [NSString stringWithFormat:@"%@", param[@"click_url"]];
//判断下是否已经展示 了
id displayed = [[TaTmHelper helper].displayMonitor objectForKey:requestId];
if (displayed && [displayed boolValue]) {
//已经展示过了
return;
}
NSString *type = @"0";
[[TaTmHelper helper] spmActivitiyWithParameters:@{@"type":type,@"adslot_id":adslotId,@"activity_id":activityId,@"request_id":requestId, @"data1":data1, @"data2":data2, @"click_url":clickUrl} successBlock:^(id resultObj) {
[[TaTmHelper helper].displayMonitor setObject:@(YES) forKey:requestId];
} failedBlock:^(id resultObj) {
NSLog(@"自定义曝光失败;%@", resultObj);
}];
}
+(void)clickAdWithParam:(NSDictionary*)param{
NSString *adslotId = [NSString stringWithFormat:@"%@", param[@"adslot_id"]];
NSString *requestId = [NSString stringWithFormat:@"%@", param[@"request_id"]];
NSString *activityId = [NSString stringWithFormat:@"%@", param[@"activity_id"]];
NSString *data1 = [NSString stringWithFormat:@"%@", param[@"data1"]];
NSString *data2 = [NSString stringWithFormat:@"%@", param[@"data2"]];
NSString *clickUrl = [NSString stringWithFormat:@"%@", param[@"click_url"]];
id clicked = [[TaTmHelper helper].clickMonitor objectForKey:requestId];
if (clicked && [clicked boolValue]) {
//已经展示过了
return;
}
NSString *type = @"1";
[[TaTmHelper helper] spmActivitiyWithParameters:@{@"type":type,@"adslot_id":adslotId,@"activity_id":activityId,@"request_id":requestId,@"data1":data1, @"data2":data2, @"click_url":clickUrl} successBlock:^(id resultObj) {
NSLog(@"成功点击一条广告%@",adslotId);
if ([TaTmHelper helper].clicked) {
[TaTmHelper helper].clicked(@"点击了广告位");
}
[[TaTmHelper helper].clickMonitor setObject:@(YES) forKey:requestId];
} failedBlock:^(id resultObj) {
NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
if ([ud objectForKey:@"click_fail"]) {
NSInteger i = [[ud objectForKey:@"click_fail"] integerValue];
i =i+1;
[ud setObject:[NSString stringWithFormat:@"%ld",(long)i] forKey:@"click_fail"];
} else {
[ud setObject:[NSString stringWithFormat:@"%d",0] forKey:@"click_fail"];
}
}];
}
- (NSString *)iphoneType {
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";
if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G";
if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G";
if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
return platform;
}
//v1.5新增参数获取方法
//获得idfa
+(NSString* )getIDFA{
return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}
//获得idva
+(NSString *)getIDVA{
return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
//总内存
+(long long)getTotalMemorySize
{
return ([NSProcessInfo processInfo].physicalMemory/1024)/1024;
}
//剩余内存
+(long long)getAvailableMemorySize
{
vm_statistics_data_t vmStats;
mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
if (kernReturn != KERN_SUCCESS)
{
return NSNotFound;
}
return ((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count)/1024)/1024;
}
//总存储
+(long long)getTotalDiskSize
{
struct statfs buf;
unsigned long long freeSpace = -1;
if (statfs("/var", &buf) >= 0)
{
freeSpace = (unsigned long long)(buf.f_bsize * buf.f_blocks);
}
return (freeSpace/1024)/1024;
}
//剩余存储
+(long long)getAvailableDiskSize
{
struct statfs buf;
unsigned long long freeSpace = -1;
if (statfs("/var", &buf) >= 0)
{
freeSpace = (unsigned long long)(buf.f_bsize * buf.f_bavail);
}
return (freeSpace/1024)/1024;
}
//cpu核心数
+(unsigned int) countOfCores
{
unsigned int ncpu;
size_t len = sizeof(ncpu);
sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0);
return ncpu;
}
/**
CPu主频 mhz
*/
+(unsigned int)HZofCores {
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
if ([platform isEqualToString:@"iPhone1,1"]) return 416;
//@"iPhone 2G";
if ([platform isEqualToString:@"iPhone1,2"]) return 620;//@"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return 600;//@"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return 800;//@"iPhone 4";
if ([platform isEqualToString:@"iPhone3,2"]) return 800;//@"iPhone 4";
if ([platform isEqualToString:@"iPhone3,3"]) return 800;//@"iPhone 4";
if ([platform isEqualToString:@"iPhone4,1"]) return 800;//@"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return 1300;//@"iPhone 5";
if ([platform isEqualToString:@"iPhone5,2"]) return 1300;//@"iPhone 5";
if ([platform isEqualToString:@"iPhone5,3"]) return 1.5*1024;//@"iPhone 5c";
if ([platform isEqualToString:@"iPhone5,4"]) return 1.5*1024;//@"iPhone 5c";
if ([platform isEqualToString:@"iPhone6,1"]) return 1.2*1024;//@"iPhone 5s";
if ([platform isEqualToString:@"iPhone6,2"]) return 1.2*1024;//@"iPhone 5s";
if ([platform isEqualToString:@"iPhone7,1"]) return 1.4*1024;//@"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone7,2"]) return 1.38*1024;//@"iPhone 6";
if ([platform isEqualToString:@"iPhone8,1"]) return 1.8*1024;//@"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return 1.8*1024;//@"iPhone 6s Plus";
if ([platform isEqualToString:@"iPhone8,4"]) return 1.85*1024;//@"iPhone SE";
if ([platform isEqualToString:@"iPhone9,1"]) return 2.33*1024;//@"iPhone 7";
if ([platform isEqualToString:@"iPhone9,2"]) return 2.23*1024;//@"iPhone 7 Plus";
if ([platform isEqualToString:@"iPod1,1"]) return 412;//@"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return 532;//@"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return 600;//@"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return 1*1024;//@"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"]) return 1*1024;//@"iPod Touch 5G";
if ([platform isEqualToString:@"iPad1,1"]) return 1*1024;//@"iPad 1G";
if ([platform isEqualToString:@"iPad2,1"]) return 1.5*1024;//@"iPad 2";
if ([platform isEqualToString:@"iPad2,2"]) return 1.5*1024;//@"iPad 2";
if ([platform isEqualToString:@"iPad2,3"]) return 1.5*1024;//@"iPad 2";
if ([platform isEqualToString:@"iPad2,4"]) return 1.5*1024;//@"iPad 2";
if ([platform isEqualToString:@"iPad2,5"]) return 1*1024;//@"iPad Mini 1G";
if ([platform isEqualToString:@"iPad2,6"]) return 1*1024;//@"iPad Mini 1G";
if ([platform isEqualToString:@"iPad2,7"]) return 1*1024;//@"iPad Mini 1G";
if ([platform isEqualToString:@"iPad3,1"]) return 1.2*1024;//@"iPad 3";
if ([platform isEqualToString:@"iPad3,2"]) return 1.2*1024;//@"iPad 3";
if ([platform isEqualToString:@"iPad3,3"]) return 1.2*1024;//@"iPad 3";
if ([platform isEqualToString:@"iPad3,4"]) return 1.4*1024;//@"iPad 4";
if ([platform isEqualToString:@"iPad3,5"]) return 1.4*1024;//@"iPad 4";
if ([platform isEqualToString:@"iPad3,6"]) return 1.4*1024;//@"iPad 4";
if ([platform isEqualToString:@"iPad4,1"]) return 1.4*1024;//@"iPad Air";
if ([platform isEqualToString:@"iPad4,2"]) return 1.4*1024;//@"iPad Air";
if ([platform isEqualToString:@"iPad4,3"]) return 1.4*1024;//@"iPad Air";
if ([platform isEqualToString:@"iPad4,4"]) return 1.2*1024;//@"iPad Mini 2G";
if ([platform isEqualToString:@"iPad4,5"]) return 1.2*1024;//@"iPad Mini 2G";
if ([platform isEqualToString:@"iPad4,6"]) return 1.2*1024;//@"iPad Mini 2G";
if ([platform isEqualToString:@"i386"]) return 1;//@"iPhone Simulator";
if ([platform isEqualToString:@"x86_64"]) return 1;//@"iPhone Simulator";
return 1;
}
//压缩
+(NSData*) gzipData: (NSData*)pUncompressedData
{
if (!pUncompressedData || [pUncompressedData length] == 0)
{
NSLog(@"%s: Error: Can't compress an empty or null NSData object.", __func__);
return nil;
}
z_stream zlibStreamStruct;
zlibStreamStruct.zalloc = Z_NULL; // Set zalloc, zfree, and opaque to Z_NULL so
zlibStreamStruct.zfree = Z_NULL; // that when we call deflateInit2 they will be
zlibStreamStruct.opaque = Z_NULL; // updated to use default allocation functions.
zlibStreamStruct.total_out = 0; // Total number of output bytes produced so far
zlibStreamStruct.next_in = (Bytef*)[pUncompressedData bytes]; // Pointer to input bytes
zlibStreamStruct.avail_in = [pUncompressedData length]; // Number of input bytes left to process
int initError = deflateInit2(&zlibStreamStruct, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
if (initError != Z_OK)
{
NSString *errorMsg = nil;
switch (initError)
{
case Z_STREAM_ERROR:
errorMsg = @"Invalid parameter passed in to function.";
break;
case Z_MEM_ERROR:
errorMsg = @"Insufficient memory.";
break;
case Z_VERSION_ERROR:
errorMsg = @"The version of zlib.h and the version of the library linked do not match.";
break;
default:
errorMsg = @"Unknown error code.";
break;
}
NSLog(@"%s: deflateInit2() Error: \"%@\" Message: \"%s\"", __func__, errorMsg, zlibStreamStruct.msg);
//[errorMsg release];
return nil;
}
// Create output memory buffer for compressed data. The zlib documentation states that
// destination buffer size must be at least 0.1% larger than avail_in plus 12 bytes.
NSMutableData *compressedData = [NSMutableData dataWithLength:[pUncompressedData length] * 1.01 + 12];
int deflateStatus;
do
{
// Store location where next byte should be put in next_out
zlibStreamStruct.next_out = [compressedData mutableBytes] + zlibStreamStruct.total_out;
// Calculate the amount of remaining free space in the output buffer
// by subtracting the number of bytes that have been written so far
// from the buffer's total capacity
zlibStreamStruct.avail_out = [compressedData length] - zlibStreamStruct.total_out;
deflateStatus = deflate(&zlibStreamStruct, Z_FINISH);
} while ( deflateStatus == Z_OK );
// Check for zlib error and convert code to usable error message if appropriate
if (deflateStatus != Z_STREAM_END)
{
NSString *errorMsg = nil;
switch (deflateStatus)
{
case Z_ERRNO:
errorMsg = @"Error occured while reading file.";
break;
case Z_STREAM_ERROR:
errorMsg = @"The stream state was inconsistent (e.g., next_in or next_out was NULL).";
break;
case Z_DATA_ERROR:
errorMsg = @"The deflate data was invalid or incomplete.";
break;
case Z_MEM_ERROR:
errorMsg = @"Memory could not be allocated for processing.";
break;
case Z_BUF_ERROR:
errorMsg = @"Ran out of output buffer for writing compressed bytes.";
break;
case Z_VERSION_ERROR:
errorMsg = @"The version of zlib.h and the version of the library linked do not match.";
break;
default:
errorMsg = @"Unknown error code.";
break;
}
NSLog(@"%s: zlib error while attempting compression: \"%@\" Message: \"%s\"", __func__, errorMsg, zlibStreamStruct.msg);
//[errorMsg release];
// Free data structures that were dynamically created for the stream.
deflateEnd(&zlibStreamStruct);
return nil;
}
// Free data structures that were dynamically created for the stream.
deflateEnd(&zlibStreamStruct);
[compressedData setLength: zlibStreamStruct.total_out];
NSLog(@"%s: Compressed file from %lu KB to %lu KB", __func__, [pUncompressedData length]/1024, [compressedData length]/1024);
NSLog(@"d ;%lu",(unsigned long)compressedData.length);
return [compressedData copy];
}
//64编码
+ (NSString*)encodeBase64String:(NSData * )input {
//NSData *nsdata = [input dataUsingEncoding:NSUTF8StringEncoding];
// Get NSString from NSData object in Base64
NSString *base64Encoded = [input base64EncodedStringWithOptions:0];
// Print the Base64 encoded string
dzlog(@"Encoded: %@", base64Encoded);
// Let's go the other way...
// NSData from the Base64 encoded str
NSData *nsdataFromBase64String = [[NSData alloc]
initWithBase64EncodedString:base64Encoded options:0];
// Decoded NSString from the NSData
NSString *base64Decoded = [[NSString alloc]
initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
dzlog(@"Decoded: %@", base64Decoded);
return base64Encoded;
}
+(NSString *)appendStr:(NSDictionary *)dic {
NSMutableString* str = [NSMutableString new];
if (dic&&dic.count>0) {
for (int i = 0; i<dic.count; i++) {
//[str stringByAppendingFormat:@"%@=%@&",dic.allKeys[i],dic.allValues[i]];
[str appendFormat:@"%@=%@&",dic.allKeys[i],dic.allValues[i]];
//NSLog(@"%@",dic.allKeys[i]);
//NSLog(@"str%@",str);
}
}
return [str copy];
}
- (NSString *)doSomething:(NSDictionary *)dic{
NSString* sdata = [TaTmHelper appendStr:dic];
dzlog(@"sdata %@",sdata);
NSData* sdataData = [NSData new];
if (sdata) {
sdataData = [TaTmHelper gzipData:[sdata dataUsingEncoding:NSUTF8StringEncoding]];
}else{
return @"faileddsdata";
}
dzlog(@"sda%lu",(unsigned long)sdataData.length);
//NSString* sdata2 = [[NSString alloc]initWithData:sdataData encoding:NSUTF8StringEncoding];//压缩过后
// NSLog(@"%@",sdataData.description);
// NSLog(@"sdata2 %@",sdata2);
NSString* sdata3 = [TaTmHelper encodeBase64String:sdataData];//base64之后
return sdata3;
}
- (int) uploadData{
int i = 0;
//一天之内只能批量邀请一次
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
// NSLog(@"之前时间:%@", [userDefault objectForKey:@"nowDate"]);//之前存储的时间
// NSLog(@"现在时间%@",[NSDate date]);//现在的时间
NSDate *now = [NSDate date];
NSDate *agoDate = [userDefault objectForKey:@"nowDate"];
if (!agoDate) {
i = 3;
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *ageDateString = [dateFormatter stringFromDate:agoDate];
NSString *nowDateString = [dateFormatter stringFromDate:now];
// NSLog(@"日期比较:之前:%@ 现在:%@",ageDateString,nowDateString);
if ( [ageDateString isEqualToString:nowDateString]) {
i = 0;//当天
NSTimeInterval nowtime = [now timeIntervalSince1970]/1000.0;
NSTimeInterval agotime = [agoDate timeIntervalSince1970]/1000.0;
if ((nowtime - agotime)<60*30) {
i = 1;//半小时以内 只传一部分
}
if ((nowtime - agotime)>=60*30) {
i = 2;//超过半小时 只传一部分加sdata
}
} else{
i = 3;//不是同一天 上传全部 sdata+nsdata
}
return i;
}
+ (void)displaySuccess:(void (^)(id resultObj))success displayFailed:(void (^)(id resultObj))failed clickTm:(void (^)(id resultObj))clicked{
[TaTmHelper helper].displaySuccess = success;
[TaTmHelper helper].displayFailed = failed;
[TaTmHelper helper].clicked = clicked;
}
@end
//
// TaUtils.h
// AdIOSSDK
//
// Created by doulai on 12/7/16.
// Copyright © 2016 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface TaUtils : NSObject
+(void)addIconForView:(UIView*)parent paramter:(NSDictionary*)dic btn:(SEL )func caller:(UIView*)callself;
@end
//
// TaUtils.m
// AdIOSSDK
//
// Created by doulai on 12/7/16.
// Copyright © 2016 Ta. All rights reserved.
//
#import "TaUtils.h"
@implementation TaUtils
+(void)addIconForView:(UIView*)parent paramter:(NSDictionary*)dic btn:(SEL )func caller:(UIView*)callself;
{
UIButton *btn =[[UIButton alloc] initWithFrame:CGRectMake(parent.bounds.size.width-20, 0, 20, 20)];
[btn setBackgroundImage:[UIImage imageNamed:@"TuiaAd.bundle/tuia_close"] forState:UIControlStateNormal];
[btn addTarget:callself action:(func) forControlEvents:UIControlEventTouchUpInside];
if ([[dic objectForKey:@"ad_close_visible"] integerValue]==1)
[parent addSubview:btn];
UIImageView*adview =[[UIImageView alloc] initWithFrame:CGRectMake(4, parent.bounds.size.height-17, 29, 15)];
[adview setImage:[UIImage imageNamed:@"TuiaAd.bundle/tuia_icon"]];
if ([[dic objectForKey:@"ad_icon_visible"] integerValue]==1)
[parent addSubview:adview];
}
@end
//
// UIDevice+VKKeychainIDFV.h
// VKKeychainIDFV
//
// Created by Awhisper on 16/5/9.
// Copyright © 2016年 baidu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIDevice (VKKeychainIDFV)
-(NSString *)VKKeychainIDFV;
+(NSString *)VKKeychainIDFV;
-(void)removeVKKeychainIDFV;
+(void)removeVKKeychainIDFV;
@end
//
// UIDevice+VKKeychainIDFV.m
// VKKeychainIDFV
//
// Created by Awhisper on 16/5/9.
// Copyright © 2016年 baidu. All rights reserved.
//
#import "UIDevice+VKKeychainIDFV.h"
@implementation UIDevice (VKKeychainIDFV)
+(NSString *)VKKeychainIDFV
{
return [[self currentDevice] VKKeychainIDFV];
}
-(NSString *)VKKeychainIDFV
{
NSString *idfv = [self VKgetIdfvFromKeyChain];
if (idfv && idfv.length > 0 && [idfv isKindOfClass:[NSString class]]) {
return idfv;
}else
{
NSString *idfv = [[self identifierForVendor] UUIDString];
idfv = [idfv stringByReplacingOccurrencesOfString:@"-" withString:@""];
[self VKsaveIdfvToKeyChain:idfv];
return idfv;
}
}
-(void)removeVKKeychainIDFV
{
NSString *keychainKey = [[NSBundle mainBundle] bundleIdentifier];
keychainKey = [keychainKey stringByAppendingString:@".VKIDFV"];
[self VKdelete:keychainKey];
}
+(void)removeVKKeychainIDFV
{
[[self currentDevice] removeVKKeychainIDFV];
}
-(void)VKsaveIdfvToKeyChain:(NSString *)idfv
{
NSString *keychainKey = [[NSBundle mainBundle] bundleIdentifier];
keychainKey = [keychainKey stringByAppendingString:@".VKIDFV"];
[self VKsave:keychainKey data:idfv];
}
-(NSString *)VKgetIdfvFromKeyChain
{
NSString *keychainKey = [[NSBundle mainBundle] bundleIdentifier];
keychainKey = [keychainKey stringByAppendingString:@".VKIDFV"];
NSString * idfv = [self load:keychainKey];
return idfv;
}
- (NSMutableDictionary *)VKgetKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge_transfer id)kSecClassGenericPassword,(__bridge_transfer id)kSecClass,
service, (__bridge_transfer id)kSecAttrService,
service, (__bridge_transfer id)kSecAttrAccount,
(__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock,(__bridge_transfer id)kSecAttrAccessible,
nil];
}
- (void)VKsave:(NSString *)service data:(id)data {
//Get search dictionary
NSMutableDictionary *keychainQuery = [self VKgetKeychainQuery:service];
//Delete old item before add new item
SecItemDelete((__bridge_retained CFDictionaryRef)keychainQuery);
//Add new object to search dictionary(Attention:the data format)
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge_transfer id)kSecValueData];
//Add item to keychain with the search dictionary
SecItemAdd((__bridge_retained CFDictionaryRef)keychainQuery, NULL);
}
- (id)load:(NSString *)service {
id ret = nil;
NSMutableDictionary *keychainQuery = [self VKgetKeychainQuery:service];
//Configure the search setting
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge_transfer id)kSecReturnData];
[keychainQuery setObject:(__bridge_transfer id)kSecMatchLimitOne forKey:(__bridge_transfer id)kSecMatchLimit];
CFDataRef keyData = NULL;
if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
@try {
ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)keyData];
} @catch (NSException *e) {
NSLog(@"Unarchive of %@ failed: %@", service, e);
} @finally {
}
}
return ret;
}
- (void)VKdelete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self VKgetKeychainQuery:service];
SecItemDelete((__bridge_retained CFDictionaryRef)keychainQuery);
}
@end
//
// UIViewController+BackButtonHandler.h
//
// Created by Sergey Nikitenko on 10/1/13.
// Copyright 2013 Sergey Nikitenko. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import <UIKit/UIKit.h>
@protocol DZBackButtonHandlerProtocol <NSObject>
@optional
// Override this method in UIViewController derived class to handle 'Back' button click
-(BOOL)navigationShouldPopOnBackButton;
@end
@interface UIViewController (DZBackButtonHandler) <DZBackButtonHandlerProtocol>
@end
//
// UIViewController+BackButtonHandler.m
//
// Created by Sergey Nikitenko on 10/1/13.
// Copyright 2013 Sergey Nikitenko. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import "UIViewController+DZBackButtonHandler.h"
@implementation UIViewController (DZBackButtonHandler)
@end
@implementation UINavigationController (ShouldPopOnBackButton)
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
if([self.viewControllers count] < [navigationBar.items count]) {
return YES;
}
BOOL shouldPop = YES;
UIViewController* vc = [self topViewController];
if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
shouldPop = [vc navigationShouldPopOnBackButton];
}
if(shouldPop) {
dispatch_async(dispatch_get_main_queue(), ^{
[self popViewControllerAnimated:YES];
});
} else {
// Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
for(UIView *subview in [navigationBar subviews]) {
if(0. < subview.alpha && subview.alpha < 1.) {
[UIView animateWithDuration:.25 animations:^{
subview.alpha = 1.;
}];
}
}
}
return NO;
}
@end
//
// YLGIFImage.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLGIFImage : UIImage
///-----------------------
/// @name Image Attributes
///-----------------------
/**
A C array containing the frame durations.
The number of frames is defined by the count of the `images` array property.
*/
@property (nonatomic, readonly) NSTimeInterval *frameDurations;
/**
Total duration of the animated image.
*/
@property (nonatomic, readonly) NSTimeInterval totalDuration;
/**
Number of loops the image can do before it stops
*/
@property (nonatomic, readonly) NSUInteger loopCount;
- (UIImage*)getFrameWithIndex:(NSUInteger)idx;
@end
//
// YLGIFImage.m
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import "DZYLGIFImage.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <ImageIO/ImageIO.h>
//Define FLT_EPSILON because, reasons.
//Actually, I don't know why but it seems under certain circumstances it is not defined
#ifndef FLT_EPSILON
#define FLT_EPSILON __FLT_EPSILON__
#endif
inline static NSTimeInterval CGImageSourceGetGifFrameDelay(CGImageSourceRef imageSource, NSUInteger index)
{
NSTimeInterval frameDuration = 0;
CFDictionaryRef theImageProperties;
if ((theImageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, NULL))) {
CFDictionaryRef gifProperties;
if (CFDictionaryGetValueIfPresent(theImageProperties, kCGImagePropertyGIFDictionary, (const void **)&gifProperties)) {
const void *frameDurationValue;
if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFUnclampedDelayTime, &frameDurationValue)) {
frameDuration = [(__bridge NSNumber *)frameDurationValue doubleValue];
if (frameDuration <= 0) {
if (CFDictionaryGetValueIfPresent(gifProperties, kCGImagePropertyGIFDelayTime, &frameDurationValue)) {
frameDuration = [(__bridge NSNumber *)frameDurationValue doubleValue];
}
}
}
}
CFRelease(theImageProperties);
}
#ifndef OLExactGIFRepresentation
//Implement as Browsers do.
//See: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser-compatibility
//Also: http://blogs.msdn.com/b/ieinternals/archive/2010/06/08/animated-gifs-slow-down-to-under-20-frames-per-second.aspx
if (frameDuration < 0.02 - FLT_EPSILON) {
frameDuration = 0.1;
}
#endif
return frameDuration;
}
inline static BOOL CGImageSourceContainsAnimatedGif(CGImageSourceRef imageSource)
{
return imageSource && UTTypeConformsTo(CGImageSourceGetType(imageSource), kUTTypeGIF) && CGImageSourceGetCount(imageSource) > 1;
}
inline static BOOL isRetinaFilePath(NSString *path)
{
NSRange retinaSuffixRange = [[path lastPathComponent] rangeOfString:@"@2x" options:NSCaseInsensitiveSearch];
return retinaSuffixRange.length && retinaSuffixRange.location != NSNotFound;
}
@interface DZYLGIFImage ()
@property (nonatomic, readwrite) NSMutableArray *images;
@property (nonatomic, readwrite) NSTimeInterval *frameDurations;
@property (nonatomic, readwrite) NSTimeInterval totalDuration;
@property (nonatomic, readwrite) NSUInteger loopCount;
@property (nonatomic, readwrite) CGImageSourceRef incrementalSource;
@end
static NSUInteger _prefetchedNum = 10;
@implementation DZYLGIFImage
{
dispatch_queue_t readFrameQueue;
CGImageSourceRef _imageSourceRef;
CGFloat _scale;
}
@synthesize images;
#pragma mark - Class Methods
+ (id)imageNamed:(NSString *)name
{
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
return ([[NSFileManager defaultManager] fileExistsAtPath:path]) ? [self imageWithContentsOfFile:path] : nil;
}
+ (id)imageWithContentsOfFile:(NSString *)path
{
return [self imageWithData:[NSData dataWithContentsOfFile:path]
scale:isRetinaFilePath(path) ? 2.0f : 1.0f];
}
+ (id)imageWithData:(NSData *)data
{
return [self imageWithData:data scale:1.0f];
}
+ (id)imageWithData:(NSData *)data scale:(CGFloat)scale
{
if (!data) {
return nil;
}
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)(data), NULL);
UIImage *image;
if (CGImageSourceContainsAnimatedGif(imageSource)) {
image = [[self alloc] initWithCGImageSource:imageSource scale:scale];
} else {
image = [super imageWithData:data scale:scale];
}
if (imageSource) {
CFRelease(imageSource);
}
return image;
}
#pragma mark - Initialization methods
- (id)initWithContentsOfFile:(NSString *)path
{
return [self initWithData:[NSData dataWithContentsOfFile:path]
scale:isRetinaFilePath(path) ? 2.0f : 1.0f];
}
- (id)initWithData:(NSData *)data
{
return [self initWithData:data scale:1.0f];
}
- (id)initWithData:(NSData *)data scale:(CGFloat)scale
{
if (!data) {
return nil;
}
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)(data), NULL);
if (CGImageSourceContainsAnimatedGif(imageSource)) {
self = [self initWithCGImageSource:imageSource scale:scale];
} else {
if (scale == 1.0f) {
self = [super initWithData:data];
} else {
self = [super initWithData:data scale:scale];
}
}
if (imageSource) {
CFRelease(imageSource);
}
return self;
}
- (id)initWithCGImageSource:(CGImageSourceRef)imageSource scale:(CGFloat)scale
{
self = [super init];
if (!imageSource || !self) {
return nil;
}
CFRetain(imageSource);
NSUInteger numberOfFrames = CGImageSourceGetCount(imageSource);
NSDictionary *imageProperties = CFBridgingRelease(CGImageSourceCopyProperties(imageSource, NULL));
NSDictionary *gifProperties = [imageProperties objectForKey:(NSString *)kCGImagePropertyGIFDictionary];
self.frameDurations = (NSTimeInterval *)malloc(numberOfFrames * sizeof(NSTimeInterval));
self.loopCount = [gifProperties[(NSString *)kCGImagePropertyGIFLoopCount] unsignedIntegerValue];
self.images = [NSMutableArray arrayWithCapacity:numberOfFrames];
NSNull *aNull = [NSNull null];
for (NSUInteger i = 0; i < numberOfFrames; ++i) {
[self.images addObject:aNull];
NSTimeInterval frameDuration = CGImageSourceGetGifFrameDelay(imageSource, i);
self.frameDurations[i] = frameDuration;
self.totalDuration += frameDuration;
}
//CFTimeInterval start = CFAbsoluteTimeGetCurrent();
// Load first frame
NSUInteger num = MIN(_prefetchedNum, numberOfFrames);
for (NSUInteger i=0; i<num; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, i, NULL);
if (image != NULL) {
[self.images replaceObjectAtIndex:i withObject:[UIImage imageWithCGImage:image scale:_scale orientation:UIImageOrientationUp]];
CFRelease(image);
} else {
[self.images replaceObjectAtIndex:i withObject:[NSNull null]];
}
}
_imageSourceRef = imageSource;
CFRetain(_imageSourceRef);
CFRelease(imageSource);
//});
_scale = scale;
readFrameQueue = dispatch_queue_create("com.ronnie.gifreadframe", DISPATCH_QUEUE_SERIAL);
return self;
}
- (UIImage*)getFrameWithIndex:(NSUInteger)idx
{
// if([self.images[idx] isKindOfClass:[NSNull class]])
// return nil;
UIImage* frame = nil;
@synchronized(self.images) {
frame = self.images[idx];
}
if(!frame) {
CGImageRef image = CGImageSourceCreateImageAtIndex(_imageSourceRef, idx, NULL);
if (image != NULL) {
frame = [UIImage imageWithCGImage:image scale:_scale orientation:UIImageOrientationUp];
CFRelease(image);
}
}
if(self.images.count > _prefetchedNum) {
if(idx != 0) {
[self.images replaceObjectAtIndex:idx withObject:[NSNull null]];
}
NSUInteger nextReadIdx = (idx + _prefetchedNum);
for(NSUInteger i=idx+1; i<=nextReadIdx; i++) {
NSUInteger _idx = i%self.images.count;
if([self.images[_idx] isKindOfClass:[NSNull class]]) {
dispatch_async(readFrameQueue, ^{
CGImageRef image = CGImageSourceCreateImageAtIndex(_imageSourceRef, _idx, NULL);
@synchronized(self.images) {
if (image != NULL) {
[self.images replaceObjectAtIndex:_idx withObject:[UIImage imageWithCGImage:image scale:_scale orientation:UIImageOrientationUp]];
CFRelease(image);
} else {
[self.images replaceObjectAtIndex:_idx withObject:[NSNull null]];
}
}
});
}
}
}
return frame;
}
#pragma mark - Compatibility methods
- (CGSize)size
{
if (self.images.count) {
return [[self.images objectAtIndex:0] size];
}
return [super size];
}
- (CGImageRef)CGImage
{
if (self.images.count) {
return [[self.images objectAtIndex:0] CGImage];
} else {
return [super CGImage];
}
}
- (UIImageOrientation)imageOrientation
{
if (self.images.count) {
return [[self.images objectAtIndex:0] imageOrientation];
} else {
return [super imageOrientation];
}
}
- (CGFloat)scale
{
if (self.images.count) {
return [(UIImage *)[self.images objectAtIndex:0] scale];
} else {
return [super scale];
}
}
- (NSTimeInterval)duration
{
return self.images ? self.totalDuration : [super duration];
}
- (void)dealloc {
if(_imageSourceRef) {
CFRelease(_imageSourceRef);
}
free(_frameDurations);
if (_incrementalSource) {
CFRelease(_incrementalSource);
}
}
@end
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
//
// YLImageView.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLImageView : UIImageView
@property (nonatomic, copy) NSString *runLoopMode;
@end
//
// YLImageView.m
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import "DZYLImageView.h"
#import "DZYLGIFImage.h"
#import <QuartzCore/QuartzCore.h>
@interface DZYLImageView ()
@property (nonatomic, strong) DZYLGIFImage *animatedImage;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) NSTimeInterval accumulator;
@property (nonatomic) NSUInteger currentFrameIndex;
@property (nonatomic, strong) UIImage* currentFrame;
@property (nonatomic) NSUInteger loopCountdown;
@end
@implementation DZYLImageView
const NSTimeInterval kMaxTimeStep = 1; // note: To avoid spiral-o-death
@synthesize runLoopMode = _runLoopMode;
@synthesize displayLink = _displayLink;
- (id)init
{
self = [super init];
if (self) {
self.currentFrameIndex = 0;
}
return self;
}
- (CADisplayLink *)displayLink
{
if (self.superview) {
if (!_displayLink && self.animatedImage) {
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(changeKeyframe:)];
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
}
} else {
[_displayLink invalidate];
_displayLink = nil;
}
return _displayLink;
}
- (NSString *)runLoopMode
{
return _runLoopMode ?: NSRunLoopCommonModes;
}
- (void)setRunLoopMode:(NSString *)runLoopMode
{
if (runLoopMode != _runLoopMode) {
[self stopAnimating];
NSRunLoop *runloop = [NSRunLoop mainRunLoop];
[self.displayLink removeFromRunLoop:runloop forMode:_runLoopMode];
[self.displayLink addToRunLoop:runloop forMode:runLoopMode];
_runLoopMode = runLoopMode;
[self startAnimating];
}
}
- (void)setImage:(UIImage *)image
{
if (image == self.image) {
return;
}
[self stopAnimating];
self.currentFrameIndex = 0;
self.loopCountdown = 0;
self.accumulator = 0;
if ([image isKindOfClass:[DZYLGIFImage class]] && image.images) {
if([image.images[0] isKindOfClass:UIImage.class])
[super setImage:image.images[0]];
else
[super setImage:nil];
self.currentFrame = nil;
self.animatedImage = (DZYLGIFImage *)image;
self.loopCountdown = self.animatedImage.loopCount ?: NSUIntegerMax;
[self startAnimating];
} else {
self.animatedImage = nil;
[super setImage:image];
}
[self.layer setNeedsDisplay];
}
- (void)setAnimatedImage:(DZYLGIFImage *)animatedImage
{
_animatedImage = animatedImage;
if (animatedImage == nil) {
self.layer.contents = nil;
}
}
- (BOOL)isAnimating
{
return [super isAnimating] || (self.displayLink && !self.displayLink.isPaused);
}
- (void)stopAnimating
{
if (!self.animatedImage) {
[super stopAnimating];
return;
}
self.loopCountdown = 0;
self.displayLink.paused = YES;
}
- (void)startAnimating
{
if (!self.animatedImage) {
[super startAnimating];
return;
}
if (self.isAnimating) {
return;
}
self.loopCountdown = self.animatedImage.loopCount ?: NSUIntegerMax;
self.displayLink.paused = NO;
}
- (void)changeKeyframe:(CADisplayLink *)displayLink
{
if (self.currentFrameIndex >= [self.animatedImage.images count]) {
return;
}
self.accumulator += fmin(displayLink.duration, kMaxTimeStep);
while (self.accumulator >= self.animatedImage.frameDurations[self.currentFrameIndex]) {
self.accumulator -= self.animatedImage.frameDurations[self.currentFrameIndex];
if (++self.currentFrameIndex >= [self.animatedImage.images count]) {
if (--self.loopCountdown == 0) {
[self stopAnimating];
return;
}
self.currentFrameIndex = 0;
}
self.currentFrameIndex = MIN(self.currentFrameIndex, [self.animatedImage.images count] - 1);
self.currentFrame = [self.animatedImage getFrameWithIndex:self.currentFrameIndex];
[self.layer setNeedsDisplay];
}
}
- (void)displayLayer:(CALayer *)layer
{
if (!self.animatedImage || [self.animatedImage.images count] == 0) {
return;
}
//NSLog(@"display index: %luu", (unsigned long)self.currentFrameIndex);
if(self.currentFrame && ![self.currentFrame isKindOfClass:[NSNull class]])
layer.contents = (__bridge id)([self.currentFrame CGImage]);
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (self.window) {
[self startAnimating];
} else {
dispatch_async(dispatch_get_main_queue(), ^{
if (!self.window) {
[self stopAnimating];
}
});
}
}
- (void)didMoveToSuperview
{
[super didMoveToSuperview];
if (self.superview) {
//Has a superview, make sure it has a displayLink
[self displayLink];
} else {
//Doesn't have superview, let's check later if we need to remove the displayLink
dispatch_async(dispatch_get_main_queue(), ^{
[self displayLink];
});
}
}
- (void)setHighlighted:(BOOL)highlighted
{
if (!self.animatedImage) {
[super setHighlighted:highlighted];
}
}
- (UIImage *)image
{
return self.animatedImage ?: [super image];
}
- (CGSize)sizeThatFits:(CGSize)size
{
return self.image.size;
}
@end
//
// duiba_FMDeviceManager.h
// duiba_FMDeviceManager
//
// Copyright (c) 2016年 Tongdun.inc. All rights reserved.
//
#define FM_SDK_VERSION @"2.1.5"
#import <Foundation/Foundation.h>
#import <AdSupport/ASIdentifierManager.h>
#import <UIKit/UIKit.h>
#import <sys/sysctl.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if_dl.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <resolv.h>
#import <sys/stat.h>
#import <mach-o/dyld.h>
#import <dlfcn.h>
#import <sys/types.h>
#import <CommonCrypto/CommonDigest.h>
typedef struct duiba_void {
void (*initWithOptions)(NSDictionary *);
NSString *(*getDeviceInfo)();
} duiba_FMDeviceManager_t;
@interface duiba_FMDeviceManager : NSObject
+ (duiba_FMDeviceManager_t *) sharedManager;
+ (void) destroy;
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
<key>SDK version</key>
<string>V2.2.0</string>
</dict>
</plist>
//
// YLGIFImage.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLGIFImage : UIImage
///-----------------------
/// @name Image Attributes
///-----------------------
/**
A C array containing the frame durations.
The number of frames is defined by the count of the `images` array property.
*/
@property (nonatomic, readonly) NSTimeInterval *frameDurations;
/**
Total duration of the animated image.
*/
@property (nonatomic, readonly) NSTimeInterval totalDuration;
/**
Number of loops the image can do before it stops
*/
@property (nonatomic, readonly) NSUInteger loopCount;
- (UIImage*)getFrameWithIndex:(NSUInteger)idx;
@end
//
// YLImageView.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLImageView : UIImageView
@property (nonatomic, copy) NSString *runLoopMode;
@end
//
// TaAppWallView.h
// AdIOSSDK
//
// Created by lc on 16/11/4.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//应用墙
@interface TaAppWallView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
circle:(BOOL)circle
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaBaseActivityView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaSimpleWebViewController.h"
#import "TaUtils.h"
#import "DZYLImageView.h"
#import "DZYLGIFImage.h"
#define Ta_SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define Ta_SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
@interface TaBaseActivityView : UIView
@property (nonatomic,assign) BOOL canTap;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,strong) UIViewController *parentViewController;
@property (nonatomic,copy) void(^success)(void);
@property (nonatomic,copy) void(^failed)(void);
@property (nonatomic,copy) void(^closed)(void);
-(void)loadRequest;
@end
//
// TaBnView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//banner
@interface TaBnView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//浮标
@interface TaDriftView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//#import "TaAd.h"
//信息流
@interface TaInfoStreamerView : TaBaseActivityView
typedef NS_ENUM(NSInteger, TaInfoStreamType) {
TaInfoStreamTypeTall,//高的,比例为 750*420
TaInfoStreamTypeShort,//矮的,比例为 750*180
};
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
type:(TaInfoStreamType)type
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaLaunchScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/13.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//开屏广告
@interface TaLaunchScreenView : TaBaseActivityView
//构造方法,
+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose;
@end
//
// TaScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//插屏
@interface TaScreenView : TaBaseActivityView
//构造方法,
+(instancetype)adViewWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
//覆盖window
-(void)show;
@end
//
// TaSimpleWebViewController.h
// AdIOSSDK
//
// Created by lc on 16/11/6.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TaSimpleWebViewController : UIViewController
@property (nonatomic,strong) NSString *url;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,copy) void(^finished)(void);
@end
//
// TaStreamerView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//横幅
@interface TaStreamerView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaAd.h
// TaAd
//
// Created by lc on 16/11/8.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for TaAd.
FOUNDATION_EXPORT double TaAdVersionNumber;
//! Project version string for TaAd.
FOUNDATION_EXPORT const unsigned char TaAdVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <TaAd/PublicHeader.h>
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import "TaStreamerView.h"
#import "TaScreenView.h"
#import "TaInfoStreamerView.h"
#import "TaBnView.h"
#import "TaDriftView.h"
#import "TaAppWallView.h"
#import "TaLaunchScreenView.h"
#import "TaTmHelper.h"
#endif
/**
* 用户信息可见类型
*/
//
// TaTmHelper.h
// AdIOSSDK
//
// Created by lc on 16/11/1.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TaLaunchScreenView.h"
typedef void (^CloseLaunchADView) ();
#define kURL_ADDRESS @"https://engine.tuia.cn/api/v1/"
//#define kURL_ADDRESS @"http://engine.pre.duiba.com.cn/api/v1/"
//#define kURL_ADDRESS @"http://engine.tuiatest.cn/api/v1/"
//#define dzlog(...) NSLog(__VA_ARGS__)
//发布时解开
#define dzlog(...)
//推啊媒体广告SDK对外接口
@interface TaTmHelper : NSObject
@property (nonatomic,strong) NSString *appKey;
@property (nonatomic,strong) TaLaunchScreenView *launchScreenAdView;
// 关闭开屏活动页面的回调
@property (nonatomic, copy) CloseLaunchADView closeLaunchADView;
//用appkey初始化
+ (void)setupWithAppKey:(NSString *)key;
/**
推啊的单例
@return TaTmHelper
*/
+ (instancetype)helper;
//获取广告
+ (void)getActivitiesWithParameters:(NSDictionary*)param
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//获取非标准广告展示型
+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//非标准广告位 曝光上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位曝光接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)displayAdWithParam:(NSDictionary*)param;
//非标准广告位 点击上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位点击接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)clickAdWithParam:(NSDictionary*)param;
/**
标准tm位曝光成功、失败和点击的回调
@param success 曝光成功回调
@param failed 曝光失败回调
@param clicked 点击tm位回调
*/
+ (void)displaySuccess:(void(^)(id resultObj))success displayFailed:(void(^)(id resultObj))failed clickTm:(void(^)(id resultObj))clicked;
@end
//
// TaUtils.h
// AdIOSSDK
//
// Created by doulai on 12/7/16.
// Copyright © 2016 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface TaUtils : NSObject
+(void)addIconForView:(UIView*)parent paramter:(NSDictionary*)dic btn:(SEL )func caller:(UIView*)callself;
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Headers/DZYLGIFImage.h</key>
<data>
uf56hS5s4sVrM7x1spDY6ME2B80=
</data>
<key>Headers/DZYLImageView.h</key>
<data>
vAvO8excbSaOi29vUq5dU+h9XqE=
</data>
<key>Headers/TaAppWallView.h</key>
<data>
gKc0XlKkWMsvhzfTe+wWEt+uISs=
</data>
<key>Headers/TaBaseActivityView.h</key>
<data>
teabNVAUdwoykok5E+a8X0e5YOQ=
</data>
<key>Headers/TaBnView.h</key>
<data>
IycgppcKAzMbNmkm44e2p25U/3g=
</data>
<key>Headers/TaDriftView.h</key>
<data>
+rvgQSieSiZVxR/OHAJQZ3pby18=
</data>
<key>Headers/TaInfoStreamerView.h</key>
<data>
9yGvHJ8LoY3aomHFHmY8lmQPUGQ=
</data>
<key>Headers/TaLaunchScreenView.h</key>
<data>
wBBBUgcsTesj/5l4x7w9EcVLtqQ=
</data>
<key>Headers/TaScreenView.h</key>
<data>
cXznGKGNExVbvOfExZit2IxRtaY=
</data>
<key>Headers/TaSimpleWebViewController.h</key>
<data>
T4LsFf3X6SHw/E5EvRt888J4hd4=
</data>
<key>Headers/TaStreamerView.h</key>
<data>
RMewrCyxLMKUOjL+CpUKkGrVkoU=
</data>
<key>Headers/TaTm.h</key>
<data>
2LPayuyptZYDPFgh/xFBVvBNzek=
</data>
<key>Headers/TaTmHelper.h</key>
<data>
C/XTScJ/3G6FfmpZfAQNEG6/eBk=
</data>
<key>Headers/TaUtils.h</key>
<data>
2YC5JkKskBwIstsxMe/bAkaUC0c=
</data>
<key>Info.plist</key>
<data>
+tyB3y+h2z/+CiK3nH6NwyiVPaM=
</data>
<key>TuiaAd.bundle/tuia_close.png</key>
<data>
jpgn3mrtuNM8egCFsbSJ+dlARR8=
</data>
<key>TuiaAd.bundle/tuia_close@2x.png</key>
<data>
HAsezHwV2P3ymis/fWgvviCtAVc=
</data>
<key>TuiaAd.bundle/tuia_icon.png</key>
<data>
DJ41dO6DYPaZdLXC5C1jduIgIxM=
</data>
<key>TuiaAd.bundle/tuia_icon@2x.png</key>
<data>
I740lkMgouwUBOclrriBqE6KZZ0=
</data>
</dict>
<key>files2</key>
<dict>
<key>Headers/DZYLGIFImage.h</key>
<dict>
<key>hash</key>
<data>
uf56hS5s4sVrM7x1spDY6ME2B80=
</data>
<key>hash2</key>
<data>
Yaukvf2rtb7IcaiFPH75OhjdbRCwv7z7sJdhkGoMkjM=
</data>
</dict>
<key>Headers/DZYLImageView.h</key>
<dict>
<key>hash</key>
<data>
vAvO8excbSaOi29vUq5dU+h9XqE=
</data>
<key>hash2</key>
<data>
07AsbMDfoA0M942ChA4JWLmMMcOVXOMO4eKDMMYvjgk=
</data>
</dict>
<key>Headers/TaAppWallView.h</key>
<dict>
<key>hash</key>
<data>
gKc0XlKkWMsvhzfTe+wWEt+uISs=
</data>
<key>hash2</key>
<data>
OIcWcSEoo3v2hEdbyD4IbrLArgFhnan54zxB/9HyWyM=
</data>
</dict>
<key>Headers/TaBaseActivityView.h</key>
<dict>
<key>hash</key>
<data>
teabNVAUdwoykok5E+a8X0e5YOQ=
</data>
<key>hash2</key>
<data>
TEJGdpgWzXNhL1jCG2IlVYmhRI17uVn/cpuUM4FwEng=
</data>
</dict>
<key>Headers/TaBnView.h</key>
<dict>
<key>hash</key>
<data>
IycgppcKAzMbNmkm44e2p25U/3g=
</data>
<key>hash2</key>
<data>
lGBfmIqR5xK4HWcKZWTwmwdt1OkpObqSo4whFLbGU1A=
</data>
</dict>
<key>Headers/TaDriftView.h</key>
<dict>
<key>hash</key>
<data>
+rvgQSieSiZVxR/OHAJQZ3pby18=
</data>
<key>hash2</key>
<data>
6GAYOmqrNqSr6GBsc7e602RImuOqjpQSvj44muxdgXY=
</data>
</dict>
<key>Headers/TaInfoStreamerView.h</key>
<dict>
<key>hash</key>
<data>
9yGvHJ8LoY3aomHFHmY8lmQPUGQ=
</data>
<key>hash2</key>
<data>
HZrHZ4QpQo/MO2LXnzVPi49ipck0fOtfY09eKkkuFao=
</data>
</dict>
<key>Headers/TaLaunchScreenView.h</key>
<dict>
<key>hash</key>
<data>
wBBBUgcsTesj/5l4x7w9EcVLtqQ=
</data>
<key>hash2</key>
<data>
wFTEXYf65eSBl7YqYTzn8956sKEy8B4uDA0jmk3moYg=
</data>
</dict>
<key>Headers/TaScreenView.h</key>
<dict>
<key>hash</key>
<data>
cXznGKGNExVbvOfExZit2IxRtaY=
</data>
<key>hash2</key>
<data>
G29PY3ALWWq7qWqtpNCDcGz1o5uhMV0Ucx+ArysddHI=
</data>
</dict>
<key>Headers/TaSimpleWebViewController.h</key>
<dict>
<key>hash</key>
<data>
T4LsFf3X6SHw/E5EvRt888J4hd4=
</data>
<key>hash2</key>
<data>
8U+G63+hRKurDi/2WnZ01iJBHz5CDdNCs7iDjrcUg/o=
</data>
</dict>
<key>Headers/TaStreamerView.h</key>
<dict>
<key>hash</key>
<data>
RMewrCyxLMKUOjL+CpUKkGrVkoU=
</data>
<key>hash2</key>
<data>
b4YCgnlyiOVyqWaKU4hHYllfcWr0ytIodxYpBcvRwUk=
</data>
</dict>
<key>Headers/TaTm.h</key>
<dict>
<key>hash</key>
<data>
2LPayuyptZYDPFgh/xFBVvBNzek=
</data>
<key>hash2</key>
<data>
3ezJ1r3ARZCj3epPKaDGpXZ80s/IEc8BxgUL/QCFDvw=
</data>
</dict>
<key>Headers/TaTmHelper.h</key>
<dict>
<key>hash</key>
<data>
C/XTScJ/3G6FfmpZfAQNEG6/eBk=
</data>
<key>hash2</key>
<data>
LaRI+IoP8UhT/eQQMs3IJqintq2PWbwrmJ8+N9rJA2A=
</data>
</dict>
<key>Headers/TaUtils.h</key>
<dict>
<key>hash</key>
<data>
2YC5JkKskBwIstsxMe/bAkaUC0c=
</data>
<key>hash2</key>
<data>
DM24MShhFuP2vdfhDVmiig8Tnz+DgADPH/Lj4asjbsE=
</data>
</dict>
<key>TuiaAd.bundle/tuia_close.png</key>
<dict>
<key>hash</key>
<data>
jpgn3mrtuNM8egCFsbSJ+dlARR8=
</data>
<key>hash2</key>
<data>
h5XwyWqN6l2MawZ9HaCqiT+I/bx3lbjvJvB6tmLOIdo=
</data>
</dict>
<key>TuiaAd.bundle/tuia_close@2x.png</key>
<dict>
<key>hash</key>
<data>
HAsezHwV2P3ymis/fWgvviCtAVc=
</data>
<key>hash2</key>
<data>
RhwJz599t616kDJbB/PO7/bQD5yxJBLem8eVOyN4bVc=
</data>
</dict>
<key>TuiaAd.bundle/tuia_icon.png</key>
<dict>
<key>hash</key>
<data>
DJ41dO6DYPaZdLXC5C1jduIgIxM=
</data>
<key>hash2</key>
<data>
ZrHegU6oaYrKx/aPt1rf9Hyqr77tMAJ3nrTfV1Q6aEc=
</data>
</dict>
<key>TuiaAd.bundle/tuia_icon@2x.png</key>
<dict>
<key>hash</key>
<data>
I740lkMgouwUBOclrriBqE6KZZ0=
</data>
<key>hash2</key>
<data>
PVwbXoWhanfc5dMRsJjS4RMIBNwk8UZhgY4Uhs1elGI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
//
// TaAd.h
// TaAd
//
// Created by lc on 16/11/8.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for TaAd.
FOUNDATION_EXPORT double TaAdVersionNumber;
//! Project version string for TaAd.
FOUNDATION_EXPORT const unsigned char TaAdVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <TaAd/PublicHeader.h>
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import "TaStreamerView.h"
#import "TaScreenView.h"
#import "TaInfoStreamerView.h"
#import "TaBnView.h"
#import "TaDriftView.h"
#import "TaAppWallView.h"
#import "TaLaunchScreenView.h"
#import "TaTmHelper.h"
#endif
/**
* 用户信息可见类型
*/
//
// TaAd.m
// AdIOSSDK
//
// Created by doulai on 11/16/16.
// Copyright © 2016 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TaTm.h"
//@interface TaAd : NSObject
////用appkey初始化
//+ (void)setupWithAppKey:(NSString *)key;
//
////普通广告位
//+(instancetype)getAdViewPoint:(CGPoint)origin
// adsId:(NSString*)adsId
// type:(TaInfoStreamType)type
// circle:(BOOL)circle
// parentViewController:(UIViewController*)parentViewController
// successBlock:(void(^)(void))success
// failedBlock:(void(^)(void))failed;
//
//
////开屏广告
//+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
// successBlock:(void(^)(void))success
// failedBlock:(void(^)(void))failed
// finishedBlock:(void(^)(void))finished
// userCloseBlock:(void(^)(void))userClose;
//
////获取非标准广告展示型
//+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
// parentViewController:(UIViewController*)parentViewController
// successBlock:(void(^)(id resultObj))success
// failedBlock:(void(^)(id resultObj))failed;
////曝光
//+ (void)displayAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
////点击
//+ (void)clickAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
//
//@end
//@implementation TaAd
//+ (instancetype)shareInstance
//{
// static TaAd *task;
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// task = [[TaAd alloc] init];
//// NSString *sessionId= [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
//// task.token =sessionId;
//
// });
// return task;
//}
//
//+ (void)setupWithAppKey:(NSString *)key;
//{
// [TaTmHelper setupWithAppKey:key];
//}
//
////普通广告位
//+(instancetype)getAdViewPoint:(CGPoint)origin
// adsId:(NSString*)adsId
// type:(TaInfoStreamType)type
// circle:(BOOL)circle
// parentViewController:(UIViewController*)parentViewController
// successBlock:(void(^)(void))success
// failedBlock:(void(^)(void))failed;
//{
//
//}
//
//
////开屏广告
//+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
// successBlock:(void(^)(void))success
// failedBlock:(void(^)(void))failed
// finishedBlock:(void(^)(void))finished
// userCloseBlock:(void(^)(void))userClose;
//{
//
//}
//
////获取非标准广告展示型
//+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
// parentViewController:(UIViewController*)parentViewController
// successBlock:(void(^)(id resultObj))success
// failedBlock:(void(^)(id resultObj))failed;
//{
//
//}
////曝光
//+ (void)displayAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
//{
//
//}
////点击
//+ (void)clickAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
//{
//
//}
//@end
//
// YLGIFImage.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLGIFImage : UIImage
///-----------------------
/// @name Image Attributes
///-----------------------
/**
A C array containing the frame durations.
The number of frames is defined by the count of the `images` array property.
*/
@property (nonatomic, readonly) NSTimeInterval *frameDurations;
/**
Total duration of the animated image.
*/
@property (nonatomic, readonly) NSTimeInterval totalDuration;
/**
Number of loops the image can do before it stops
*/
@property (nonatomic, readonly) NSUInteger loopCount;
- (UIImage*)getFrameWithIndex:(NSUInteger)idx;
@end
//
// YLImageView.h
// YLGIFImage
//
// Created by Yong Li on 14-3-2.
// Copyright (c) 2014年 Yong Li. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DZYLImageView : UIImageView
@property (nonatomic, copy) NSString *runLoopMode;
@end
//
// TaAppWallView.h
// AdIOSSDK
//
// Created by lc on 16/11/4.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//应用墙
@interface TaAppWallView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
circle:(BOOL)circle
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaBaseActivityView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaSimpleWebViewController.h"
#import "TaUtils.h"
#import "DZYLImageView.h"
#import "DZYLGIFImage.h"
#define Ta_SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define Ta_SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
@interface TaBaseActivityView : UIView
@property (nonatomic,assign) BOOL canTap;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,strong) UIViewController *parentViewController;
@property (nonatomic,copy) void(^success)(void);
@property (nonatomic,copy) void(^failed)(void);
@property (nonatomic,copy) void(^closed)(void);
-(void)loadRequest;
@end
//
// TaBnView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//banner
@interface TaBnView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import "TaBaseActivityView.h"
//浮标
@interface TaDriftView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//#import "TaAd.h"
//信息流
@interface TaInfoStreamerView : TaBaseActivityView
typedef NS_ENUM(NSInteger, TaInfoStreamType) {
TaInfoStreamTypeTall,//高的,比例为 750*420
TaInfoStreamTypeShort,//矮的,比例为 750*180
};
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
type:(TaInfoStreamType)type
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaLaunchScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/13.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//开屏广告
@interface TaLaunchScreenView : TaBaseActivityView
//构造方法,
+(instancetype)showAdViewWithAdslotId:(NSString*)adslotId
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
finishedBlock:(void(^)(void))finished
userCloseBlock:(void(^)(void))userClose;
@end
//
// TaScreenView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//插屏
@interface TaScreenView : TaBaseActivityView
//构造方法,
+(instancetype)adViewWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
//覆盖window
-(void)show;
@end
//
// TaSimpleWebViewController.h
// AdIOSSDK
//
// Created by lc on 16/11/6.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TaSimpleWebViewController : UIViewController
@property (nonatomic,strong) NSString *url;
@property (nonatomic, strong) NSString* ad_title;
@property (nonatomic,copy) void(^finished)(void);
@end
//
// TaStreamerView.h
// AdIOSSDK
//
// Created by lc on 16/11/3.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TaBaseActivityView.h"
//横幅
@interface TaStreamerView : TaBaseActivityView
//构造方法,需要传入frame.orgin以确定广告视图位置
+(instancetype)adViewWithOrigin:(CGPoint)origin
adslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(void))success
failedBlock:(void(^)(void))failed
closedBlock:(void(^)(void))closed;
@end
//
// TaAd.h
// TaAd
//
// Created by lc on 16/11/8.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for TaAd.
FOUNDATION_EXPORT double TaAdVersionNumber;
//! Project version string for TaAd.
FOUNDATION_EXPORT const unsigned char TaAdVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <TaAd/PublicHeader.h>
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import "TaStreamerView.h"
#import "TaScreenView.h"
#import "TaInfoStreamerView.h"
#import "TaBnView.h"
#import "TaDriftView.h"
#import "TaAppWallView.h"
#import "TaLaunchScreenView.h"
#import "TaTmHelper.h"
#endif
/**
* 用户信息可见类型
*/
//
// TaTmHelper.h
// AdIOSSDK
//
// Created by lc on 16/11/1.
// Copyright © 2016年 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "TaLaunchScreenView.h"
typedef void (^CloseLaunchADView) ();
#define kURL_ADDRESS @"https://engine.tuia.cn/api/v1/"
//#define kURL_ADDRESS @"http://engine.pre.duiba.com.cn/api/v1/"
//#define kURL_ADDRESS @"http://test-engine.tuia.cn/api/v1/"
//#define dzlog(...) NSLog(__VA_ARGS__)
//发布时解开
#define dzlog(...)
//推啊媒体广告SDK对外接口
@interface TaTmHelper : NSObject
@property (nonatomic,strong) NSString *appKey;
@property (nonatomic,strong) TaLaunchScreenView *launchScreenAdView;
// 关闭开屏活动页面的回调
@property (nonatomic, copy) CloseLaunchADView closeLaunchADView;
//用appkey初始化
+ (void)setupWithAppKey:(NSString *)key;
/**
推啊的单例
@return TaTmHelper
*/
+ (instancetype)helper;
//获取广告
+ (void)getActivitiesWithParameters:(NSDictionary*)param
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//获取非标准广告展示型
+ (void)getActivityDataWithAdslotId:(NSString*)adslotId
parentViewController:(UIViewController*)parentViewController
successBlock:(void(^)(id resultObj))success
failedBlock:(void(^)(id resultObj))failed;
//非标准广告位 曝光上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位曝光接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)displayAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
//非标准广告位 点击上报(adslotId、activityId、requestId 参数为非标准广告位的请求到的对应参数)
/**
自定义广告位点击接口
(下列参数需要根据接入文档转换为需要的类型)
@param adslotId 请求到的 adslot_id
@param activityId 请求到的 activity_id
@param requestId 请求到的 request_id
*/
+ (void)clickAd:(NSString*)adslotId activityId:(NSString*)activityId requestId:(NSString*)requestId;
/**
标准tm位曝光成功、失败和点击的回调
@param success 曝光成功回调
@param failed 曝光失败回调
@param clicked 点击tm位回调
*/
+ (void)displaySuccess:(void(^)(id resultObj))success displayFailed:(void(^)(id resultObj))failed clickTm:(void(^)(id resultObj))clicked;
@end
//
// TaUtils.h
// AdIOSSDK
//
// Created by doulai on 12/7/16.
// Copyright © 2016 Ta. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface TaUtils : NSObject
+(void)addIconForView:(UIView*)parent paramter:(NSDictionary*)dic btn:(SEL )func caller:(UIView*)callself;
@end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Headers/DZYLGIFImage.h</key>
<data>
uf56hS5s4sVrM7x1spDY6ME2B80=
</data>
<key>Headers/DZYLImageView.h</key>
<data>
vAvO8excbSaOi29vUq5dU+h9XqE=
</data>
<key>Headers/TaAppWallView.h</key>
<data>
gKc0XlKkWMsvhzfTe+wWEt+uISs=
</data>
<key>Headers/TaBaseActivityView.h</key>
<data>
teabNVAUdwoykok5E+a8X0e5YOQ=
</data>
<key>Headers/TaBnView.h</key>
<data>
IycgppcKAzMbNmkm44e2p25U/3g=
</data>
<key>Headers/TaDriftView.h</key>
<data>
+rvgQSieSiZVxR/OHAJQZ3pby18=
</data>
<key>Headers/TaInfoStreamerView.h</key>
<data>
9yGvHJ8LoY3aomHFHmY8lmQPUGQ=
</data>
<key>Headers/TaLaunchScreenView.h</key>
<data>
wBBBUgcsTesj/5l4x7w9EcVLtqQ=
</data>
<key>Headers/TaScreenView.h</key>
<data>
cXznGKGNExVbvOfExZit2IxRtaY=
</data>
<key>Headers/TaSimpleWebViewController.h</key>
<data>
T4LsFf3X6SHw/E5EvRt888J4hd4=
</data>
<key>Headers/TaStreamerView.h</key>
<data>
RMewrCyxLMKUOjL+CpUKkGrVkoU=
</data>
<key>Headers/TaTm.h</key>
<data>
2LPayuyptZYDPFgh/xFBVvBNzek=
</data>
<key>Headers/TaTmHelper.h</key>
<data>
lqBG2VsHDnjU9PL7se5AJNMqfSc=
</data>
<key>Headers/TaUtils.h</key>
<data>
2YC5JkKskBwIstsxMe/bAkaUC0c=
</data>
<key>Info.plist</key>
<data>
+tyB3y+h2z/+CiK3nH6NwyiVPaM=
</data>
<key>TuiaAd.bundle/tuia_close.png</key>
<data>
jpgn3mrtuNM8egCFsbSJ+dlARR8=
</data>
<key>TuiaAd.bundle/tuia_close@2x.png</key>
<data>
HAsezHwV2P3ymis/fWgvviCtAVc=
</data>
<key>TuiaAd.bundle/tuia_icon.png</key>
<data>
DJ41dO6DYPaZdLXC5C1jduIgIxM=
</data>
<key>TuiaAd.bundle/tuia_icon@2x.png</key>
<data>
I740lkMgouwUBOclrriBqE6KZZ0=
</data>
</dict>
<key>files2</key>
<dict>
<key>Headers/DZYLGIFImage.h</key>
<dict>
<key>hash</key>
<data>
uf56hS5s4sVrM7x1spDY6ME2B80=
</data>
<key>hash2</key>
<data>
Yaukvf2rtb7IcaiFPH75OhjdbRCwv7z7sJdhkGoMkjM=
</data>
</dict>
<key>Headers/DZYLImageView.h</key>
<dict>
<key>hash</key>
<data>
vAvO8excbSaOi29vUq5dU+h9XqE=
</data>
<key>hash2</key>
<data>
07AsbMDfoA0M942ChA4JWLmMMcOVXOMO4eKDMMYvjgk=
</data>
</dict>
<key>Headers/TaAppWallView.h</key>
<dict>
<key>hash</key>
<data>
gKc0XlKkWMsvhzfTe+wWEt+uISs=
</data>
<key>hash2</key>
<data>
OIcWcSEoo3v2hEdbyD4IbrLArgFhnan54zxB/9HyWyM=
</data>
</dict>
<key>Headers/TaBaseActivityView.h</key>
<dict>
<key>hash</key>
<data>
teabNVAUdwoykok5E+a8X0e5YOQ=
</data>
<key>hash2</key>
<data>
TEJGdpgWzXNhL1jCG2IlVYmhRI17uVn/cpuUM4FwEng=
</data>
</dict>
<key>Headers/TaBnView.h</key>
<dict>
<key>hash</key>
<data>
IycgppcKAzMbNmkm44e2p25U/3g=
</data>
<key>hash2</key>
<data>
lGBfmIqR5xK4HWcKZWTwmwdt1OkpObqSo4whFLbGU1A=
</data>
</dict>
<key>Headers/TaDriftView.h</key>
<dict>
<key>hash</key>
<data>
+rvgQSieSiZVxR/OHAJQZ3pby18=
</data>
<key>hash2</key>
<data>
6GAYOmqrNqSr6GBsc7e602RImuOqjpQSvj44muxdgXY=
</data>
</dict>
<key>Headers/TaInfoStreamerView.h</key>
<dict>
<key>hash</key>
<data>
9yGvHJ8LoY3aomHFHmY8lmQPUGQ=
</data>
<key>hash2</key>
<data>
HZrHZ4QpQo/MO2LXnzVPi49ipck0fOtfY09eKkkuFao=
</data>
</dict>
<key>Headers/TaLaunchScreenView.h</key>
<dict>
<key>hash</key>
<data>
wBBBUgcsTesj/5l4x7w9EcVLtqQ=
</data>
<key>hash2</key>
<data>
wFTEXYf65eSBl7YqYTzn8956sKEy8B4uDA0jmk3moYg=
</data>
</dict>
<key>Headers/TaScreenView.h</key>
<dict>
<key>hash</key>
<data>
cXznGKGNExVbvOfExZit2IxRtaY=
</data>
<key>hash2</key>
<data>
G29PY3ALWWq7qWqtpNCDcGz1o5uhMV0Ucx+ArysddHI=
</data>
</dict>
<key>Headers/TaSimpleWebViewController.h</key>
<dict>
<key>hash</key>
<data>
T4LsFf3X6SHw/E5EvRt888J4hd4=
</data>
<key>hash2</key>
<data>
8U+G63+hRKurDi/2WnZ01iJBHz5CDdNCs7iDjrcUg/o=
</data>
</dict>
<key>Headers/TaStreamerView.h</key>
<dict>
<key>hash</key>
<data>
RMewrCyxLMKUOjL+CpUKkGrVkoU=
</data>
<key>hash2</key>
<data>
b4YCgnlyiOVyqWaKU4hHYllfcWr0ytIodxYpBcvRwUk=
</data>
</dict>
<key>Headers/TaTm.h</key>
<dict>
<key>hash</key>
<data>
2LPayuyptZYDPFgh/xFBVvBNzek=
</data>
<key>hash2</key>
<data>
3ezJ1r3ARZCj3epPKaDGpXZ80s/IEc8BxgUL/QCFDvw=
</data>
</dict>
<key>Headers/TaTmHelper.h</key>
<dict>
<key>hash</key>
<data>
lqBG2VsHDnjU9PL7se5AJNMqfSc=
</data>
<key>hash2</key>
<data>
+6ck4ACZ3kE/EZ51uP+sl4rkHaMMZKqyLHBzpPIu50E=
</data>
</dict>
<key>Headers/TaUtils.h</key>
<dict>
<key>hash</key>
<data>
2YC5JkKskBwIstsxMe/bAkaUC0c=
</data>
<key>hash2</key>
<data>
DM24MShhFuP2vdfhDVmiig8Tnz+DgADPH/Lj4asjbsE=
</data>
</dict>
<key>TuiaAd.bundle/tuia_close.png</key>
<dict>
<key>hash</key>
<data>
jpgn3mrtuNM8egCFsbSJ+dlARR8=
</data>
<key>hash2</key>
<data>
h5XwyWqN6l2MawZ9HaCqiT+I/bx3lbjvJvB6tmLOIdo=
</data>
</dict>
<key>TuiaAd.bundle/tuia_close@2x.png</key>
<dict>
<key>hash</key>
<data>
HAsezHwV2P3ymis/fWgvviCtAVc=
</data>
<key>hash2</key>
<data>
RhwJz599t616kDJbB/PO7/bQD5yxJBLem8eVOyN4bVc=
</data>
</dict>
<key>TuiaAd.bundle/tuia_icon.png</key>
<dict>
<key>hash</key>
<data>
DJ41dO6DYPaZdLXC5C1jduIgIxM=
</data>
<key>hash2</key>
<data>
ZrHegU6oaYrKx/aPt1rf9Hyqr77tMAJ3nrTfV1Q6aEc=
</data>
</dict>
<key>TuiaAd.bundle/tuia_icon@2x.png</key>
<dict>
<key>hash</key>
<data>
I740lkMgouwUBOclrriBqE6KZZ0=
</data>
<key>hash2</key>
<data>
PVwbXoWhanfc5dMRsJjS4RMIBNwk8UZhgY4Uhs1elGI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment