Commit 8b684d46 by 李雅珠

[comment] 添加IGLiveSDK的项目

[jira_id] none
[version] 0.1.0
parent 2c4f1d3b
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
044DD9DC2A445FCD00AF4F9E /* VIZNavigationController.m in Sources */ = {isa = PBXBuildFile; fileRef = 044DD9DB2A445FCD00AF4F9E /* VIZNavigationController.m */; };
4C335F75ACC0847DEFFF704E /* Pods_IGLiveSDK_Example.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DA4FD25D2FCF0D677E147549 /* Pods_IGLiveSDK_Example.framework */; }; 4C335F75ACC0847DEFFF704E /* Pods_IGLiveSDK_Example.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DA4FD25D2FCF0D677E147549 /* Pods_IGLiveSDK_Example.framework */; };
6003F58E195388D20070C39A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; }; 6003F58E195388D20070C39A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58D195388D20070C39A /* Foundation.framework */; };
6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58F195388D20070C39A /* CoreGraphics.framework */; }; 6003F590195388D20070C39A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6003F58F195388D20070C39A /* CoreGraphics.framework */; };
...@@ -38,6 +39,8 @@ ...@@ -38,6 +39,8 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
019A8EDCC150122F77DD8365 /* Pods-IGLiveSDK_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Example.release.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example.release.xcconfig"; sourceTree = "<group>"; }; 019A8EDCC150122F77DD8365 /* Pods-IGLiveSDK_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Example.release.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example.release.xcconfig"; sourceTree = "<group>"; };
044DD9DA2A445FCD00AF4F9E /* VIZNavigationController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = VIZNavigationController.h; sourceTree = "<group>"; };
044DD9DB2A445FCD00AF4F9E /* VIZNavigationController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = VIZNavigationController.m; sourceTree = "<group>"; };
3FD3AAAB760CDB861EB32BCA /* Pods_IGLiveSDK_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_IGLiveSDK_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3FD3AAAB760CDB861EB32BCA /* Pods_IGLiveSDK_Tests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_IGLiveSDK_Tests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
6003F58A195388D20070C39A /* IGLiveSDK_Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = IGLiveSDK_Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6003F58A195388D20070C39A /* IGLiveSDK_Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = IGLiveSDK_Example.app; sourceTree = BUILT_PRODUCTS_DIR; };
6003F58D195388D20070C39A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 6003F58D195388D20070C39A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
...@@ -60,9 +63,9 @@ ...@@ -60,9 +63,9 @@
606FC2411953D9B200FFA9A0 /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = "<group>"; }; 606FC2411953D9B200FFA9A0 /* Tests-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Tests-Prefix.pch"; sourceTree = "<group>"; };
71719F9E1E33DC2100824A3D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; }; 71719F9E1E33DC2100824A3D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
873B8AEA1B1F5CCA007FD442 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = Main.storyboard; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; }; 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = Main.storyboard; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
A0A61CD7F01B96C23D8A66E5 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; name = README.md; path = ../README.md; sourceTree = "<group>"; }; A0A61CD7F01B96C23D8A66E5 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = ../README.md; sourceTree = "<group>"; };
A124F6D139894622AE04F0CF /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; name = LICENSE; path = ../LICENSE; sourceTree = "<group>"; }; A124F6D139894622AE04F0CF /* LICENSE */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = LICENSE; path = ../LICENSE; sourceTree = "<group>"; };
A15ABBC141EB193392630184 /* IGLiveSDK.podspec */ = {isa = PBXFileReference; includeInIndex = 1; name = IGLiveSDK.podspec; path = ../IGLiveSDK.podspec; sourceTree = "<group>"; }; A15ABBC141EB193392630184 /* IGLiveSDK.podspec */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; name = IGLiveSDK.podspec; path = ../IGLiveSDK.podspec; sourceTree = "<group>"; };
A84A9763CF95B069E18D0208 /* Pods-IGLiveSDK_Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Example.debug.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example.debug.xcconfig"; sourceTree = "<group>"; }; A84A9763CF95B069E18D0208 /* Pods-IGLiveSDK_Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Example.debug.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example.debug.xcconfig"; sourceTree = "<group>"; };
AC03B0B2625D32364DA6B1AE /* Pods-IGLiveSDK_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Tests.debug.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Tests/Pods-IGLiveSDK_Tests.debug.xcconfig"; sourceTree = "<group>"; }; AC03B0B2625D32364DA6B1AE /* Pods-IGLiveSDK_Tests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IGLiveSDK_Tests.debug.xcconfig"; path = "Target Support Files/Pods-IGLiveSDK_Tests/Pods-IGLiveSDK_Tests.debug.xcconfig"; sourceTree = "<group>"; };
DA4FD25D2FCF0D677E147549 /* Pods_IGLiveSDK_Example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_IGLiveSDK_Example.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DA4FD25D2FCF0D677E147549 /* Pods_IGLiveSDK_Example.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_IGLiveSDK_Example.framework; sourceTree = BUILT_PRODUCTS_DIR; };
...@@ -103,7 +106,6 @@ ...@@ -103,7 +106,6 @@
AC03B0B2625D32364DA6B1AE /* Pods-IGLiveSDK_Tests.debug.xcconfig */, AC03B0B2625D32364DA6B1AE /* Pods-IGLiveSDK_Tests.debug.xcconfig */,
F1844C37CBD589AD3C7F36BF /* Pods-IGLiveSDK_Tests.release.xcconfig */, F1844C37CBD589AD3C7F36BF /* Pods-IGLiveSDK_Tests.release.xcconfig */,
); );
name = Pods;
path = Pods; path = Pods;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
...@@ -149,6 +151,8 @@ ...@@ -149,6 +151,8 @@
873B8AEA1B1F5CCA007FD442 /* Main.storyboard */, 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */,
6003F5A5195388D20070C39A /* VIZViewController.h */, 6003F5A5195388D20070C39A /* VIZViewController.h */,
6003F5A6195388D20070C39A /* VIZViewController.m */, 6003F5A6195388D20070C39A /* VIZViewController.m */,
044DD9DA2A445FCD00AF4F9E /* VIZNavigationController.h */,
044DD9DB2A445FCD00AF4F9E /* VIZNavigationController.m */,
71719F9D1E33DC2100824A3D /* LaunchScreen.storyboard */, 71719F9D1E33DC2100824A3D /* LaunchScreen.storyboard */,
6003F5A8195388D20070C39A /* Images.xcassets */, 6003F5A8195388D20070C39A /* Images.xcassets */,
6003F594195388D20070C39A /* Supporting Files */, 6003F594195388D20070C39A /* Supporting Files */,
...@@ -209,6 +213,7 @@ ...@@ -209,6 +213,7 @@
6003F587195388D20070C39A /* Frameworks */, 6003F587195388D20070C39A /* Frameworks */,
6003F588195388D20070C39A /* Resources */, 6003F588195388D20070C39A /* Resources */,
CBE008F79EB66945C970125F /* [CP] Embed Pods Frameworks */, CBE008F79EB66945C970125F /* [CP] Embed Pods Frameworks */,
56EAA632364910D1CF4A5BCA /* [CP] Copy Pods Resources */,
); );
buildRules = ( buildRules = (
); );
...@@ -258,6 +263,7 @@ ...@@ -258,6 +263,7 @@
developmentRegion = English; developmentRegion = English;
hasScannedForEncodings = 0; hasScannedForEncodings = 0;
knownRegions = ( knownRegions = (
English,
en, en,
Base, Base,
); );
...@@ -295,6 +301,24 @@ ...@@ -295,6 +301,24 @@
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */
56EAA632364910D1CF4A5BCA /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example-resources.sh",
"${PODS_CONFIGURATION_BUILD_DIR}/IGLiveSDK/IGLiveSDK.bundle",
);
name = "[CP] Copy Pods Resources";
outputPaths = (
"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/IGLiveSDK.bundle",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example-resources.sh\"\n";
showEnvVarsInLog = 0;
};
92AA0D0C07C5D509F96BBDBF /* [CP] Check Pods Manifest.lock */ = { 92AA0D0C07C5D509F96BBDBF /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
...@@ -346,11 +370,25 @@ ...@@ -346,11 +370,25 @@
); );
inputPaths = ( inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example-frameworks.sh", "${PODS_ROOT}/Target Support Files/Pods-IGLiveSDK_Example/Pods-IGLiveSDK_Example-frameworks.sh",
"${BUILT_PRODUCTS_DIR}/IGLiveSDK/IGLiveSDK.framework", "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework",
"${PODS_ROOT}/AliPlayerSDK_iOS/AliyunPlayer.framework",
"${PODS_ROOT}/AliPlayerSDK_iOS/alivcffmpeg.framework",
"${PODS_ROOT}/AliPlayerSDK_iOS/AliyunMediaDownloader.framework",
"${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework",
"${BUILT_PRODUCTS_DIR}/MJExtension/MJExtension.framework",
"${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework",
"${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework",
); );
name = "[CP] Embed Pods Frameworks"; name = "[CP] Embed Pods Frameworks";
outputPaths = ( outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IGLiveSDK.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AliyunPlayer.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/alivcffmpeg.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AliyunMediaDownloader.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MBProgressHUD.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJExtension.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework",
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh; shellPath = /bin/sh;
...@@ -365,6 +403,7 @@ ...@@ -365,6 +403,7 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
6003F59E195388D20070C39A /* VIZAppDelegate.m in Sources */, 6003F59E195388D20070C39A /* VIZAppDelegate.m in Sources */,
044DD9DC2A445FCD00AF4F9E /* VIZNavigationController.m in Sources */,
6003F5A7195388D20070C39A /* VIZViewController.m in Sources */, 6003F5A7195388D20070C39A /* VIZViewController.m in Sources */,
6003F59A195388D20070C39A /* main.m in Sources */, 6003F59A195388D20070C39A /* main.m in Sources */,
); );
......
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:IGLiveSDK.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13771" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="whP-gf-Uak"> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="21701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="JSL-2C-LmU">
<device id="retina4_7" orientation="portrait"> <device id="retina4_7" orientation="portrait" appearance="light"/>
<adaptation id="fullscreen"/>
</device>
<dependencies> <dependencies>
<deployment identifier="iOS"/> <deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13772"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="21678"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies> </dependencies>
<scenes> <scenes>
<!--Navigation Controller-->
<scene sceneID="8tb-Fd-pG9">
<objects>
<navigationController id="JSL-2C-LmU" customClass="VIZNavigationController" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="Uaa-sI-j2j">
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="whP-gf-Uak" kind="relationship" relationship="rootViewController" id="jv5-qp-HBz"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="Y2W-sI-t69" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-1111" y="332"/>
</scene>
<!--View Controller--> <!--View Controller-->
<scene sceneID="wQg-tq-qST"> <scene sceneID="wQg-tq-qST">
<objects> <objects>
...@@ -22,10 +36,11 @@ ...@@ -22,10 +36,11 @@
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view> </view>
<navigationItem key="navigationItem" id="8Tp-lT-KFG"/>
</viewController> </viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="tc2-Qw-aMS" userLabel="First Responder" sceneMemberID="firstResponder"/> <placeholder placeholderIdentifier="IBFirstResponder" id="tc2-Qw-aMS" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects> </objects>
<point key="canvasLocation" x="305" y="433"/> <point key="canvasLocation" x="-246" y="331"/>
</scene> </scene>
</scenes> </scenes>
</document> </document>
...@@ -24,6 +24,11 @@ ...@@ -24,6 +24,11 @@
<string>1.0</string> <string>1.0</string>
<key>LSRequiresIPhoneOS</key> <key>LSRequiresIPhoneOS</key>
<true/> <true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UILaunchStoryboardName</key> <key>UILaunchStoryboardName</key>
<string>LaunchScreen</string> <string>LaunchScreen</string>
<key>UIMainStoryboardFile</key> <key>UIMainStoryboardFile</key>
......
//
// VIZNavigationController.h
// IGLiveSDK_Example
//
// Created by mac on 2023/6/22.
// Copyright © 2023 李雅珠. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface VIZNavigationController : UINavigationController
@end
NS_ASSUME_NONNULL_END
//
// VIZNavigationController.m
// IGLiveSDK_Example
//
// Created by mac on 2023/6/22.
// Copyright © 2023 李雅珠. All rights reserved.
//
#import "VIZNavigationController.h"
@interface VIZNavigationController ()
@end
@implementation VIZNavigationController
- (BOOL)shouldAutorotate{
return [self.topViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
@end
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
// //
#import "VIZViewController.h" #import "VIZViewController.h"
#import <IGLiveSDK/IGLiveSDK.h>
@interface VIZViewController () @interface VIZViewController ()
...@@ -17,7 +18,10 @@ ...@@ -17,7 +18,10 @@
- (void)viewDidLoad - (void)viewDidLoad
{ {
[super viewDidLoad]; [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageV.backgroundColor = [UIColor redColor];
imageV.image = [self getImageWithName:@"back_i"];
[self.view addSubview:imageV];
} }
- (void)didReceiveMemoryWarning - (void)didReceiveMemoryWarning
...@@ -26,4 +30,46 @@ ...@@ -26,4 +30,46 @@
// Dispose of any resources that can be recreated. // Dispose of any resources that can be recreated.
} }
- (UIImage *)getImageWithName:(NSString *)imageName {
NSString *oneBundle = [[NSBundle mainBundle] pathForResource:@"IGLiveSDK" ofType:@"bundle"];
NSString *newFilePath = [oneBundle stringByAppendingFormat:@"/%@@2x.png",imageName];
UIImage *oneImage = [UIImage imageWithContentsOfFile:newFilePath];
if (oneImage == nil) {
oneImage = [UIImage imageNamed:imageName];
}
return oneImage;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 强制横屏
UIDevice *device = [UIDevice currentDevice];
if (device.orientation == UIInterfaceOrientationLandscapeLeft) {
NSNumber *value = @(UIInterfaceOrientationLandscapeLeft);
[device setValue:value forKey:@"orientation"];
} else if (device.orientation == UIInterfaceOrientationLandscapeRight) {
NSNumber *value = @(UIInterfaceOrientationLandscapeRight);
[device setValue:value forKey:@"orientation"];
} else {
NSNumber *value = @(UIInterfaceOrientationLandscapeRight);
[device setValue:value forKey:@"orientation"];
}
VIZEpisodeListModel *listModel = [[VIZEpisodeListModel alloc] init];
// 播放地址
listModel.appStreamUrl = @"http://42.193.106.159/flv/1653365933741";
// 节目id
listModel.episodeId = @"1657935454060613633";
// 登录的账号id
listModel.account = @"2023051201";
VIZPlayerViewController* videoVC=[[VIZPlayerViewController alloc]init];
videoVC.pModel = listModel;
[self.navigationController pushViewController:videoVC animated:YES];
}
@end @end
PODS:
- AFNetworking (4.0.1):
- AFNetworking/NSURLSession (= 4.0.1)
- AFNetworking/Reachability (= 4.0.1)
- AFNetworking/Security (= 4.0.1)
- AFNetworking/Serialization (= 4.0.1)
- AFNetworking/UIKit (= 4.0.1)
- AFNetworking/NSURLSession (4.0.1):
- AFNetworking/Reachability
- AFNetworking/Security
- AFNetworking/Serialization
- AFNetworking/Reachability (4.0.1)
- AFNetworking/Security (4.0.1)
- AFNetworking/Serialization (4.0.1)
- AFNetworking/UIKit (4.0.1):
- AFNetworking/NSURLSession
- AliPlayerSDK_iOS (5.4.2.0):
- AliPlayerSDK_iOS/AliPlayerSDK (= 5.4.2.0)
- AliPlayerSDK_iOS/AliPlayerSDK (5.4.2.0)
- IGLiveSDK (0.1.0):
- AFNetworking (= 4.0.1)
- AliPlayerSDK_iOS (= 5.4.2.0)
- Masonry
- MBProgressHUD
- MJExtension
- SDWebImage
- Masonry (1.1.0)
- MBProgressHUD (1.2.0)
- MJExtension (3.4.1)
- SDWebImage (5.16.0):
- SDWebImage/Core (= 5.16.0)
- SDWebImage/Core (5.16.0)
DEPENDENCIES:
- IGLiveSDK (from `../`)
SPEC REPOS:
trunk:
- AFNetworking
- AliPlayerSDK_iOS
- Masonry
- MBProgressHUD
- MJExtension
- SDWebImage
EXTERNAL SOURCES:
IGLiveSDK:
:path: "../"
SPEC CHECKSUMS:
AFNetworking: 3bd23d814e976cd148d7d44c3ab78017b744cd58
AliPlayerSDK_iOS: 6f7cc2a5a6634c8638d59d50f5675640efbd4aa7
IGLiveSDK: d164c7f24d5bfbe92f3c08ac8a7983f0ec85f628
Masonry: 678fab65091a9290e40e2832a55e7ab731aad201
MBProgressHUD: 3ee5efcc380f6a79a7cc9b363dd669c5e1ae7406
MJExtension: 21c5f6f8c4d5d8844b7ae8fbae08fed0b501f961
SDWebImage: 2aea163b50bfcb569a2726b6a754c54a4506fcf6
PODFILE CHECKSUM: a5d034ea0b34cbab0ba130195db19e39939b49f6
COCOAPODS: 1.12.1
// AFCompatibilityMacros.h
// Copyright (c) 2011–2016 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.
#ifndef AFCompatibilityMacros_h
#define AFCompatibilityMacros_h
#ifdef API_AVAILABLE
#define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__)
#else
#define AF_API_AVAILABLE(...)
#endif // API_AVAILABLE
#ifdef API_UNAVAILABLE
#define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__)
#else
#define AF_API_UNAVAILABLE(...)
#endif // API_UNAVAILABLE
#if __has_warning("-Wunguarded-availability-new")
#define AF_CAN_USE_AT_AVAILABLE 1
#else
#define AF_CAN_USE_AT_AVAILABLE 0
#endif
#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000))
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0
#else
#define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1
#endif
#endif /* AFCompatibilityMacros_h */
// AFNetworkReachabilityManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,
AFNetworkReachabilityStatusNotReachable = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,
};
NS_ASSUME_NONNULL_BEGIN
/**
`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.
See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ )
@warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
*/
@interface AFNetworkReachabilityManager : NSObject
/**
The current network reachability status.
*/
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
/**
Whether or not the network is currently reachable.
*/
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;
/**
Whether or not the network is currently reachable via WWAN.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;
/**
Whether or not the network is currently reachable via WiFi.
*/
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;
///---------------------
/// @name Initialization
///---------------------
/**
Returns the shared network reachability manager.
*/
+ (instancetype)sharedManager;
/**
Creates and returns a network reachability manager with the default socket address.
@return An initialized network reachability manager, actively monitoring the default socket address.
*/
+ (instancetype)manager;
/**
Creates and returns a network reachability manager for the specified domain.
@param domain The domain used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified domain.
*/
+ (instancetype)managerForDomain:(NSString *)domain;
/**
Creates and returns a network reachability manager for the socket address.
@param address The socket address (`sockaddr_in6`) used to evaluate network reachability.
@return An initialized network reachability manager, actively monitoring the specified socket address.
*/
+ (instancetype)managerForAddress:(const void *)address;
/**
Initializes an instance of a network reachability manager from the specified reachability object.
@param reachability The reachability object to monitor.
@return An initialized network reachability manager, actively monitoring the specified reachability.
*/
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;
/**
* Unavailable initializer
*/
+ (instancetype)new NS_UNAVAILABLE;
/**
* Unavailable initializer
*/
- (instancetype)init NS_UNAVAILABLE;
///--------------------------------------------------
/// @name Starting & Stopping Reachability Monitoring
///--------------------------------------------------
/**
Starts monitoring for changes in network reachability status.
*/
- (void)startMonitoring;
/**
Stops monitoring for changes in network reachability status.
*/
- (void)stopMonitoring;
///-------------------------------------------------
/// @name Getting Localized Reachability Description
///-------------------------------------------------
/**
Returns a localized string representation of the current network reachability status.
*/
- (NSString *)localizedNetworkReachabilityStatusString;
///---------------------------------------------------
/// @name Setting Network Reachability Change Callback
///---------------------------------------------------
/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
*/
- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;
@end
///----------------
/// @name Constants
///----------------
/**
## Network Reachability
The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.
enum {
AFNetworkReachabilityStatusUnknown,
AFNetworkReachabilityStatusNotReachable,
AFNetworkReachabilityStatusReachableViaWWAN,
AFNetworkReachabilityStatusReachableViaWiFi,
}
`AFNetworkReachabilityStatusUnknown`
The `baseURL` host reachability is not known.
`AFNetworkReachabilityStatusNotReachable`
The `baseURL` host cannot be reached.
`AFNetworkReachabilityStatusReachableViaWWAN`
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
`AFNetworkReachabilityStatusReachableViaWiFi`
The `baseURL` host can be reached via a Wi-Fi connection.
### Keys for Notification UserInfo Dictionary
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
`AFNetworkingReachabilityNotificationStatusItem`
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
*/
///--------------------
/// @name Notifications
///--------------------
/**
Posted when network reachability changes.
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
*/
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification;
FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem;
///--------------------
/// @name Functions
///--------------------
/**
Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
*/
FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);
NS_ASSUME_NONNULL_END
#endif
// AFNetworking.h
//
// Copyright (c) 2013 AFNetworking (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>
#import <TargetConditionals.h>
#ifndef _AFNETWORKING_
#define _AFNETWORKING_
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h"
#import "AFSecurityPolicy.h"
#if !TARGET_OS_WATCH
#import "AFNetworkReachabilityManager.h"
#endif
#import "AFURLSessionManager.h"
#import "AFHTTPSessionManager.h"
#endif /* _AFNETWORKING_ */
// AFSecurityPolicy.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Security/Security.h>
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
};
/**
`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections.
Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled.
*/
NS_ASSUME_NONNULL_BEGIN
@interface AFSecurityPolicy : NSObject <NSSecureCoding, NSCopying>
/**
The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`.
*/
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/**
The certificates used to evaluate server trust according to the SSL pinning mode.
Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches.
@see policyWithPinningMode:withPinnedCertificates:
*/
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
/**
Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`.
*/
@property (nonatomic, assign) BOOL allowInvalidCertificates;
/**
Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`.
*/
@property (nonatomic, assign) BOOL validatesDomainName;
///-----------------------------------------
/// @name Getting Certificates from the Bundle
///-----------------------------------------
/**
Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`.
@return The certificates included in the given bundle.
*/
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
///-----------------------------------------
/// @name Getting Specific Security Policies
///-----------------------------------------
/**
Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys.
@return The default security policy.
*/
+ (instancetype)defaultPolicy;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a security policy with the specified pinning mode.
Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead.
@param pinningMode The SSL pinning mode.
@return A new security policy.
@see -policyWithPinningMode:withPinnedCertificates:
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
/**
Creates and returns a security policy with the specified pinning mode.
@param pinningMode The SSL pinning mode.
@param pinnedCertificates The certificates to pin against.
@return A new security policy.
@see +certificatesInBundle:
@see -pinnedCertificates
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
///------------------------------
/// @name Evaluating Server Trust
///------------------------------
/**
Whether or not the specified server trust should be accepted, based on the security policy.
This method should be used when responding to an authentication challenge from a server.
@param serverTrust The X.509 certificate trust of the server.
@param domain The domain of serverTrust. If `nil`, the domain will not be validated.
@return Whether or not to trust the server.
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(nullable NSString *)domain;
@end
NS_ASSUME_NONNULL_END
///----------------
/// @name Constants
///----------------
/**
## SSL Pinning Modes
The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
}
`AFSSLPinningModeNone`
Do not used pinned certificates to validate servers.
`AFSSLPinningModePublicKey`
Validate host certificates against public keys of pinned certificates.
`AFSSLPinningModeCertificate`
Validate host certificates against pinned certificates.
*/
Copyright (c) 2011-2020 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.
// AFAutoPurgingImageCache.h
// Copyright (c) 2011–2016 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 AFImageCache <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 AFImageRequestCache <AFImageCache>
/**
Asks if the image should be cached using an identifier created from the request and additional identifier.
@param image The image to be cached.
@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 the image should be added to the cache. YES will cache, NO will prevent caching.
*/
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
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 AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
/**
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 preferredMemoryCapacity 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–2016 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 "AFAutoPurgingImageCache.h"
@interface AFCachedImage : NSObject
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, assign) UInt64 totalBytes;
@property (nonatomic, strong) NSDate *lastAccessDate;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@end
@implementation AFCachedImage
- (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 bytesPerSize = imageSize.width * imageSize.height;
self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
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 AFAutoPurgingImageCache ()
@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@end
@implementation AFAutoPurgingImageCache
- (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, ^{
AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
AFCachedImage *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 <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
ascending:YES];
[sortedImages sortUsingDescriptors:@[sortDescriptor]];
UInt64 bytesPurged = 0;
for (AFCachedImage *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, ^{
AFCachedImage *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, ^{
AFCachedImage *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;
}
- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier {
return YES;
}
@end
#endif
// AFImageDownloader.h
// Copyright (c) 2011–2016 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 "AFAutoPurgingImageCache.h"
#import "AFHTTPSessionManager.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
AFImageDownloadPrioritizationFIFO,
AFImageDownloadPrioritizationLIFO
};
/**
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 AFImageDownloadReceipt : 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 AFImageDownloader : NSObject
/**
The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
*/
@property (nonatomic, strong, nullable) id <AFImageRequestCache> 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) AFHTTPSessionManager *sessionManager;
/**
Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
*/
@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization;
/**
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;
/**
The default `NSURLSessionConfiguration` with common usage parameter values.
*/
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration;
/**
Default initializer
@return An instance of `AFImageDownloader` initialized with default values.
*/
- (instancetype)init;
/**
Initializer with specific `URLSessionConfiguration`
@param configuration The `NSURLSessionConfiguration` to be be used
@return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration`
*/
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
/**
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:(AFHTTPSessionManager *)sessionManager
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(nullable id <AFImageRequestCache>)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 AFImageDownloadReceipt *)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 receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
@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 AFImageDownloadReceipt *)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:(AFImageDownloadReceipt *)imageDownloadReceipt;
@end
#endif
NS_ASSUME_NONNULL_END
// AFNetworkActivityIndicatorManager.h
// Copyright (c) 2011–2016 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
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
*/
NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
@interface AFNetworkActivityIndicatorManager : NSObject
/**
A Boolean value indicating whether the manager is enabled.
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
*/
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
/**
A Boolean value indicating whether the network activity indicator manager is currently active.
*/
@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
/**
A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
Apple's HIG describes the following:
> Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
*/
@property (nonatomic, assign) NSTimeInterval activationDelay;
/**
A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
*/
@property (nonatomic, assign) NSTimeInterval completionDelay;
/**
Returns the shared network activity indicator manager object for the system.
@return The systemwide network activity indicator manager.
*/
+ (instancetype)sharedManager;
/**
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
*/
- (void)incrementActivityCount;
/**
Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
*/
- (void)decrementActivityCount;
/**
Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
@param block A block to be executed when the network activity indicator status changes.
*/
- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
@end
NS_ASSUME_NONNULL_END
#endif
// AFNetworkActivityIndicatorManager.m
// Copyright (c) 2011–2016 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 "AFNetworkActivityIndicatorManager.h"
#if TARGET_OS_IOS
#import "AFURLSessionManager.h"
typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
AFNetworkActivityManagerStateNotActive,
AFNetworkActivityManagerStateDelayingStart,
AFNetworkActivityManagerStateActive,
AFNetworkActivityManagerStateDelayingEnd
};
static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
return [(NSURLSessionTask *)[notification object] originalRequest];
} else {
return nil;
}
}
typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
@interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
@property (nonatomic, assign) AFNetworkActivityManagerState currentState;
@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateCurrentStateForNetworkActivityChange;
@end
@implementation AFNetworkActivityIndicatorManager
+ (instancetype)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedManager = [[self alloc] init];
});
return _sharedManager;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.currentState = AFNetworkActivityManagerStateNotActive;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_activationDelayTimer invalidate];
[_completionDelayTimer invalidate];
}
- (void)setEnabled:(BOOL)enabled {
_enabled = enabled;
if (enabled == NO) {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
}
- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
self.networkActivityActionBlock = block;
}
- (BOOL)isNetworkActivityOccurring {
@synchronized(self) {
return self.activityCount > 0;
}
}
- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
@synchronized(self) {
_networkActivityIndicatorVisible = networkActivityIndicatorVisible;
}
if (self.networkActivityActionBlock) {
self.networkActivityActionBlock(networkActivityIndicatorVisible);
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
}
}
}
- (void)incrementActivityCount {
@synchronized(self) {
self.activityCount++;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange];
});
}
- (void)decrementActivityCount {
@synchronized(self) {
self.activityCount = MAX(_activityCount - 1, 0);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange];
});
}
- (void)networkRequestDidStart:(NSNotification *)notification {
if ([AFNetworkRequestFromNotification(notification) URL]) {
[self incrementActivityCount];
}
}
- (void)networkRequestDidFinish:(NSNotification *)notification {
if ([AFNetworkRequestFromNotification(notification) URL]) {
[self decrementActivityCount];
}
}
#pragma mark - Internal State Management
- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
@synchronized(self) {
if (_currentState != currentState) {
_currentState = currentState;
switch (currentState) {
case AFNetworkActivityManagerStateNotActive:
[self cancelActivationDelayTimer];
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:NO];
break;
case AFNetworkActivityManagerStateDelayingStart:
[self startActivationDelayTimer];
break;
case AFNetworkActivityManagerStateActive:
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:YES];
break;
case AFNetworkActivityManagerStateDelayingEnd:
[self startCompletionDelayTimer];
break;
}
}
}
}
- (void)updateCurrentStateForNetworkActivityChange {
if (self.enabled) {
switch (self.currentState) {
case AFNetworkActivityManagerStateNotActive:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
}
break;
case AFNetworkActivityManagerStateDelayingStart:
//No op. Let the delay timer finish out.
break;
case AFNetworkActivityManagerStateActive:
if (!self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
}
break;
case AFNetworkActivityManagerStateDelayingEnd:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
}
break;
}
}
}
- (void)startActivationDelayTimer {
self.activationDelayTimer = [NSTimer
timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)activationDelayTimerFired {
if (self.networkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
} else {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
}
- (void)startCompletionDelayTimer {
[self.completionDelayTimer invalidate];
self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)completionDelayTimerFired {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
- (void)cancelActivationDelayTimer {
[self.activationDelayTimer invalidate];
}
- (void)cancelCompletionDelayTimer {
[self.completionDelayTimer invalidate];
}
@end
#endif
// UIActivityIndicatorView+AFNetworking.h
// Copyright (c) 2011–2016 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>
/**
This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task.
*/
@interface UIActivityIndicatorView (AFNetworking)
///----------------------------------
/// @name Animating for Session Tasks
///----------------------------------
/**
Binds the animating state to the state of the specified task.
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
@end
#endif
// UIActivityIndicatorView+AFNetworking.m
// Copyright (c) 2011–2016 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 "UIActivityIndicatorView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFURLSessionManager.h"
@interface AFActivityIndicatorViewNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
@end
@implementation UIActivityIndicatorView (AFNetworking)
- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
if (notificationObserver == nil) {
notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return notificationObserver;
}
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setAnimatingWithStateOfTask:task];
}
@end
@implementation AFActivityIndicatorViewNotificationObserver
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
{
self = [super init];
if (self) {
_activityIndicatorView = activityIndicatorView;
}
return self;
}
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
if (task) {
if (task.state != NSURLSessionTaskStateCompleted) {
UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
if (task.state == NSURLSessionTaskStateRunning) {
[activityIndicatorView startAnimating];
} else {
[activityIndicatorView stopAnimating];
}
[notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
}
}
}
#pragma mark -
- (void)af_startAnimating {
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicatorView startAnimating];
});
}
- (void)af_stopAnimating {
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicatorView stopAnimating];
});
}
#pragma mark -
- (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
}
@end
#endif
// UIImageView+AFNetworking.h
// Copyright (c) 2011–2016 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 AFImageDownloader;
/**
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 (AFNetworking)
///------------------------------------
/// @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:(AFImageDownloader *)imageDownloader;
/**
The shared image downloader used to download images.
*/
+ (AFImageDownloader *)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–2016 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+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFImageDownloader.h"
@interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
@end
@implementation UIImageView (_AFNetworking)
- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
}
- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation UIImageView (AFNetworking)
+ (AFImageDownloader *)sharedImageDownloader {
return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
}
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
objc_setAssociatedObject([UIImageView class], @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.image = placeholderImage;
if (failure) {
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
failure(urlRequest, nil, error);
}
return;
}
if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) {
return;
}
[self cancelImageDownloadTask];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> 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];
AFImageDownloadReceipt *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
// UIKit+AFNetworking.h
//
// Copyright (c) 2011–2016 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>
#ifndef _UIKIT_AFNETWORKING_
#define _UIKIT_AFNETWORKING_
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFAutoPurgingImageCache.h"
#import "AFImageDownloader.h"
#import "UIActivityIndicatorView+AFNetworking.h"
#import "UIButton+AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "UIProgressView+AFNetworking.h"
#endif
#if TARGET_OS_IOS
#import "AFNetworkActivityIndicatorManager.h"
#import "UIRefreshControl+AFNetworking.h"
#import "WKWebView+AFNetworking.h"
#endif
#endif /* _UIKIT_AFNETWORKING_ */
// UIProgressView+AFNetworking.h
// Copyright (c) 2011–2016 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
/**
This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task.
*/
@interface UIProgressView (AFNetworking)
///------------------------------------
/// @name Setting Session Task Progress
///------------------------------------
/**
Binds the progress to the upload progress of the specified session task.
@param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated;
/**
Binds the progress to the download progress of the specified session task.
@param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
#endif
// UIProgressView+AFNetworking.m
// Copyright (c) 2011–2016 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 "UIProgressView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFURLSessionManager.h"
static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
#pragma mark -
@implementation UIProgressView (AFNetworking)
- (BOOL)af_uploadProgressAnimated {
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
}
- (void)af_setUploadProgressAnimated:(BOOL)animated {
objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)af_downloadProgressAnimated {
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
}
- (void)af_setDownloadProgressAnimated:(BOOL)animated {
objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated
{
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
[task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
[self af_setUploadProgressAnimated:animated];
}
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated
{
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[self af_setDownloadProgressAnimated:animated];
}
#pragma mark - NSKeyValueObserving
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(__unused NSDictionary *)change
context:(void *)context
{
if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
if ([object countOfBytesExpectedToSend] > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
});
}
}
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
if ([object countOfBytesExpectedToReceive] > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
});
}
}
if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
@try {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
if (context == AFTaskCountOfBytesSentContext) {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
}
if (context == AFTaskCountOfBytesReceivedContext) {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
}
}
@catch (NSException * __unused exception) {}
}
}
}
}
@end
#endif
// UIRefreshControl+AFNetworking.m
//
// Copyright (c) 2011–2016 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
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task.
*/
@interface UIRefreshControl (AFNetworking)
///-----------------------------------
/// @name Refreshing for Session Tasks
///-----------------------------------
/**
Binds the refreshing state to the state of the specified task.
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
@end
NS_ASSUME_NONNULL_END
#endif
// UIRefreshControl+AFNetworking.m
//
// Copyright (c) 2011–2016 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 "UIRefreshControl+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS
#import "AFURLSessionManager.h"
@interface AFRefreshControlNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
@end
@implementation UIRefreshControl (AFNetworking)
- (AFRefreshControlNotificationObserver *)af_notificationObserver {
AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
if (notificationObserver == nil) {
notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return notificationObserver;
}
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setRefreshingWithStateOfTask:task];
}
@end
@implementation AFRefreshControlNotificationObserver
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
{
self = [super init];
if (self) {
_refreshControl = refreshControl;
}
return self;
}
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
if (task) {
UIRefreshControl *refreshControl = self.refreshControl;
if (task.state == NSURLSessionTaskStateRunning) {
[refreshControl beginRefreshing];
[notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
} else {
[refreshControl endRefreshing];
}
}
}
#pragma mark -
- (void)af_beginRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{
[self.refreshControl beginRefreshing];
});
}
- (void)af_endRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{
[self.refreshControl endRefreshing];
});
}
#pragma mark -
- (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
}
@end
#endif
// WkWebView+AFNetworking.h
// Copyright (c) 2011–2016 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
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@class AFHTTPSessionManager;
@interface WKWebView (AFNetworking)
/**
The session manager used to download all request
*/
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
/**
Asynchronously loads the specified request.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
@param progress A progress object monitoring the current download progress.
@param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
navigation:(WKNavigation * _Nonnull)navigation
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(nullable void (^)(NSError *error))failure;
/**
Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`.
@param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
@param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
@param progress A progress object monitoring the current download progress.
@param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
navigation:(WKNavigation * _Nonnull)navigation
MIMEType:(nullable NSString *)MIMEType
textEncodingName:(nullable NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(nullable void (^)(NSError *error))failure;
@end
NS_ASSUME_NONNULL_END
#endif
// WkWebView+AFNetworking.m
// Copyright (c) 2011–2016 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 "WKWebView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS
#import "AFHTTPSessionManager.h"
#import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h"
@interface WKWebView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
@end
@implementation WKWebView (_AFNetworking)
- (NSURLSessionDataTask *)af_URLSessionTask {
return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
}
- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation WKWebView (AFNetworking)
- (AFHTTPSessionManager *)sessionManager {
static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
_af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
_af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
}
- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
});
return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)loadRequest:(NSURLRequest *)request
navigation:(WKNavigation * _Nonnull)navigation
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(nullable void (^)(NSError *error))failure {
[self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) {
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
if (response.textEncodingName) {
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
}
NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (success) {
string = success(response, string);
}
return [string dataUsingEncoding:stringEncoding];
} failure:failure];
}
- (void)loadRequest:(NSURLRequest *)request
navigation:(WKNavigation * _Nonnull)navigation
MIMEType:(nullable NSString *)MIMEType
textEncodingName:(nullable NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(nullable void (^)(NSError *error))failure {
NSParameterAssert(request);
if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
[self.af_URLSessionTask cancel];
}
self.af_URLSessionTask = nil;
__weak __typeof(self)weakSelf = self;
__block NSURLSessionDataTask *dataTask;
__strong __typeof(weakSelf) strongSelf = weakSelf;
__strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate;
dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
if (failure) {
failure(error);
}
} else {
if (success) {
success((NSHTTPURLResponse *)response, responseObject);
}
[strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
[strongSelfDelegate webView:strongSelf didFinishNavigation:navigation];
}
}
}];
self.af_URLSessionTask = dataTask;
if (progress != nil) {
*progress = [self.sessionManager downloadProgressForTask:dataTask];
}
[self.af_URLSessionTask resume];
if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
[strongSelfDelegate webView:self didStartProvisionalNavigation:navigation];
}
}
@end
#endif
//
// AVDConfig.h
// AliPlayerSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AVDConfig_h
#define AVDConfig_h
#import <Foundation/Foundation.h>
OBJC_EXPORT
@interface AVDConfig : NSObject
/**
@brief 最大超时时间 默认15000毫秒
*/
/****
@brief Maximum timeout time. Default: 15000 milliseconds.
*/
@property (nonatomic, assign) int timeoutMs;
/**
@brief 最大连接超时时间 默认5000毫秒
*/
/****
@brief Maximum connection timeout time. Default: 5000 milliseconds.
*/
@property (nonatomic, assign) int connnectTimoutMs;
/**
@brief 请求referer
*/
/****
@brief Request Referer.
*/
@property (nonatomic, copy) NSString *referer;
/**
@brief user Agent
*/
/****
@brief UserAgent.
*/
@property (nonatomic, copy) NSString *userAgent;
/**
@brief httpProxy代理
*/
/****
@brief HTTP proxy.
*/
@property (nonatomic, copy) NSString *httpProxy;
@end
#endif /* AVDConfig_h */
//
// AliMediaDownloader.h
// AliMediaDownloader
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AliyunPlayer/AliyunPlayer.h>
#import "AVDConfig.h"
@class AVPVidStsSource;
@class AVPVidAuthSource;
OBJC_EXPORT
@interface AliMediaDownloader : NSObject
/**
@brief 删除下载文件
@param saveDir 文件保存路径
@param vid vid
@param format 格式
@param index vid对应的下载索引
*/
/****
@brief Delete a downloaded file.
@param saveDir The path where the file is saved.
@param vid VID.
@param format Format.
@param index The download index corresponds to the VID.
*/
+(int) deleteFile:(NSString *)saveDir vid:(NSString *)vid format:(NSString *)format index:(int)index;
/**
@brief 初始化下载对象
*/
/****
@brief Intialize the download object.
*/
- (instancetype)init;
/**
@brief 销毁下载对象
*/
/****
@brief Delete the download object.
*/
- (void)destroy;
/**
@brief 使用AVPVidStsSource准备播放
@param source vid sts的播放方式
*/
/****
@brief Use AVPVidStsSource to prepare for playback.
@param source vid Play the media through VidSts.
*/
- (void) prepareWithVid:(AVPVidStsSource*)source;
/**
@brief 鉴权过期,更新AVPVidStsSource信息,
@param source vid sts的信息
*/
/****
@brief Update the AVPVidStsSource information when the authentication expires.
@param source vid STS information.
*/
- (void) updateWithVid:(AVPVidStsSource*)source;
/**
@brief 使用AVPVidAuthSource准备播放
@param source vid playAuth的播放方式
*/
/****
@brief Use AVPVidAuthSource to prepare for playback.
@param source vid Play the media through playAuth.
*/
- (void) prepareWithPlayAuth:(AVPVidAuthSource*)source;
/**
@brief 鉴权过期,更新AVPVidAuthSource信息,
@param source vid auth的信息
*/
/****
@brief Update the AVPVidAuthSource information when the authentication expires.
@param source vid Authentication information.
*/
- (void) updateWithPlayAuth:(AVPVidAuthSource*)source;
/**
@brief 设置下载的保存路径
@param dir 保存文件夹
*/
/****
@brief Set a path to save the downloaded file.
@param dir The specified path.
*/
- (void) setSaveDirectory:(NSString*)dir;
/**
@brief 开始下载
*/
/****
@brief Start downloading.
*/
- (void) start;
/**
@brief 停止下载
*/
/****
@brief Pause downloading.
*/
- (void) stop;
/**
@brief 删除下载文件
*/
/****
@brief Delete the downloaded file.
*/
- (void)deleteFile;
/**
@brief 获取下载config
*/
/****
@brief Query download config.
*/
- (AVDConfig*) getConfig;
/**
@brief 设置下载config
*/
/****
@brief Modify download config.
*/
- (void) setConfig:(AVDConfig*)config;
/**
@brief 设置下载的trackIndex
@param trackIndex 从prepare回调中可以获取所有index
*/
/****
@brief Specify the indexes of the tracks to be downloaded.
@param trackIndex Use the prepare callback to retrieve all track indexes.
*/
- (void) selectTrack:(int)trackIndex;
/**
@brief 设置转换播放的url的回调函数,一般用于p2p中的url地址转换
@param callback 回调函数指针
*/
/****
@brief Set a URL conversion callback. URL conversion is typically used in P2P broadcasting.
@param callback The function pointer of the callback.
*/
- (void) setPlayUrlConvertCallback:(PlayURLConverCallback)callback;
/**
@brief 设置代理,参考AMDDelegate
*/
/****
@brief Set a proxy. See AMDDelegate.
*/
@property (nonatomic, weak) id<AMDDelegate> delegate;
/**
@brief 获取SDK版本号信息
*/
/****
@brief Query the SDK version.
*/
+ (NSString*) getSDKVersion;
/**
@brief 获取下载之后的文件路径
*/
/****
@brief Query the path of the downloaded file.
*/
@property (nonatomic, readonly) NSString* downloadedFilePath;
@end
//
// AliyunMediaDownloader.h
// AliyunMediaDownloader
//
// Created by shiping.csp on 2019/2/25.
// Copyright © 2019 shiping.csp. All rights reserved.
//
//#import <Foundation/Foundation.h>
//! Project version number for AliyunMediaDownloader.
//FOUNDATION_EXPORT double AliyunMediaDownloaderVersionNumber;
//! Project version string for AliyunMediaDownloader.
//FOUNDATION_EXPORT const unsigned char AliyunMediaDownloaderVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <AliyunMediaDownloader/PublicHeader.h>
#import <AliyunMediaDownloader/AliMediaDownloader.h>
framework module AliyunMediaDownloader {
umbrella header "AliyunMediaDownloader.h"
export *
module * { export * }
}
//
// AMDDelegate.h
// AliMediaDownloader
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AMDDelegate_h
#define AMDDelegate_h
@class AVPMediaInfo;
@class AVPErrorModel;
@class AliMediaDownloader;
#import <Foundation/Foundation.h>
@protocol AMDDelegate <NSObject>
@optional
/**
@brief 下载准备完成事件回调
@param downloader 下载downloader指针
@param info 下载准备完成回调,@see AVPMediaInfo
*/
/****
@brief Download preparation completion callback.
@param downloader Downloader pointer.
@param info Download preparation completion callback. @see AVPMediaInfo
*/
-(void)onPrepared:(AliMediaDownloader*)downloader mediaInfo:(AVPMediaInfo*)info;
/**
@brief 错误代理回调
@param downloader 下载downloader指针
@param errorModel 播放器错误描述,参考AliVcPlayerErrorModel
*/
/****
@brief Proxy error callback.
@param downloader Downloader pointer.
@param errorModel Player error description. See AliVcPlayerErrorModel
*/
- (void)onError:(AliMediaDownloader*)downloader errorModel:(AVPErrorModel *)errorModel;
/**
@brief 下载进度回调
@param downloader 下载downloader指针
@param percent 下载进度 0-100
*/
/****
@brief Download progress callback.
@param downloader Downloader pointer.
@param percent Download progress: 0 to 100.
*/
- (void)onDownloadingProgress:(AliMediaDownloader*)downloader percentage:(int)percent;
/**
@brief 下载文件的处理进度回调
@param downloader 下载downloader指针
@param percent 下载进度 0-100
*/
/****
@brief Downloaded file processing progress callback.
@param downloader Downloader pointer.
@param percent Processing progress: 0 to 100.
*/
- (void)onProcessingProgress:(AliMediaDownloader*)downloader percentage:(int)percent;
/**
@brief 下载完成回调
@param downloader 下载downloader指针
*/
/****
@brief Download completion callback.
@param downloader Downloader pointer.
*/
- (void)onCompletion:(AliMediaDownloader*)downloader;
@end
#endif /* AMDDelegate_h */
//
// AVPCacheConfig.h
// AliPlayerSDK
//
// Created by huang_jiafa on 2019/05/31.
// Copyright (c) 2019 Aliyun. All rights reserved.
//
#ifndef AVPCacheConfig_h
#define AVPCacheConfig_h
#import <Foundation/Foundation.h>
OBJC_EXPORT
@interface AVPCacheConfig : NSObject
/**
@brief 缓存目录
*/
/****
@brief The cache directory.
*/
@property (nonatomic, copy) NSString *path;
/**
@brief 单个视频缓存的最大时长,单位秒,即某个视频的时长超过maxDuration将不会被缓存
*/
/****
@brief The maximum length of a single video that can be cached. Unit: seconds. Videos that exceed the maximum length are not cached.
*/
@property (nonatomic, assign) long maxDuration;
/**
@brief 所有缓存最大占用空间,单位:MB
*/
/****
@brief The maximum cache memory size. Unit: MB.
*/
@property (nonatomic, assign) int maxSizeMB;
/**
@brief 是否开启缓存。默认关闭。
*/
/****
@brief Enable or disable content caching. Default: disabled.
*/
@property (nonatomic, assign) BOOL enable;
@end
#endif /* AVPCacheConfig_h */
//
// AVPConfig.h
// AliPlayerSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AVPConfig_h
#define AVPConfig_h
#import <Foundation/Foundation.h>
OBJC_EXPORT
@interface AVPConfig : NSObject
/**
@brief 直播最大延迟 默认5000毫秒,单位毫秒
*/
/****
@brief The maximum broadcasting delay. Default: 5000 milliseconds, Unit: millisecond.
*/
@property (nonatomic, assign) int maxDelayTime;
/**
@brief 卡顿后缓存数据的高水位,当播放器缓存数据大于此值时开始播放,单位毫秒
*/
/****
@brief The size of data to be cached before the player can be resumed from playback lag. When the size of the data cached by the player reaches this value, the playback is resumed, Unit: millisecond.
*/
@property (nonatomic, assign) int highBufferDuration;
/**
@brief 开始起播缓存区数据长度,默认500ms,单位毫秒
*/
/****
@brief The size of the cache data required for starting playback. Default: 500 milliseconds, Unit: millisecond.
*/
@property (nonatomic, assign) int startBufferDuration;
/**
@brief 播放器最大的缓存数据长度,默认50秒,单位毫秒
*/
/****
@brief The maximum size of cache data. Default: 50 seconds, Unit: millisecond.
*/
@property (nonatomic, assign) int maxBufferDuration;
/**
@brief 网络超时时间,默认15秒,单位毫秒
*/
/****
@brief Network connection timeout time. Default: 15 seconds, Unit: millisecond.
*/
@property (nonatomic, assign) int networkTimeout;
/**
@brief 网络重试次数,每次间隔networkTimeout,networkRetryCount=0则表示不重试,重试策略app决定,默认值为2
*/
/****
@brief The maximum network reconnection attempts. Default: 2. networkTimeout specifies the reconnection interval. networkRetryCount=0 indicates that automatic network reconnection is disabled. The reconnection policy varies depending on the app.
*/
@property (nonatomic, assign) int networkRetryCount;
/**
@brief probe数据大小,默认-1,表示不设置
*/
/****
@brief The size of the probe data. Default: -1. Value -1 indicates that the probe data size is not specified. */
@property (nonatomic, assign) int maxProbeSize;
/**
@brief 请求referer
*/
/****
@brief Request Referer.
*/
@property (nonatomic, copy) NSString *referer;
/**
@brief user Agent
*/
/****
@brief UserAgent.
*/
@property (nonatomic, copy) NSString *userAgent;
/**
@brief httpProxy代理
*/
/****
@brief HTTP proxy.
*/
@property (nonatomic, copy) NSString *httpProxy;
/**
@brief 调用stop停止后是否显示最后一帧图像,YES代表清除显示,黑屏,默认为NO
*/
/****
@brief Whether to clear the last frame when the player is stopped. Set to YES to clear the last frame and a black view is displayed. Default: NO.
*/
@property (nonatomic, assign) BOOL clearShowWhenStop;
/**
@brief 添加自定义header
*/
/****
@brief Add a custom header.
*/
@property (nonatomic, copy) NSMutableArray *httpHeaders;
/**
@brief 是否启用SEI
*/
/****
@brief Enable or disable SEI.
*/
@property (nonatomic, assign) BOOL enableSEI;
/* set the video format for renderFrame callback
* vtb decoder only, equal to OSType, not be supported by other decoder
* support 420v 420f y420 BGRA
* */
@property (nonatomic, assign) int pixelBufferOutputFormat;
@property(nonatomic, assign) int liveStartIndex;
/**
@brief 禁用Audio.
*/
/****
@brief Disable audio track.
*/
@property (nonatomic, assign) BOOL disableAudio;
/**
@brief 禁用Video
*/
/****
@brief Disable video track.
*/
@property (nonatomic, assign) BOOL disableVideo;
/**
@brief 进度跟新的频率。包括当前位置和缓冲位置。
*/
/****
@brief Set the frequencies of Progress. Includes the current position and the buffer position.
*/
@property(nonatomic, assign) int positionTimerIntervalMs;
/**
@brief 设置播放器后向buffer的最大值.
*/
/****
@brief set the maximum backward buffer duration of the player.
*/
@property(nonatomic, assign) uint64_t mMAXBackwardDuration;
@end
#endif /* AVPConfig_h */
//
// AVPDef.h
// AVPSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AVPDef_h
#define AVPDef_h
#import <Foundation/Foundation.h>
#if TARGET_OS_OSX
#import <AppKit/AppKit.h>
#define AVPView NSView
#define AVPImage NSImage
#elif TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#define AVPView UIView
#define AVPImage UIImage
#endif // TARGET_OS_OSX
#import "AVPErrorCode.h"
/**
* Convert playback URL before playback.
*
* For vid playback, try to convert the playback URL before playback
*
* @param srcURL [in] input URL.
* @param srcFormat [in] input format. should be "m3u8" "mp4", or "" if unknown.
* @param destURL [out] output URL, convertURL function will malloc the memory, and user of PlayURLConverCallback need free it outside.
*
* @return true if success.
*/
typedef bool (*PlayURLConverCallback)(const char* srcURL, const char* srcFormat, char** destURL);
typedef enum AVPStatus: NSUInteger {
/** @brief 空转,闲时,静态 */
/**** @brief Idle */
AVPStatusIdle = 0,
/** @brief 初始化完成 */
/**** @brief Initialized */
AVPStatusInitialzed,
/** @brief 准备完成 */
/**** @brief Prepared */
AVPStatusPrepared,
/** @brief 正在播放 */
/**** @brief Playing */
AVPStatusStarted,
/** @brief 播放暂停 */
/**** @brief Paused */
AVPStatusPaused,
/** @brief 播放停止 */
/**** @brief Stopped */
AVPStatusStopped,
/** @brief 播放完成 */
/**** @brief Completed */
AVPStatusCompletion,
/** @brief 播放错误 */
/**** @brief Error */
AVPStatusError
} AVPStatus;
/**@brief 跳转模式,是否为精准跳转*/
/****@brief Seeking mode: accurate seeking or inaccurate seeking.*/
typedef enum AVPSeekMode: NSUInteger {
AVP_SEEKMODE_ACCURATE = 0x01,
AVP_SEEKMODE_INACCURATE = 0x10,
} AVPSeekMode;
/**@brief 渲染显示模式*/
/****@brief Zoom mode*/
typedef enum AVPScalingMode: NSUInteger {
/**@brief 不保持比例平铺*/
/****@brief Auto stretch to fit.*/
AVP_SCALINGMODE_SCALETOFILL,
/**@brief 保持比例,黑边*/
/****@brief Keep aspect ratio and add black borders.*/
AVP_SCALINGMODE_SCALEASPECTFIT,
/**@brief 保持比例填充,需裁剪*/
/****@brief Keep aspect ratio and crop.*/
AVP_SCALINGMODE_SCALEASPECTFILL,
} AVPScalingMode;
/**@brief 旋转模式*/
/****@brief Rotate mode*/
typedef enum AVPRotateMode: NSUInteger {
AVP_ROTATE_0 = 0,
AVP_ROTATE_90 = 90,
AVP_ROTATE_180 = 180,
AVP_ROTATE_270 = 270
} AVPRotateMode;
/**@brief 镜像模式*/
/****@brief Mirroring mode*/
typedef enum AVPMirrorMode: NSUInteger {
AVP_MIRRORMODE_NONE,
AVP_MIRRORMODE_HORIZONTAL,
AVP_MIRRORMODE_VERTICAL,
} AVPMirrorMode;
/**@brief 播放器事件类型*/
/****@brief Player event type*/
typedef enum AVPEventType: NSUInteger {
/**@brief 准备完成事件*/
/****@brief Preparation completion event*/
AVPEventPrepareDone,
/**@brief 自动启播事件*/
/****@brief Autoplay start event*/
AVPEventAutoPlayStart,
/**@brief 首帧显示事件*/
/****@brief First frame display event*/
AVPEventFirstRenderedStart,
/**@brief 播放完成事件*/
/****@brief Playback completion event*/
AVPEventCompletion,
/**@brief 缓冲开始事件*/
/****@brief Buffer start event*/
AVPEventLoadingStart,
/**@brief 缓冲完成事件*/
/****@brief Buffer completion event*/
AVPEventLoadingEnd,
/**@brief 跳转完成事件*/
/****@brief Seeking completion event*/
AVPEventSeekEnd,
/**@brief 循环播放开始事件*/
/****@brief Loop playback start event*/
AVPEventLoopingStart,
} AVPEventType;
/**@brief 获取信息播放器的key*/
/****@brief The key to get property*/
typedef enum AVPPropertyKey: NSUInteger {
/**@brief Http的response信息
* 返回的字符串是JSON数组,每个对象带response和type字段。type字段可以是url/video/audio/subtitle,根据流是否有相应Track返回。
* 例如:[{"response":"response string","type":"url"},{"response":"","type":"video"}]
*/
/****@brief Http response info
* Return with JSON array,each object item include 'response'/'type' filed。'type' could be url/video/audio/subtitle, depend on the stream whether have the tracks。
* For example: [{"response":"response string","type":"url"},{"response":"","type":"video"}]
*/
AVP_KEY_RESPONSE_INFO = 0,
/**@brief 主URL的连接信息
* 返回的字符串是JSON对象,带url/ip/eagleID/cdnVia/cdncip/cdnsip等字段(如果解析不到则不添加)
* 例如:{"url":"http://xxx","openCost":23,"ip":"11.111.111.11","cdnVia":"xxx","cdncip":"22.222.222.22","cdnsip":"xxx"}
*/
/****@brief Major URL connect information
* Return with JSON object,include sub fileds such as url/ip/eagleID/cdnVia/cdncip/cdnsip.
* For example: {"url":"http://xxx","openCost":23,"ip":"11.111.111.11","cdnVia":"xxx","cdncip":"22.222.222.22","cdnsip":"xxx"}
*/
AVP_KEY_CONNECT_INFO = 1,
} AVPPropertyKey;
/**@brief IP 解析类型*/
/**@brief IP resolve type*/
typedef enum AVPIpResolveType: NSUInteger {
AVPIpResolveWhatEver,
AVPIpResolveV4,
AVPIpResolveV6,
} AVPIpResolveType;
typedef enum AVPOption: NSUInteger {
/**
* @brief 渲染的fps。类型为Float
*/
/****
* @brief render fps. Return value type is Float
*/
AVP_OPTION_RENDER_FPS = 0,
} AVPOption;
/**
@brief AVPErrorModel为播放错误信息描述
*/
/****
@brief AVPErrorModel represents playback error descriptions.
*/
OBJC_EXPORT
@interface AVPErrorModel : NSObject
/**
@brief code为播放错误信息code
*/
/****
@brief code represents a playback error code.
*/
@property (nonatomic, assign) AVPErrorCode code;
/**
@brief message为播放错误信息描述
*/
/****
@brief message represents a playback error message.
*/
@property (nonatomic, copy) NSString *message;
/**
@brief requestId为播放错误信息requestID
*/
/****
@brief requestId represents the request ID of a playback error.
*/
@property (nonatomic, copy) NSString *requestId;
/**
@brief videoId为播放错误发生的videoID
*/
/****
@brief videoId represents the VID of the video that has a playback error.
*/
@property (nonatomic, copy) NSString *videoId;
@end
/**
@brief AVPTimeShiftModel直播时移描述
*/
/****
@brief AVPTimeShiftModel represents broadcasting timeshift descriptions.
*/
OBJC_EXPORT
@interface AVPTimeShiftModel : NSObject
/**
@brief startTime直播时移开始时间
*/
/****
@brief startTime represents the start of the time range for broadcasting timeshift.
*/
@property (nonatomic, assign) NSTimeInterval startTime;
/**
@brief endTime直播时移结束时间
*/
/****
@brief endTime represents the end of the time range for broadcasting timeshift.
*/
@property (nonatomic, assign) NSTimeInterval endTime;
/**
@brief currentTime直播时移当前时间
*/
/****
@brief currentTime represents the time that broadcasting timeshift seeks to.
*/
@property (nonatomic, assign) NSTimeInterval currentTime;
@end
/**
@brief logLevel
*/
typedef enum AVPLogLevel: NSUInteger {
LOG_LEVEL_NONE = 0,
LOG_LEVEL_FATAL = 8,
LOG_LEVEL_ERROR = 16,
LOG_LEVEL_WARNING = 24,
LOG_LEVEL_INFO = 32,
LOG_LEVEL_DEBUG = 48,
LOG_LEVEL_TRACE = 56,
} AVPLogLevel;
typedef enum _AVPStsStatus {
Valid,
Invalid,
Pending
} AVPStsStatus;
typedef struct _AVPStsInfo {
NSString* accId;
NSString* accSecret;
NSString* token;
NSString* region;
NSString* formats;
} AVPStsInfo;
#endif /* AVPDef_h */
//
// AVPDelegate.h
// AliPlayerSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AVPDelegate_h
#define AVPDelegate_h
@class AliPlayer;
@class AVPTrackInfo;
#import <Foundation/Foundation.h>
#import "AVPDef.h"
@protocol AVPDelegate <NSObject>
@optional
/**
@brief 播放器事件回调
@param player 播放器player指针
@param eventType 播放器事件类型
@see AVPEventType
*/
/****
@brief Player event callback.
@param player Player pointer.
@param eventType Player event type.
@see AVPEventType
*/
-(void)onPlayerEvent:(AliPlayer*)player eventType:(AVPEventType)eventType;
/**
@brief 播放器事件回调
@param player 播放器player指针
@param eventWithString 播放器事件类型
@param description 播放器事件说明
@see AVPEventType
*/
/****
@brief Player event callback.
@param player Player pointer.
@param eventWithString Player event type.
@param description Player event description.
@see AVPEventType
*/
-(void)onPlayerEvent:(AliPlayer*)player eventWithString:(AVPEventWithString)eventWithString description:(NSString *)description;
/**
@brief 错误代理回调
@param player 播放器player指针
@param errorModel 播放器错误描述,参考AVPErrorModel
@see AVPErrorModel
*/
/****
@brief Proxy error callback.
@param player Player pointer.
@param errorModel Player error description. See AVPErrorModel.
@see AVPErrorModel
*/
- (void)onError:(AliPlayer*)player errorModel:(AVPErrorModel *)errorModel;
/**
@brief 视频大小变化回调
@param player 播放器player指针
@param width 视频宽度
@param height 视频高度
@param rotation 视频旋转角度
*/
/****
@brief Video size change callback.
@param player Player pointer.
@param width Video width.
@param height Video height.
@param rotation Video rotate angle.
*/
- (void)onVideoSizeChanged:(AliPlayer*)player width:(int)width height:(int)height rotation:(int)rotation;
/**
@brief 视频当前播放位置回调
@param player 播放器player指针
@param position 视频当前播放位置
*/
/****
@brief Current playback position callback.
@param player Player pointer.
@param position Current playback position.
*/
- (void)onCurrentPositionUpdate:(AliPlayer*)player position:(int64_t)position;
/**
@brief 视频当前播放内容对应的utc时间回调
@param player 播放器player指针
@param time utc时间
*/
/****
@brief Current playback utc time callback.
@param player Player pointer.
@param position Current utc time.
*/
- (void)onCurrentUtcTimeUpdate:(AliPlayer *)player time:(int64_t)time;
/**
@brief 视频缓存位置回调
@param player 播放器player指针
@param position 视频当前缓存位置
*/
/****
@brief Current cache position callback.
@param player Player pointer.
@param position Current cache position.
*/
- (void)onBufferedPositionUpdate:(AliPlayer*)player position:(int64_t)position;
/**
@brief 视频缓冲进度回调
@param player 播放器player指针
@param progress 缓存进度0-100
*/
/****
@brief Buffer progress callback.
@param player Player pointer.
@param progress Buffer progress: from 0 to 100.
*/
- (void)onLoadingProgress:(AliPlayer*)player progress:(float)progress;
/**
@brief 当前下载速度回调
@param player 播放器player指针
@param speed bits per second
*/
/****
@brief current download speed callback.
@param player Player pointer.
@param speed bits per second.
*/
- (void)onCurrentDownloadSpeed:(AliPlayer *)player speed:(int64_t)speed;
/**
@brief 获取track信息回调
@param player 播放器player指针
@param info track流信息数组
@see AVPTrackInfo
*/
/****
@brief Track information callback.
@param player Player pointer.
@param info An array of track information.
@see AVPTrackInfo
*/
- (void)onTrackReady:(AliPlayer*)player info:(NSArray<AVPTrackInfo*>*)info;
/**
@brief 选择希望播放的流
@param player 播放器player指针
@param info track流信息数组
@see AVPTrackInfo
*/
- (int)onChooseTrackIndex:(AliPlayer *)player info:(NSArray<AVPTrackInfo *> *)info;
/**
@brief track切换完成回调
@param player 播放器player指针
@param info 切换后的信息 参考AVPTrackInfo
@see AVPTrackInfo
*/
/****
@brief Track switchover completion callback.
@param player Player pointer.
@param info Track switchover completion information. See AVPTrackInfo.
@see AVPTrackInfo
*/
- (void)onTrackChanged:(AliPlayer*)player info:(AVPTrackInfo*)info;
/**
@brief 外挂字幕被添加
@param player 播放器player指针
@param index 字幕显示的索引号
@param URL 字幕url
*/
/****
@brief External subtitles have been added
@param player Player pointer.
@param trackIndex Subtitle index.
@param URL subtitle url
*/
- (void)onSubtitleExtAdded:(AliPlayer*)player trackIndex:(int)trackIndex URL:(NSString *)URL;
/**
@brief 字幕显示回调
@param player 播放器player指针
@param trackIndex 字幕流索引.
@param subtitleID 字幕ID.
@param subtitle 字幕显示的字符串
*/
/****
@brief Show subtitle callback.
@param player Player pointer.
@param trackIndex Subtitle stream index.
@param subtitleID Subtitle ID.
@param subtitle Subtitle string.
*/
- (void)onSubtitleShow:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID subtitle:(NSString *)subtitle;
/**
@brief 字幕隐藏回调
@param player 播放器player指针
@param trackIndex 字幕流索引.
@param subtitleID 字幕ID.
*/
/****
@brief Hide subtitle callback.
@param player Player pointer.
@param trackIndex Subtitle stream index.
@param subtitleID Subtitle ID.
*/
- (void)onSubtitleHide:(AliPlayer*)player trackIndex:(int)trackIndex subtitleID:(long)subtitleID;
/**
@brief 获取缩略图成功回调
@param positionMs 指定的缩略图位置
@param fromPos 此缩略图的开始位置
@param toPos 此缩略图的结束位置
@param image 缩图略图像指针,对于mac是NSImage,iOS平台是UIImage指针
*/
/****
@brief Thumbnail image retrieval success callback.
@param positionMs The specified thumbnail image position.
@param fromPos The initial position of the thumbnail image.
@param toPos The end position of the thumbnail image.
@param image Thumbnail image pointer. Mac: NSImage. iOS: UIImage.
*/
- (void)onGetThumbnailSuc:(int64_t)positionMs fromPos:(int64_t)fromPos toPos:(int64_t)toPos image:(id)image;
/**
@brief 获取缩略图失败回调
@param positionMs 指定的缩略图位置
*/
/****
@brief Thumbnail image retrieval failure callback.
@param positionMs The specified thumbnail image position.
*/
- (void)onGetThumbnailFailed:(int64_t)positionMs;
/**
@brief 播放器状态改变回调
@param player 播放器player指针
@param oldStatus 老的播放器状态 参考AVPStatus
@param newStatus 新的播放器状态 参考AVPStatus
@see AVPStatus
*/
/****
@brief Player status update callback.
@param player Player pointer.
@param oldStatus The previous status. See AVPStatus.
@param newStatus The updated status. See AVPStatus.
@see AVPStatus
*/
- (void)onPlayerStatusChanged:(AliPlayer*)player oldStatus:(AVPStatus)oldStatus newStatus:(AVPStatus)newStatus;
/**
@brief 获取截图回调
@param player 播放器player指针
@param image 图像
@see AVPImage
*/
/****
@brief Snapshot retrieval callback.
@param player Player pointer.
@param image Snapshot.
@see AVPImage
*/
- (void)onCaptureScreen:(AliPlayer*)player image:(AVPImage*)image;
/**
@brief SEI回调
@param player 播放器player指针
@param type 类型
@param data 数据
@see AVPImage
*/
/****
@brief SEI callback.
@param player Player pointer.
@param type Type.
@param data Data.
@see AVPImage
*/
- (void)onSEIData:(AliPlayer*)player type:(int)type data:(NSData *)data;
/**
@brief 播放器渲染信息回调
@param player 播放器player指针
@param timeMs 渲染时的系统时间
@param pts 视频帧pts
*/
/****
@brief Player render info callback.
@param player Player pointer.
@param timeMs system time when render.
@param pts video frame pts
@see AVPEventType
*/
-(void)onVideoRendered:(AliPlayer*)player timeMs:(int64_t)timeMs pts:(int64_t)pts;
@end
@protocol AVPEventReportParamsDelegate <NSObject>
-(void)onEventReportParams:(NSDictionary<NSString *, NSString *>*)params;
@end
#endif /* AVPDelegate_h */
//
// AVPHlsKeyGenerator.h
// AliPlayerSDK
//
//
#import <Foundation/Foundation.h>
@protocol AVPLiveKeyInfoDelegate <NSObject>
@required
/*
功能:异步,获取到m3u8中的URI,解析出key,将key相关信息回调出去,如果有两个key,则会回调两次
ekeyGenURL: 密文key的url
ekeyPreGenTime:在多少时间内必须要生成key,这个时间可以用于打散,如果time=0,表示打散时间为0,这个key必须要优先立即生成
*/
/***
Feature: Asynchronous key generation. Retrieve the URI from m3u8, parse the URI, generate a key, and then return the key information. If two keys are generated, two callbacks are required.
ekeyGenURL: The URL of the ciphertext key.
ekeyPreGenTime: The maximum key generation time. You can divide the time into multiple periods. If time=0, then the key must be generated immediately.
*/
-(void) onLiveKeyInfo:(NSString*)ekeyGenURL ekeyPreGenTime:(int)time;
/*
功能:同步,通过密文key来获取到明文key
ekeyGenURL: 密文key的url
*/
/***
Feature: Synchronous key generation. Use a ciphertext key to generate a plaintext key.
ekeyGenURL: The URL of the ciphertext key.
*/
-(NSData*) onGetLiveKey:(NSString*)ekeyGenURL;
@end
OBJC_EXPORT
@interface AVPLiveKeyGenerator : NSObject
+ (AVPLiveKeyGenerator *) getInstance;
@property(nonatomic,weak) id<AVPLiveKeyInfoDelegate> delegate;
@end
//
// AVPLiveTimeShift.h
// AliPlayerSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AliPlayer.h"
OBJC_EXPORT
@interface AVPLiveTimeShift : AliPlayer
/**
@brief 直播时移,打开直播时移播放地址
@param liveTimeUrl 直播时移播放地址
*/
/****
@brief Send a request to the broadcasting timeshift URL.
@param liveTimeUrl Broadcasting timeshift URL.
*/
- (void)prepareWithLiveTimeUrl:(NSString*)liveTimeUrl;
/**
@brief 直播时移,设置直播时移地址
@param liveTimeShiftUrl 直播时移请求地址
*/
/****
@brief Set a broadcasting timeshift URL.
@param liveTimeShiftUrl Broadcasting timeshift URL.
*/
- (void)setLiveTimeShiftUrl:(NSString*)liveTimeShiftUrl;
/**
@brief 直播时移,跳转到指定时移位置
@param startTime 跳转到直播startTime位置
*/
/****
@brief Seek to a specified position.
@param startTime Seek to the position specified by startTime in broadcasting.
*/
- (void)seekToLiveTime:(NSTimeInterval)startTime;
/**
@brief 直播时移,获取直播时间
*/
/****
@brief Query the broadcasting time.
*/
@property (nonatomic, assign) NSTimeInterval liveTime;
/**
@brief 直播时移,获取当前播放时间
*/
/****
@brief Query the current playback time.
*/
@property (nonatomic, assign) NSTimeInterval currentPlayTime;
/**
@brief 直播时移,每60秒更新用户时移时间,参考AliyunPlayerVideoTimeShiftModel
*/
/****
@brief Update the user timeshifting time at an interval of 60 seconds. See AliyunPlayerVideoTimeShiftModel.
*/
@property (nonatomic, strong) AVPTimeShiftModel *timeShiftModel;
/**
@brief 停止播放
*/
/****
@brief Stop the player.
*/
-(void)stop;
/**
@brief 开始播放
*/
/****
@brief Start the player.
*/
-(void)start;
@end
//
// AVPMediaInfo.h
// AliPlayerSDK
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#ifndef AVPMediaInfo_h
#define AVPMediaInfo_h
#import <Foundation/Foundation.h>
const static int SELECT_AVPTRACK_TYPE_VIDEO_AUTO = -1;
/**
@brief track type
* AVPTRACK_TYPE_VIDEO: video track
* AVPTRACK_TYPE_AUDIO: audio track
* AVPTRACK_TYPE_SUBTITLE: subtitle track
* AVPTRACK_TYPE_MIXED: have auido and video info in this track
*/
typedef enum AVPTrackType: NSUInteger {
AVPTRACK_TYPE_VIDEO,
AVPTRACK_TYPE_AUDIO,
AVPTRACK_TYPE_SUBTITLE,
AVPTRACK_TYPE_SAAS_VOD,//track from vod
} AVPTrackType;
OBJC_EXPORT
@interface AVPTrackInfo : NSObject
/**
@brief track type @see AVPTrackType
*/
@property (nonatomic, assign) AVPTrackType trackType;
/**
@brief vod format
*/
@property (nonatomic, copy) NSString* vodFormat;
/**
@brief track index
*/
@property (nonatomic, assign) int trackIndex;
/**
@brief track definition, only meaningful if the trackType is AVPTRACK_TYPE_SAAS_VOD
*/
@property (nonatomic, copy) NSString* trackDefinition;
/**
@brief vod file size, only meaningful if the trackType is AVPTRACK_TYPE_SAAS_VOD
*/
@property (nonatomic, assign) int64_t vodFileSize;
/**
@brief vod play URL, only meaningful if the trackType is AVPTRACK_TYPE_SAAS_VOD
*/
@property (nonatomic, copy) NSString* vodPlayUrl;
/**
@brief waterMark URL, only meaningful if the trackType is AVPTRACK_TYPE_SAAS_VOD
*/
@property (nonatomic, copy) NSString* waterMarkUrl;
/**
@brief video width, only meaningful if the trackType is AVPTRACK_TYPE_VIDEO
*/
@property (nonatomic, assign) int videoWidth;
/**
@brief video height, only meaningful if the trackType is AVPTRACK_TYPE_VIDEO
*/
@property (nonatomic, assign) int videoHeight;
/**
@brief bitrate, only meaningful if the trackType is AVPTRACK_TYPE_VIDEO
*/
@property (nonatomic, assign) int trackBitrate;
/**
@brief the number of audio channel, only meaningful if the trackType is AVPTRACK_TYPE_AUDIO
*/
@property (nonatomic, assign) int audioChannels;
/**
@brief audio samplerate, only meaningful if the trackType is AVPTRACK_TYPE_AUDIO
*/
@property (nonatomic, assign) int audioSamplerate;
/**
@brief audio sampleFormat, only meaningful if the trackType is AVPTRACK_TYPE_AUDIO
*/
@property (nonatomic, assign) int audioSampleFormat;
/**
@brief audio Language, only meaningful if the trackType is AVPTRACK_TYPE_AUDIO
*/
@property (nonatomic, copy) NSString* audioLanguage;
/**
@brief subtitle Language, only meaningful if the trackType is AVPTRACK_TYPE_SUBTITLE
*/
@property (nonatomic, copy) NSString* subtitleLanguage;
@end
OBJC_EXPORT
@interface AVPThumbnailInfo : NSObject
/**
@brief thumbnail URL
*/
@property (nonatomic, copy) NSString* URL;
@end
OBJC_EXPORT
@interface AVPMediaInfo : NSObject
/**
@brief media title
*/
@property (nonatomic, copy) NSString* title;
/**
@brief media cover url
*/
@property (nonatomic, copy) NSString* coverURL;
/**
@brief media type
* video audio video|audio
*/
@property (nonatomic, copy) NSString* mediaType;
/**
@brief media status
*/
@property (nonatomic, copy) NSString* status;
/**
@brief media duration
* 单位: 毫秒
*/
/****
@brief media duration
* Unit: millisecond.
*/
@property (nonatomic, assign) int64_t duration;
/**
@brief 文件码率(vod 和多码率时值为0,应该使用AVPTrackInfo中的trackBitrate)
*/
/****
@brief Retrievable bit rate (VOD and multi-bit rate values are 0; Should use trackBitrate in AVPTrackInfo)
*/
@property(nonatomic, assign) int64_t totalBitrate;
/**
@brief media transcodeMode
*转码类型,取值:FastTranscode(上传完成即转码,且转码完成才能播放),NoTranscode(上传完成不转码,且立即能播放),默认取值FastTranscode
*/
/****
@brief media transcodeMode
*Transcoding type. Valid values: FastTranscode and NoTranscode. FastTranscode: Transcode the content immediately after it is uploaded. Only transcoded content can be played. NoTranscode: Do not transcode the content after it is uploaded. Content can be played without transcoding. Default: FastTranscode.
*/
@property (nonatomic, copy) NSString* transcodeMode;
/**
@brief thumbnails in media info
*/
@property (nonatomic, strong) NSArray<AVPThumbnailInfo*>* thumbnails;
/**
@brief tracks in media info
*/
@property (nonatomic, strong) NSArray<AVPTrackInfo*>* tracks;
@end
#endif /* AVPMediaInfo_h */
//
// AliListPlayer.h
// AliListPlayer
//
// Created by shiping.csp on 2018/11/16.
// Copyright © 2018 com.alibaba.AliyunPlayer. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AliPlayer.h"
OBJC_EXPORT
@interface AliListPlayer : AliPlayer
/**
@brief 初始化播放列表
*/
/****
@brief Initialize the playlist.
*/
- (instancetype)init;
/**
@brief 初始化播放器
@param traceID 用于跟踪debug信息
*/
/****
@brief Initialize the player.
@param traceID The trace ID for debugging.
*/
- (instancetype)init:(NSString*)traceID;
/**
@brief 添加资源到播放列表中
@param vid vid的播放方式
@param uid 该资源的uid,代表在列表中的唯一标识
*/
/****
@brief Add a resource to the playlist.
@param vid Specify a resource by VID.
@param uid The UID of the resource, which uniquely identifies a resource.
*/
- (void) addVidSource:(NSString*)vid uid:(NSString*)uid;
/**
@brief 添加资源到播放列表中
@param url url的播放方式
@param uid 该资源的uid,代表在列表中的唯一标识
*/
/****
@brief Add a resource to the playlist.
@param url Specify a resource by URL.
@param uid The UID of the resource, which uniquely identifies a resource.
*/
- (void) addUrlSource:(NSString*)url uid:(NSString*)uid;
/**
@brief 从播放列表中删除指定资源
@param uid 该资源的uid,代表在列表中的唯一标识
*/
/****
@brief Remove a resource from the playlist.
@param uid The UID of the resource, which uniquely identifies a resource.
*/
- (void) removeSource:(NSString*)uid;
/**
@brief 清除播放列表
*/
/****
@brief Clear the playlist.
*/
- (void) clear;
/**
@brief 获取当前播放资源的uid
*/
/****
@brief Query the UID of the resource that is being played.
*/
- (NSString*) currentUid;
/**
@brief 当前位置移动到下一个进行准备播放,url播放方式
*/
/****
@brief Seek to the next resource and prepare for playback. Only playback by URL is supported.
*/
- (BOOL) moveToNext;
/**
@brief 当前位置移动到上一个进行准备播放,url播放方式
*/
/****
@brief Seek to the previous resource and prepare for playback. Only playback by URL is supported.
*/
- (BOOL) moveToPre;
/**
@brief 移动到指定位置开始准备播放,url播放方式
@param uid 指定资源的uid,代表在列表中的唯一标识
*/
/****
@brief Seek to the specified position and prepare for playback. Only playback by URL is supported.
@param uid The UID of the specified resource, which uniquely identifies a resource.
*/
- (BOOL) moveTo:(NSString*)uid;
/**
@brief 当前位置移动到下一个进行准备播放,sts播放方式,需要更新sts信息
@param accId vid sts播放方式的accessKeyID
@param accKey vid sts播放方式的accessKeySecret
@param token vid sts播放方式的securtiToken
@param region vid sts播放方式的region 默认cn-shanghai
*/
/****
@brief Seek to the next resource and prepare for playback. Only playback by STS is supported. You must update the STS information.
@param accId vid The AccessKey ID.
@param accKey vid The AccessKey Secret.
@param token vid The STS token.
@param region vid The specified region. Default: cn-shanghai.
*/
- (BOOL) moveToNext:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
/**
@brief 当前位置移动到上一个进行准备播放,sts播放方式,需要更新sts信息
@param accId vid sts播放方式的accessKeyID
@param accKey vid sts播放方式的accessKeySecret
@param token vid sts播放方式的securtiToken
@param region vid sts播放方式的region 默认cn-shanghai
*/
/****
@brief Seek to the previous resource and prepare for playback. Only playback by STS is supported. You must update the STS information.
@param accId vid The AccessKey ID.
@param accKey vid The AccessKey Secret.
@param token vid The STS token.
@param region vid The specified region. Default: cn-shanghai.
*/
- (BOOL) moveToPre:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
/**
@brief 移动到指定位置开始准备播放,sts播放方式,需要更新sts信息
@param uid 指定资源的uid,代表在列表中的唯一标识
@param accId vid sts播放方式的accessKeyID
@param accKey vid sts播放方式的accessKeySecret
@param token vid sts播放方式的securtiToken
@param region vid sts播放方式的region 默认cn-shanghai
*/
/****
@brief Seek to the specified resource and prepare for playback. Only playback by STS is supported. You must update the STS information.
@param uid The UID of the specified resource, which uniquely identifies a resource.
@param accId vid The AccessKey ID.
@param accKey vid The AccessKey Secret.
@param token vid The STS token.
@param region vid The specified region. Default: cn-shanghai.
*/
- (BOOL) moveTo:(NSString*)uid accId:(NSString*)accId accKey:(NSString*)accKey token:(NSString*)token region:(NSString*)region;
/**
@brief 设置最大的预缓存的内存大小,默认100M,最小20M
*/
/****
@brief Set the maximum preloading cache size. Default: 100 MB. Minimum: 20 MB.
*/
@property (nonatomic, assign) int maxPreloadMemorySizeMB;
/**
@brief 获取/设置预加载的个数,当前位置的前preloadCount和后preloadCount,默认preloadCount = 2
*/
/****
@brief Query or set the number of preloaded resources. The number of resources before preloading and the number of resources after preloading are returned. Default: 2.
*/
@property (nonatomic, assign) int preloadCount;
/**
@brief 获取/设置列表播放的sts播放方式,指定默认的清晰度,如"LD、HD"等,moveTo之前调用,一旦预加载后不能更改
*/
/****
@brief Query or set the definition for playback by STS, such as LD or HD. Call this method before moveTo. After the resources are preloaded, you cannot change the definition.
*/
@property (nonatomic, copy) NSString* stsPreloadDefinition;
@end
This source diff could not be displayed because it is too large. You can view the blob instead.
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