From e6dd076b42e2c358200d40e0616990514ca06f92 Mon Sep 17 00:00:00 2001 From: Marco Schmickler Date: Sun, 2 Apr 2017 15:34:21 +0200 Subject: [PATCH] ios 10.3 --- .idea/kplayer.iml | 412 +----------------- Podfile | 41 +- kplayer.xcodeproj/project.pbxproj | 75 ++-- kplayer/AppDelegate.swift | 34 +- kplayer/Base.lproj/Main.storyboard | 38 +- .../AppIcon.appiconset/Contents.json | 25 ++ kplayer/core/ItemModel.swift | 2 +- kplayer/core/MediaItem.swift | 38 +- kplayer/core/NetworkManager.swift | 113 +++-- kplayer/detail/DetailViewController.swift | 102 ++--- kplayer/detail/HeaderCell.swift | 4 +- kplayer/detail/ItemCell.swift | 8 +- kplayer/detail/VideoPlayerController.swift | 92 ++-- kplayer/master/MasterViewController.swift | 50 +-- kplayer/photo/MediaPhotoController.swift | 182 ++++---- kplayer/util/DataLoadOperation.swift | 22 +- kplayer/util/HanekeFetchOperation.swift | 10 +- kplayer/util/ImageLoadOperation.swift | 28 +- kplayer/util/LayoutTools.swift | 22 +- kplayer/util/NetData.swift | 4 +- kplayer/util/NetworkHelper.swift | 94 ++-- kplayer/util/UIImageExtension.swift | 14 +- kplayer/util/UploadOperation.swift | 49 ++- kplayer/util/ViewControllerExtensions.swift | 12 +- kplayer/util/stringutil.swift | 34 +- kplayerTests/kplayerTests.swift | 2 +- 26 files changed, 593 insertions(+), 914 deletions(-) diff --git a/.idea/kplayer.iml b/.idea/kplayer.iml index 8f4724a..74121dc 100644 --- a/.idea/kplayer.iml +++ b/.idea/kplayer.iml @@ -1,412 +1,2 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + \ No newline at end of file diff --git a/Podfile b/Podfile index a5977ba..5ee1339 100644 --- a/Podfile +++ b/Podfile @@ -1,19 +1,30 @@ -platform :ios, '8.3' +platform :ios, '10.2' source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -# pod 'Player' -#pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :branch => 'swift-2.0' -#pod 'Alamofire', '~> 1.2' -pod 'Alamofire', '~> 2.0' -pod 'ALMoviePlayerController', '~>0.3.0' -#pod 'DZVideoPlayerViewController' -#pod 'SwiftyJSON' -pod 'HanekeSwift' -pod 'Nimbus/Photos' -pod 'Nimbus/PagingScrollView' -#pod 'AFNetworking', '~>2.1' -pod 'Dollar' -pod 'Cent' -#, '1.2.0' +target 'kplayer' do + # pod 'Player' + #pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :branch => 'swift-2.0' + #pod 'Alamofire', '~> 1.2' + pod 'Alamofire', '~> 4.2' + pod 'ALMoviePlayerController', '~>0.3.0' + #pod 'DZVideoPlayerViewController' + #pod 'SwiftyJSON' + #pod 'HanekeSwift' + pod 'HanekeSwift', :git => 'https://github.com/jasonnoahchoi/HanekeSwift', :branch => 'swift3' + pod 'Nimbus/Photos' + pod 'Nimbus/PagingScrollView' + #pod 'AFNetworking', '~>2.1' + #pod 'Dollar', '6.1.0' + #pod 'Cent', '6.0.3' + #, '1.2.0' + post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + config.build_settings['SWIFT_VERSION'] = '3.0' + end + end + end +end + diff --git a/kplayer.xcodeproj/project.pbxproj b/kplayer.xcodeproj/project.pbxproj index 731a24d..41d5908 100644 --- a/kplayer.xcodeproj/project.pbxproj +++ b/kplayer.xcodeproj/project.pbxproj @@ -29,7 +29,7 @@ 1C736D24B49451141CD4B64D /* DetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C7369F53095B7A4D65679C2 /* DetailViewController.swift */; }; 1C736F6A223D4ADB2E1BA733 /* ItemCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C736069C214E9522BB1BD97 /* ItemCell.swift */; }; 1C736FB92B19FE17E4357C85 /* MediaItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C73688DAB88F9360FB62A49 /* MediaItem.swift */; }; - A5D637AE4588AAB5DC1CBC6B /* Pods.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 127AC1F28342F9AAE3CEC5C2 /* Pods.framework */; }; + AA74B07A01F0E99E6DEC7D1B /* Pods_kplayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B75159FFCD5A882E6F167FE /* Pods_kplayer.framework */; }; C98AF5D51B124D6A00D196CC /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C98AF5D41B124D6A00D196CC /* AppDelegate.swift */; }; C98AF5D81B124D6A00D196CC /* kplayer.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = C98AF5D61B124D6A00D196CC /* kplayer.xcdatamodeld */; }; C98AF5DF1B124D6A00D196CC /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = C98AF5DD1B124D6A00D196CC /* Main.storyboard */; }; @@ -49,7 +49,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 127AC1F28342F9AAE3CEC5C2 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 1C736059262A57AADE6AB761 /* Kirschkeks-256x256.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Kirschkeks-256x256.png"; path = "kplayer/Kirschkeks-256x256.png"; sourceTree = ""; }; 1C736069C214E9522BB1BD97 /* ItemCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ItemCell.swift; sourceTree = ""; }; 1C7360744ABACC3557D05760 /* HanekeFetchOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HanekeFetchOperation.swift; sourceTree = ""; }; @@ -72,8 +71,8 @@ 1C736DCCE3AA9993E15F7652 /* UIImageExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UIImageExtension.swift; sourceTree = ""; }; 1C736E3BE8EC464D6F5DC8FA /* scratch.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = scratch.txt; sourceTree = ""; }; 1C736F9338CE36708244D42A /* DataLoadOperation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataLoadOperation.swift; sourceTree = ""; }; - 5C6CBA548F885BF342F594EA /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; - A170BFB886D61D57F7009BFC /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + 6D522F61736592330F481B4F /* Pods-kplayer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-kplayer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-kplayer/Pods-kplayer.debug.xcconfig"; sourceTree = ""; }; + 8B75159FFCD5A882E6F167FE /* Pods_kplayer.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_kplayer.framework; sourceTree = BUILT_PRODUCTS_DIR; }; C98AF5CF1B124D6A00D196CC /* kplayer.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = kplayer.app; sourceTree = BUILT_PRODUCTS_DIR; }; C98AF5D31B124D6A00D196CC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C98AF5D41B124D6A00D196CC /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -84,6 +83,7 @@ C98AF5E91B124D6A00D196CC /* kplayerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = kplayerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; C98AF5EE1B124D6A00D196CC /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; C98AF5EF1B124D6A00D196CC /* kplayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = kplayerTests.swift; sourceTree = ""; }; + DF1DF76780D9CDC55209D1CE /* Pods-kplayer.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-kplayer.release.xcconfig"; path = "Pods/Target Support Files/Pods-kplayer/Pods-kplayer.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -91,8 +91,8 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - A5D637AE4588AAB5DC1CBC6B /* Pods.framework in Frameworks */, 1C73635138BBD2BB480A308F /* MediaPlayer.framework in Frameworks */, + AA74B07A01F0E99E6DEC7D1B /* Pods_kplayer.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -160,22 +160,22 @@ path = core; sourceTree = ""; }; - 8CB608B13A2BDFA9D708982B /* Frameworks */ = { + 8052F5B3AAC2535E5C08A529 /* Pods */ = { isa = PBXGroup; children = ( - 127AC1F28342F9AAE3CEC5C2 /* Pods.framework */, - 1C736777456388CA571DA17B /* MediaPlayer.framework */, + 6D522F61736592330F481B4F /* Pods-kplayer.debug.xcconfig */, + DF1DF76780D9CDC55209D1CE /* Pods-kplayer.release.xcconfig */, ); - name = Frameworks; + name = Pods; sourceTree = ""; }; - 8EB26707CC8BD3E10F328A9E /* Pods */ = { + 8CB608B13A2BDFA9D708982B /* Frameworks */ = { isa = PBXGroup; children = ( - 5C6CBA548F885BF342F594EA /* Pods.debug.xcconfig */, - A170BFB886D61D57F7009BFC /* Pods.release.xcconfig */, + 1C736777456388CA571DA17B /* MediaPlayer.framework */, + 8B75159FFCD5A882E6F167FE /* Pods_kplayer.framework */, ); - name = Pods; + name = Frameworks; sourceTree = ""; }; C98AF5C61B124D6A00D196CC = { @@ -184,9 +184,9 @@ C98AF5D11B124D6A00D196CC /* kplayer */, C98AF5EC1B124D6A00D196CC /* kplayerTests */, C98AF5D01B124D6A00D196CC /* Products */, - 8EB26707CC8BD3E10F328A9E /* Pods */, 8CB608B13A2BDFA9D708982B /* Frameworks */, 1C736059262A57AADE6AB761 /* Kirschkeks-256x256.png */, + 8052F5B3AAC2535E5C08A529 /* Pods */, ); sourceTree = ""; }; @@ -250,12 +250,12 @@ isa = PBXNativeTarget; buildConfigurationList = C98AF5F31B124D6A00D196CC /* Build configuration list for PBXNativeTarget "kplayer" */; buildPhases = ( - FA5E42A873B9445C28CCC025 /* Check Pods Manifest.lock */, + 5BE7FB291B76EEE317F0B068 /* [CP] Check Pods Manifest.lock */, C98AF5CB1B124D6A00D196CC /* Sources */, C98AF5CC1B124D6A00D196CC /* Frameworks */, C98AF5CD1B124D6A00D196CC /* Resources */, - 81E453B289EA9615E1980098 /* Embed Pods Frameworks */, - F554AE493C60519505E761A6 /* Copy Pods Resources */, + 34FE5806529FEB6C56D30822 /* [CP] Embed Pods Frameworks */, + 9901417B0A169BA87853DAAE /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -292,15 +292,17 @@ attributes = { LastSwiftMigration = 0700; LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0720; + LastUpgradeCheck = 0820; ORGANIZATIONNAME = "Marco Schmickler"; TargetAttributes = { C98AF5CE1B124D6A00D196CC = { CreatedOnToolsVersion = 6.3.1; DevelopmentTeam = G9J99WBBN9; + LastSwiftMigration = 0820; }; C98AF5E81B124D6A00D196CC = { CreatedOnToolsVersion = 6.3.1; + LastSwiftMigration = 0820; TestTargetID = C98AF5CE1B124D6A00D196CC; }; }; @@ -347,49 +349,49 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 81E453B289EA9615E1980098 /* Embed Pods Frameworks */ = { + 34FE5806529FEB6C56D30822 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-frameworks.sh\"\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-kplayer/Pods-kplayer-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - F554AE493C60519505E761A6 /* Copy Pods Resources */ = { + 5BE7FB291B76EEE317F0B068 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Copy Pods Resources"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; showEnvVarsInLog = 0; }; - FA5E42A873B9445C28CCC025 /* Check Pods Manifest.lock */ = { + 9901417B0A169BA87853DAAE /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "Check Pods Manifest.lock"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-kplayer/Pods-kplayer-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -474,8 +476,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -498,7 +502,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -520,8 +524,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -537,9 +543,10 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.3; + IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -547,8 +554,9 @@ }; C98AF5F41B124D6A00D196CC /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 5C6CBA548F885BF342F594EA /* Pods.debug.xcconfig */; + baseConfigurationReference = 6D522F61736592330F481B4F /* Pods-kplayer.debug.xcconfig */; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -557,13 +565,15 @@ PRODUCT_BUNDLE_IDENTIFIER = "schmickler.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 3.0; }; name = Debug; }; C98AF5F51B124D6A00D196CC /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = A170BFB886D61D57F7009BFC /* Pods.release.xcconfig */; + baseConfigurationReference = DF1DF76780D9CDC55209D1CE /* Pods-kplayer.release.xcconfig */; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -572,6 +582,7 @@ PRODUCT_BUNDLE_IDENTIFIER = "schmickler.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -591,6 +602,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "schmickler.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/kplayer.app/kplayer"; }; name = Debug; @@ -607,6 +619,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "schmickler.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/kplayer.app/kplayer"; }; name = Release; diff --git a/kplayer/AppDelegate.swift b/kplayer/AppDelegate.swift index 8c6a924..b65f204 100644 --- a/kplayer/AppDelegate.swift +++ b/kplayer/AppDelegate.swift @@ -15,11 +15,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController - navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() + navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController @@ -33,6 +33,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele MediaItem(name: "knk_archiv2", path:"", root: "/srv/samba/ren/knk_archiv2", type: ItemType.VIDEOROOT), MediaItem(name: "knk_archiv3", path:"", root: "/srv/samba/ren/knk_archiv3", type: ItemType.VIDEOROOT), MediaItem(name: "knk_archiv4", path:"", root: "/srv/samba/ren/knk_archiv4", type: ItemType.VIDEOROOT), + MediaItem(name: "fetish", path:"", root: "/srv/samba/ren/fetish", type: ItemType.VIDEOROOT), MediaItem(name: "fjoy", path:"", root: "/srv/samba/ren/fjoy", type: ItemType.ROOT), MediaItem(name: "heg", path:"", root: "/srv/samba/ren/heg", type: ItemType.ROOT), MediaItem(name: "ten", path:"", root: "/srv/samba/ren/ten", type: ItemType.ROOT), @@ -41,31 +42,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele MediaItem(name: "series", path:"", root: "/srv/samba/ren/series", type: ItemType.ROOT), MediaItem(name: "bm", path:"", root: "/srv/samba/ren/bm", type: ItemType.ROOT), MediaItem(name: "medieval", path:"", root: "/srv/samba/ren/medieval", type: ItemType.ROOT), - ] return true } - func applicationWillResignActive(application: UIApplication) { + func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - func applicationDidEnterBackground(application: UIApplication) { + func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - func applicationWillEnterForeground(application: UIApplication) { + func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - func applicationDidBecomeActive(application: UIApplication) { + func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - func applicationWillTerminate(application: UIApplication) { + func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() @@ -73,7 +73,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele // MARK: - Split view - func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { + func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { @@ -86,34 +86,34 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDele } // MARK: - Core Data stack - lazy var applicationDocumentsDirectory: NSURL = { + lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "schmickler.kplayer" in the application's documents Application Support directory. - let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) + let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. - let modelURL = NSBundle.mainBundle().URLForResource("kplayer", withExtension: "momd")! - return NSManagedObjectModel(contentsOfURL: modelURL)! + let modelURL = Bundle.main.url(forResource: "kplayer", withExtension: "momd")! + return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) - let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("kplayer.sqlite") + let url = self.applicationDocumentsDirectory.appendingPathComponent("kplayer.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { - try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) + try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() - dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" - dict[NSLocalizedFailureReasonErrorKey] = failureReason + dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? + dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. diff --git a/kplayer/Base.lproj/Main.storyboard b/kplayer/Base.lproj/Main.storyboard index 41cf79f..76b41e8 100644 --- a/kplayer/Base.lproj/Main.storyboard +++ b/kplayer/Base.lproj/Main.storyboard @@ -1,8 +1,12 @@ - + + + + - + + @@ -29,18 +33,18 @@ - + - + @@ -68,9 +72,9 @@ - + - + @@ -81,7 +85,7 @@ - + @@ -134,27 +138,27 @@ - + - + - + - + - + diff --git a/kplayer/Images.xcassets/AppIcon.appiconset/Contents.json b/kplayer/Images.xcassets/AppIcon.appiconset/Contents.json index 36d2c80..1d060ed 100644 --- a/kplayer/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/kplayer/Images.xcassets/AppIcon.appiconset/Contents.json @@ -1,5 +1,15 @@ { "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, { "idiom" : "iphone", "size" : "29x29", @@ -30,6 +40,16 @@ "size" : "60x60", "scale" : "3x" }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, { "idiom" : "ipad", "size" : "29x29", @@ -59,6 +79,11 @@ "idiom" : "ipad", "size" : "76x76", "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" } ], "info" : { diff --git a/kplayer/core/ItemModel.swift b/kplayer/core/ItemModel.swift index 6ad2493..26e3b39 100644 --- a/kplayer/core/ItemModel.swift +++ b/kplayer/core/ItemModel.swift @@ -9,7 +9,7 @@ class ItemModel { var items = [MediaItem]() var itemsMap = Dictionary() - func addItem(item: MediaItem) { + func addItem(_ item: MediaItem) { let path = item.encodedDir! var folder = itemsMap[path] diff --git a/kplayer/core/MediaItem.swift b/kplayer/core/MediaItem.swift index 2034a5e..f3fb3ca 100644 --- a/kplayer/core/MediaItem.swift +++ b/kplayer/core/MediaItem.swift @@ -79,14 +79,14 @@ class MediaItem: CustomDebugStringConvertible { // Nutzinhalt var image: UIImage? - var time: NSTimeInterval? + var time: TimeInterval? var thumbUrl: String? init(name: String, path: String, root: String, type: ItemType) { self.name = name - let trim = NSCharacterSet(charactersInString: "/ ") - self.root = "/" + root.stringByTrimmingCharactersInSet(trim) - self.path = path.stringByTrimmingCharactersInSet(trim) + let trim = CharacterSet(charactersIn: "/ ") + self.root = "/" + root.trimmingCharacters(in: trim) + self.path = path.trimmingCharacters(in: trim) self.type = type children = [MediaItem]() @@ -94,8 +94,8 @@ class MediaItem: CustomDebugStringConvertible { sortName = computeSortName(name) } - private func computeSortName(sname: String) -> String { - var lsortName = sname.stringByReplacingOccurrencesOfString("full", withString: "") + fileprivate func computeSortName(_ sname: String) -> String { + var lsortName = sname.replacingOccurrences(of: "full", with: "") var fullNameArr = lsortName.characters.split { $0 == "_" }.map { @@ -119,9 +119,9 @@ class MediaItem: CustomDebugStringConvertible { */ var snapshotDirPathForVideo: String { let len = "/srv/samba/ren".characters.count - let rootPostfix = (root as NSString).substringFromIndex(len) + let rootPostfix = (root as NSString).substring(from: len) let tpath = "/srv/samba/ren/thumb\(rootPostfix)/\(path)/\(name)" - let enc = tpath.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding)! + let enc = tpath.addingPercentEscapes(using: String.Encoding.isoLatin1)! return enc + "/" } @@ -130,7 +130,7 @@ class MediaItem: CustomDebugStringConvertible { Absolute URL, unter der das Thumbnail des Items abgerufen werden kann. */ var thumbUrlAbsolute: String { - let enc = thumbUrl!.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding)! + let enc = thumbUrl!.addingPercentEscapes(using: String.Encoding.isoLatin1)! return NetworkManager.sharedInstance.baseurl + "/service/download" + enc } @@ -138,22 +138,22 @@ class MediaItem: CustomDebugStringConvertible { Absolute URL, unter der das Image des Items abgerufen werden kann. */ var imageUrlAbsolute: String { - var imageUrl = thumbUrl!.stringByReplacingOccurrencesOfString("_thumb.", withString: ".") - imageUrl = imageUrl.stringByReplacingOccurrencesOfString("?preview=true", withString: "") - imageUrl = imageUrl.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding)! + var imageUrl = thumbUrl!.replacingOccurrences(of: "_thumb.", with: ".") + imageUrl = imageUrl.replacingOccurrences(of: "?preview=true", with: "") + imageUrl = imageUrl.addingPercentEscapes(using: String.Encoding.isoLatin1)! return NetworkManager.sharedInstance.baseurl + "/service/download" + imageUrl } - var playerURL: NSURL? { - let enc = name.stringByReplacingOccurrencesOfString(" ", withString: "%20") + var playerURL: URL? { + let enc = name.replacingOccurrences(of: " ", with: "%20") let s = NetworkManager.sharedInstance.baseurl + "/service/stream" + encodedDir! if s.endsWith("/") { - return NSURL(string: s + enc) + return URL(string: s + enc) } else { - return NSURL(string: s + "/" + enc) + return URL(string: s + "/" + enc) } } @@ -162,7 +162,7 @@ class MediaItem: CustomDebugStringConvertible { */ var fullPath: String { let fpath = "\(root)/\(path)/\(name)" - let enc = fpath.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding) + let enc = fpath.addingPercentEscapes(using: String.Encoding.isoLatin1) return enc! } @@ -173,7 +173,7 @@ class MediaItem: CustomDebugStringConvertible { var encodedDir: String? { let dir = "\(root)/\(path)" - return dir.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding) + return dir.addingPercentEscapes(using: String.Encoding.isoLatin1) } func superRoot() -> MediaItem { @@ -185,7 +185,7 @@ class MediaItem: CustomDebugStringConvertible { } func sort() { - children.sortInPlace({ + children.sort(by: { $0.sortName < $1.sortName }) } diff --git a/kplayer/core/NetworkManager.swift b/kplayer/core/NetworkManager.swift index ff9b615..e4ca12f 100644 --- a/kplayer/core/NetworkManager.swift +++ b/kplayer/core/NetworkManager.swift @@ -5,15 +5,15 @@ import Foundation import Alamofire -import Cent +//import Cent class NetworkManager { static let sharedInstance = NetworkManager() let baseurl = "http://linkstation.local/tomcat/media" - lazy var operationQueue: NSOperationQueue = { - var queue = NSOperationQueue() + lazy var operationQueue: OperationQueue = { + var queue = OperationQueue() queue.name = "Backup queue" queue.maxConcurrentOperationCount = 1 return queue @@ -22,33 +22,33 @@ class NetworkManager { internal typealias Weiter = ([MediaItem]) -> Void - func loadDirs(rootParam: String, completionHandler: Weiter) -> Void { + func loadDirs(_ rootParam: String, completionHandler: @escaping Weiter) -> Void { var root = rootParam - if root.containsString("*") { - root = rootParam[rootParam.startIndex.. 1000) { // print(pathlen) @@ -59,7 +59,7 @@ class NetworkManager { pathlen = 2 } - let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2)) + let path = (s as NSString).substring(with: NSMakeRange(len + 1, pathlen - 2)) let i = MediaItem(name: name, path: path, root: root, type: ItemType.VIDEO) if !name.hasPrefix(".") { res.append(i) @@ -71,27 +71,27 @@ class NetworkManager { } } - func loadPicDirs(rootParam: String, completionHandler: Weiter) -> Void { + func loadPicDirs(_ rootParam: String, completionHandler: @escaping Weiter) -> Void { var root = rootParam - if root.containsString("*") { - root = rootParam[rootParam.startIndex..() let result = json as! [String] @@ -99,10 +99,10 @@ class NetworkManager { for s in result { // print(s) - if s.lowercaseString.hasSuffix(".jpg") { - let l = s.length + if s.lowercased().hasSuffix(".jpg") { + let l = s.characters.count let name = (s as NSString).lastPathComponent - var pathlen = l - len - name.length + var pathlen = l - len - name.characters.count // print(pathlen) // print(name) @@ -112,14 +112,14 @@ class NetworkManager { pathlen = 2 } - let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2)) + let path = (s as NSString).substring(with: NSMakeRange(len + 1, pathlen - 2)) let folderName = NSURL(fileURLWithPath: path).lastPathComponent! - let fl = path.length - let pfl = fl - folderName.length + let fl = path.characters.count + let pfl = fl - folderName.characters.count // print("\(folderName) \(pfl)") - let fpath = (path as NSString).substringWithRange(NSMakeRange(0, pfl)) + let fpath = (path as NSString).substring(with: NSMakeRange(0, pfl)) let i = MediaItem(name: folderName, path: fpath, root: root, type: ItemType.PICS) i.thumbUrl = "\(s)?preview=true" @@ -143,16 +143,16 @@ class NetworkManager { } } - func listDirs(root: String, completionHandler: ([MediaItem], Bool) -> Void) -> Void { + func listDirs(_ root: String, completionHandler: @escaping ([MediaItem], Bool) -> Void) -> Void { let len = root.characters.count - let url = (root as NSString).stringByReplacingOccurrencesOfString(" ", withString: "+") + let url = (root as NSString).replacingOccurrences(of: " ", with: "+") let ux = baseurl + "/service/listdirs" + url print(ux) - Alamofire.request(.GET, ux).responseJSON { - (_, _, response) in + Alamofire.request(ux).responseJSON { + (response) in - if let json = response.value { + if let json = response.result.value { var res = [MediaItem]() var leaf = false var hasPics = false @@ -166,8 +166,7 @@ class NetworkManager { if s == "!!LEAF!!" { leaf = true } else { - let index1 = s.startIndex.advancedBy(len) - let st = s.substringFromIndex(index1) + let st = s.substringStartingFrom(len) // print(st) @@ -175,14 +174,13 @@ class NetworkManager { let i = MediaItem(name: st, path: st, root: root, type: ItemType.FOLDER) res.append(i) } else { - if s.lowercaseString.hasSuffix(".jpg") { + if s.lowercased().hasSuffix(".jpg") { if !hasPics { hasPics = true let name = (root as NSString).lastPathComponent let namelen = name.characters.count - let idx = root.endIndex.advancedBy(namelen * -1) - let rootstart = root.substringToIndex(idx) + let rootstart = root.substringRight(namelen) let i = MediaItem(name: name, path: "", root: rootstart, type: ItemType.DETAILS) res.append(i) } @@ -199,7 +197,7 @@ class NetworkManager { } } - func loadItems(item: MediaItem) { + func loadItems(_ item: MediaItem) { if (item.type != ItemType.FOLDER && item.type != ItemType.DETAILS) { return } @@ -209,10 +207,10 @@ class NetworkManager { loadItem(i, index: j) j+=1 } - NSNotificationCenter.defaultCenter().postNotificationName("loadedItems", object: nil) + NotificationCenter.default.post(name: Notification.Name(rawValue: "loadedItems"), object: nil) } - func loadItem(item: MediaItem, index: Int) { + func loadItem(_ item: MediaItem, index: Int) { if (item.type != ItemType.VIDEO) { var j = 0 for i in item.children { @@ -234,23 +232,22 @@ class NetworkManager { print(url) - Alamofire.request(.GET, url).responseJSON { - (_, _, response) in + Alamofire.request(url).responseJSON { + (response) in - if let json = response.value { + if let json = response.result.value { var hashes = Dictionary() for b in json as! [String] { let p = NSURL(fileURLWithPath: b).lastPathComponent! - if p.containsString("_thumb.jpg") { - let ts = p[0 ..< p.length - 10] + if p.contains("_thumb.jpg") { + let ts = p.substringWithoutLast(10) hashes[ts] = b } else { - let ende = p.length - 4 - let ts = p[0 ..< ende] + let ts = p.substringWithoutLast(4) if hashes[ts] == nil { hashes[ts] = b @@ -258,7 +255,7 @@ class NetworkManager { } } - item.children.removeAll(keepCapacity: true) + item.children.removeAll(keepingCapacity: true) for (ts, p) in hashes { let t = (ts as NSString).doubleValue / 1000 @@ -276,19 +273,19 @@ class NetworkManager { } item.loaded = true - NSNotificationCenter.defaultCenter().postNotificationName("loadedItems", object: item) + NotificationCenter.default.post(name: Notification.Name(rawValue: "loadedItems"), object: item) // println(error) } } } - func favItem(item: MediaItem) { + func favItem(_ item: MediaItem) { let url = baseurl + "/service/linkfav" + item.fullPath - Alamofire.request(.GET, url) + Alamofire.request(url) } - func saveItem(item: MediaItem) { + func saveItem(_ item: MediaItem) { print(item.children) @@ -300,12 +297,12 @@ class NetworkManager { print(url) - Alamofire.request(.GET, url).responseJSON { - (_, _, response) in + Alamofire.request(url).responseJSON { + (response) in var hashes = Set() - if let json = response.value { + if let json = response.result.value { for b in json as! [String] { hashes.insert(b) print(b) @@ -321,7 +318,7 @@ class NetworkManager { if hashes.contains(pt) { print("contained") } else { - if let id = c.image, imageData = UIImageJPEGRepresentation(id, 1.0) { + if let id = c.image, let imageData = UIImageJPEGRepresentation(id, 1.0) { let op = UploadOperation(baseUrl: self.baseurl + "/service/upload", data: imageData, path: p) self.operationQueue.addOperation(op) diff --git a/kplayer/detail/DetailViewController.swift b/kplayer/detail/DetailViewController.swift index e9fb054..d27bdc3 100644 --- a/kplayer/detail/DetailViewController.swift +++ b/kplayer/detail/DetailViewController.swift @@ -32,11 +32,11 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(refreshItems(_:)), name: "loadedItems", object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(refreshItems(_:)), name: NSNotification.Name(rawValue: "loadedItems"), object: nil) } deinit { - NSNotificationCenter.defaultCenter().removeObserver(self, name: "loadedItems", object: nil) + NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "loadedItems"), object: nil) } override func viewDidLoad() { @@ -53,13 +53,13 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout collectionView.dataSource = self collectionView.delegate = self - collectionView.registerClass(ItemCell.self, forCellWithReuseIdentifier: "Cell") - collectionView.backgroundColor = UIColor.lightGrayColor() - collectionView.registerClass(HeaderCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView"); + collectionView.register(ItemCell.self, forCellWithReuseIdentifier: "Cell") + collectionView.backgroundColor = UIColor.lightGray + collectionView.register(HeaderCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView"); view.addSubview(collectionView) view.autoresizesSubviews = true - collectionView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] + collectionView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] // Do any additional setup after loading the view, typically from a nib. collectionView.reloadData() @@ -70,8 +70,8 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout lpgr.delaysTouchesBegan = true self.collectionView.addGestureRecognizer(lpgr); - let overviewButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(overview)); - let favButton = UIBarButtonItem(barButtonSystemItem: .Bookmarks, target: self, action: #selector(favorites)); + let overviewButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(overview)); + let favButton = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(favorites)); navigationItem.rightBarButtonItems = [favButton, overviewButton] if detailItem != nil { print("Details \(detailItem!.children)") @@ -99,15 +99,15 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout pc.items = i pc.completionHandler = { - self.dismissViewControllerAnimated(true, completion: nil); + self.dismiss(animated: true, completion: nil); } let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack. - presentViewController(navController, animated: false, completion: nil) + present(navController, animated: false, completion: nil) } } - func refreshItems(notification: NSNotification) { + func refreshItems(_ notification: Notification) { if notification.object == nil { if self.collectionView != nil { @@ -124,8 +124,8 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout if let detail: MediaItem = self.detailItem { if i.type == ItemType.VIDEO { if i.parent!.type != ItemType.DETAILS { - let path = NSIndexPath(forItem: index, inSection: i.parent!.index) - self.collectionView.reloadItemsAtIndexPaths([path]) + let path = IndexPath(item: index, section: i.parent!.index) + self.collectionView.reloadItems(at: [path]) } } else { if i.parent! !== detail { @@ -135,20 +135,20 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout print("Object: \(oid.hashValue) Index \(index) Item: \(i) Parent: \(i.parent) Detail: \(detailItem)") collectionView.performBatchUpdates({ - var newItems = [NSIndexPath]() + var newItems = [IndexPath]() var j = 0 if detail.children.count > index { - let path = NSIndexPath(forItem: 0, inSection: index) - self.collectionView.reloadItemsAtIndexPaths([path]) + let path = IndexPath(item: 0, section: index) + self.collectionView.reloadItems(at: [path]) for _ in detail.children[index].children { if j >= 1 { - newItems.append(NSIndexPath(forItem: j, inSection: index)) + newItems.append(IndexPath(item: j, section: index)) } j += 1 } - self.collectionView.insertItemsAtIndexPaths(newItems) + self.collectionView.insertItems(at: newItems) } return }, completion: nil) @@ -156,13 +156,13 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout } } - func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) { - if (gestureRecognizer.state != UIGestureRecognizerState.Ended) { + func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) { + if (gestureRecognizer.state != UIGestureRecognizerState.ended) { return; } - let p = gestureRecognizer.locationInView(self.collectionView); + let p = gestureRecognizer.location(in: self.collectionView); - let indexPath = self.collectionView.indexPathForItemAtPoint(p); + let indexPath = self.collectionView.indexPathForItem(at: p); if (indexPath == nil) { print("couldn't find index path"); } else { @@ -173,13 +173,13 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout } else { if indexPath!.item >= items.children.count { } else { - let c = items.children.removeAtIndex(indexPath!.item) + let c = items.children.remove(at: indexPath!.item) if let t = c.time { let ms = Int(t * 1000) let p = c.snapshotDirPathForVideo + "\(ms).jpg" let pt = c.snapshotDirPathForVideo + "\(ms)_thumb.jpg" - Alamofire.request(.GET, NetworkManager.sharedInstance.baseurl + "/service/deletethumb\(p)") - Alamofire.request(.GET, NetworkManager.sharedInstance.baseurl + "/service/deletethumb\(pt)") + Alamofire.request(NetworkManager.sharedInstance.baseurl + "/service/deletethumb\(p)") + Alamofire.request(NetworkManager.sharedInstance.baseurl + "/service/deletethumb\(pt)") } self.collectionView.reloadData() } @@ -189,7 +189,7 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout } } - func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { + func numberOfSections(in collectionView: UICollectionView) -> Int { if let detail: MediaItem = self.detailItem { let cnt = detail.children.count return cnt @@ -197,7 +197,7 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout return 0 } - func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let detail: MediaItem = self.detailItem { let n = detail.children[section].children.count @@ -213,8 +213,8 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout return 0 } - func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { - let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ItemCell + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ItemCell if let detail: MediaItem = self.detailItem { let items = detail.children[indexPath.section] @@ -232,15 +232,15 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout return cell } - func collectionView(collectionView: UICollectionView, + func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, - atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { + at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let headerView = - collectionView.dequeueReusableSupplementaryViewOfKind(kind, + collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderView", - forIndexPath: indexPath) + for: indexPath) as! HeaderCell let items = detailItem!.children[indexPath.section] @@ -251,7 +251,7 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout } } - func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let detail: MediaItem = self.detailItem { var items = detail.children[indexPath.section] if (items.type == ItemType.VIDEO || items.loaded) { @@ -266,7 +266,7 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout } if items.type == ItemType.VIDEO || items.type == ItemType.SNAPSHOT { - performSegueWithIdentifier("showVideo", sender: self) + performSegue(withIdentifier: "showVideo", sender: self) } else { let len = items.root.characters.count @@ -275,18 +275,18 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout print(items) print(url) - Alamofire.request(.GET, url).responseJSON { - (_,_,response) in + Alamofire.request(url).responseJSON { + (response) in - if let json = response.value { + if let json = response.result.value { var im = [MediaItem]() for s in json as! [String] { - if s.lowercaseString.hasSuffix(".jpg") { - let l = s.length + if s.lowercased().hasSuffix(".jpg") { + let l = s.characters.count let name = NSURL(fileURLWithPath: s).lastPathComponent! - var pathlen = l - len - name.length + var pathlen = l - len - name.characters.count // if (pathlen > 1000) { print(pathlen) @@ -297,14 +297,14 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout pathlen = 2 } - let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2)) + let path = (s as NSString).substring(with: NSMakeRange(len + 1, pathlen - 2)) let folderName = NSURL(fileURLWithPath: path).lastPathComponent! - let fl = path.length - let pfl = fl - folderName.length + let fl = path.characters.count + let pfl = fl - folderName.characters.count print("\(folderName) \(pfl)") - let fpath = (s as NSString).substringWithRange(NSMakeRange(0, pfl)) + let fpath = s.substringLeft(pfl) let i = MediaItem(name: folderName, path: fpath, root: items.root, type: ItemType.PICS) i.thumbUrl = "\(s)?preview=true" @@ -318,11 +318,11 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout pc.items = im pc.completionHandler = { - self.dismissViewControllerAnimated(true, completion: nil); + self.dismiss(animated: true, completion: nil); } let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack. - self.presentViewController(navController, animated: false, completion: nil) + self.present(navController, animated: false, completion: nil) } } } @@ -331,14 +331,14 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout // MARK: - Segues - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showVideo" { - let nc = segue.destinationViewController as! UINavigationController + let nc = segue.destination as! UINavigationController let controller = nc.topViewController as! VideoPlayerController controller.currentItem = self.currentItem // controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true - nc.navigationBar.barTintColor = UIColor.blackColor() + nc.navigationBar.barTintColor = UIColor.black controller.completionHandler = { () in @@ -353,7 +353,7 @@ class DetailViewController: UIViewController, UICollectionViewDelegateFlowLayout if let ci = self.currentItem { NetworkManager.sharedInstance.saveItem(ci) } - self.dismissViewControllerAnimated(true, completion: nil); + self.dismiss(animated: true, completion: nil); } } } diff --git a/kplayer/detail/HeaderCell.swift b/kplayer/detail/HeaderCell.swift index cd63eb7..c96aa60 100644 --- a/kplayer/detail/HeaderCell.swift +++ b/kplayer/detail/HeaderCell.swift @@ -29,10 +29,10 @@ class HeaderCell: UICollectionViewCell { "V:|-5-[label]-5-|" ) } - func setItem(item: MediaItem) { + func setItem(_ item: MediaItem) { self.item = item label.text = item.name - backgroundColor = UIColor.grayColor() + backgroundColor = UIColor.gray } } diff --git a/kplayer/detail/ItemCell.swift b/kplayer/detail/ItemCell.swift index da83aaf..a87c35f 100644 --- a/kplayer/detail/ItemCell.swift +++ b/kplayer/detail/ItemCell.swift @@ -23,7 +23,7 @@ class ItemCell: UICollectionViewCell { super.init(frame: frame) image = UIImageView(frame: frame) - image.contentMode = UIViewContentMode.ScaleAspectFit + image.contentMode = UIViewContentMode.scaleAspectFit autolayout(["imag": image], constraints: @@ -31,16 +31,16 @@ class ItemCell: UICollectionViewCell { "V:|[imag]|") } - func setItem(item: MediaItem) { + func setItem(_ item: MediaItem) { self.item = item - if let _ = item.thumbUrl, nsurl = NSURL(string: item.thumbUrlAbsolute) { + if let _ = item.thumbUrl, let nsurl = URL(string: item.thumbUrlAbsolute) { image.hnk_setImageFromURL(nsurl, placeholder: defaultImage) } else { if let i = item.image { image.image = i.scaleToSize(15 * 16, height: 15 * 9) } else if item.children.count > 0 { - if let _ = item.children[0].thumbUrl, nsurl = NSURL(string: item.children[0].thumbUrlAbsolute) { + if let _ = item.children[0].thumbUrl, let nsurl = URL(string: item.children[0].thumbUrlAbsolute) { image.hnk_setImageFromURL(nsurl, placeholder: defaultImage) } } diff --git a/kplayer/detail/VideoPlayerController.swift b/kplayer/detail/VideoPlayerController.swift index bcd5cbf..2521fe7 100644 --- a/kplayer/detail/VideoPlayerController.swift +++ b/kplayer/detail/VideoPlayerController.swift @@ -26,7 +26,7 @@ class VideoPlayerController: UIViewController { let speedOptions = [ 0.25, 0.5, 1.0, 2.0 ] var speedOption = 2 - var thumbnailTime: NSTimeInterval = 0.0 + var thumbnailTime: TimeInterval = 0.0 var edit = true var allowEdit = true @@ -35,39 +35,39 @@ class VideoPlayerController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - barbutton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(VideoPlayerController.twoFingersTwoTaps)); + barbutton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(VideoPlayerController.twoFingersTwoTaps)); navigationItem.rightBarButtonItems = [barbutton!] - backButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(VideoPlayerController.back(_:))) - speedButton = UIBarButtonItem(title:"1.0", style:UIBarButtonItemStyle.Plain, target: self, action: #selector(VideoPlayerController.speed(_:))) - playButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: #selector(VideoPlayerController.startstop(_:))) - reviewButton = UIBarButtonItem(title:"Edit ", style:UIBarButtonItemStyle.Plain, target: self, action: #selector(VideoPlayerController.doEdit(_:))) + backButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(VideoPlayerController.back(_:))) + speedButton = UIBarButtonItem(title:"1.0", style:UIBarButtonItemStyle.plain, target: self, action: #selector(VideoPlayerController.speed(_:))) + playButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(VideoPlayerController.startstop(_:))) + reviewButton = UIBarButtonItem(title:"Edit ", style:UIBarButtonItemStyle.plain, target: self, action: #selector(VideoPlayerController.doEdit(_:))) navigationItem.leftBarButtonItems = [backButton!, playButton!, speedButton!, reviewButton!] - if let c = currentItem, url = c.playerURL { + if let c = currentItem, let url = c.playerURL { print(url) - play(url) + play(url as URL) } } - func doEdit(sender: AnyObject) { + func doEdit(_ sender: AnyObject) { if (!allowEdit) { return } if (edit) { edit = false - reviewButton!.tintColor = UIColor.blueColor() + reviewButton!.tintColor = UIColor.blue } else { edit = true - reviewButton!.tintColor = UIColor.yellowColor() + reviewButton!.tintColor = UIColor.yellow } } - func startstop(sender: AnyObject) { - if moviePlayer!.playbackState == MPMoviePlaybackState.Playing { + func startstop(_ sender: AnyObject) { + if moviePlayer!.playbackState == MPMoviePlaybackState.playing { moviePlayer!.pause() } else { @@ -77,7 +77,7 @@ class VideoPlayerController: UIViewController { print("play") } - func speed(sender: AnyObject) { + func speed(_ sender: AnyObject) { speedOption += 1 if speedOption > 3 { speedOption = 0 @@ -89,32 +89,32 @@ print("play") print("speed \(moviePlayer!.currentPlaybackRate)") } - @IBAction func back(sender: AnyObject) { + @IBAction func back(_ sender: AnyObject) { if let player = self.moviePlayer { player.stop() } completionHandler!() } - func play(url: NSURL) { - self.moviePlayer = ALMoviePlayerController(frame: CGRectMake(0, 0, view.frame.width, view.frame.height)) + func play(_ url: URL) { + self.moviePlayer = ALMoviePlayerController(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)) if let player = self.moviePlayer { - let movieControls = ALMoviePlayerControls(moviePlayer: player, style: ALMoviePlayerControlsStyleDefault); + let movieControls = ALMoviePlayerControls(moviePlayer: player, style: ALMoviePlayerControlsStyleDefault)!; movieControls.fadeDelay = 60 player.controls = movieControls movieControls.style = ALMoviePlayerControlsStyleEmbedded - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VideoPlayerController.exitedFullscreen), name: MPMoviePlayerDidExitFullscreenNotification, object: nil); - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VideoPlayerController.enteredFullscreen), name: MPMoviePlayerDidEnterFullscreenNotification, object: nil); - NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VideoPlayerController.showThumbnail(_:)), name: MPMoviePlayerThumbnailImageRequestDidFinishNotification, object: nil); + NotificationCenter.default.addObserver(self, selector: #selector(VideoPlayerController.exitedFullscreen), name: NSNotification.Name.MPMoviePlayerDidExitFullscreen, object: nil); + NotificationCenter.default.addObserver(self, selector: #selector(VideoPlayerController.enteredFullscreen), name: NSNotification.Name.MPMoviePlayerDidEnterFullscreen, object: nil); + NotificationCenter.default.addObserver(self, selector: #selector(VideoPlayerController.showThumbnail(_:)), name: NSNotification.Name.MPMoviePlayerThumbnailImageRequestDidFinish, object: nil); player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) player.view.sizeToFit() - player.scalingMode = MPMovieScalingMode.AspectFit + player.scalingMode = MPMovieScalingMode.aspectFit // player.controlStyle = MPMovieControlStyle.Embedded - player.movieSourceType = MPMovieSourceType.Streaming - player.repeatMode = MPMovieRepeatMode.One + player.movieSourceType = MPMovieSourceType.streaming + player.repeatMode = MPMovieRepeatMode.one player.contentURL = url self.view.addSubview(player.view) @@ -123,10 +123,10 @@ print("play") } } - func showThumbnail(note: NSNotification) { + func showThumbnail(_ note: Notification) { let userInfo = note.userInfo! as NSDictionary - let thumbnail = userInfo.objectForKey(MPMoviePlayerThumbnailImageKey) as! UIImage - let time = userInfo.objectForKey(MPMoviePlayerThumbnailTimeKey) as! NSTimeInterval + let thumbnail = userInfo.object(forKey: MPMoviePlayerThumbnailImageKey) as! UIImage + let time = userInfo.object(forKey: MPMoviePlayerThumbnailTimeKey) as! TimeInterval let newItem = MediaItem(name: currentItem!.name, path: currentItem!.path, root: currentItem!.root, type: ItemType.SNAPSHOT) newItem.image = thumbnail @@ -139,25 +139,25 @@ print("play") addItemButton(newItem) } - func addItemButton(newItem: MediaItem) { - let frame = CGRectMake(0, 0, 66.0, 44.0); + func addItemButton(_ newItem: MediaItem) { + let frame = CGRect(x: 0, y: 0, width: 66.0, height: 44.0); let button = UIButton(frame: frame) button.showsTouchWhenHighlighted = true - button.addTarget(self, action: #selector(thumbnailClicked(_:)), forControlEvents: .TouchDown) + button.addTarget(self, action: #selector(thumbnailClicked(_:)), for: .touchDown) if newItem.image != nil { let icon = newItem.image!.scaleToSize(66.0, height: 44.0) - button.setBackgroundImage(icon, forState: UIControlState.Normal); + button.setBackgroundImage(icon, for: UIControlState()); } else { if newItem.thumbUrl != nil { - let URL = NSURL(string: newItem.thumbUrlAbsolute)! + let URL = Foundation.URL(string: newItem.thumbUrlAbsolute)! Shared.imageCache.fetch(URL: URL).onSuccess { i in let icon = i.scaleToSize(66.0, height: 44.0) - button.setBackgroundImage(icon, forState: UIControlState.Normal); + button.setBackgroundImage(icon, for: UIControlState.normal); } } } @@ -172,7 +172,7 @@ print("play") buttons[button] = newItem } - func thumbnailClicked(source: UIButton) { + func thumbnailClicked(_ source: UIButton) { moviePlayer!.currentPlaybackTime = buttons[source]!.time! moviePlayer!.currentPlaybackRate = Float(speedOptions[speedOption]) @@ -185,7 +185,7 @@ print("play") if !(player.duration > 0.0) { print("again") - NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(update), userInfo: nil, repeats: false) + Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(update), userInfo: nil, repeats: false) return } @@ -215,7 +215,7 @@ print("play") } func enteredFullscreen() { - let mp = UIApplication.sharedApplication().keyWindow; + let mp = UIApplication.shared.keyWindow; if let moviePlayerContainer = mp!.recursiveSearchForViewWithName("MPVideoContainerView") { if (moviePlayerContainer.gestureRecognizers != nil) { return; @@ -227,33 +227,33 @@ print("play") func exitedFullscreen() { moviePlayer!.view.removeFromSuperview(); moviePlayer = nil; - NSNotificationCenter.defaultCenter().removeObserver(self); + NotificationCenter.default.removeObserver(self); } - func installGestures(moviePlayer: UIView) { + func installGestures(_ moviePlayer: UIView) { let twoFingersTwoTapsGesture = UITapGestureRecognizer(target: self, action: #selector(twoFingersTwoTaps)) twoFingersTwoTapsGesture.numberOfTapsRequired = 2 twoFingersTwoTapsGesture.numberOfTouchesRequired = 2 moviePlayer.addGestureRecognizer(twoFingersTwoTapsGesture) let sR = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight)) - sR.direction = UISwipeGestureRecognizerDirection.Right + sR.direction = UISwipeGestureRecognizerDirection.right sR.numberOfTouchesRequired = 1 moviePlayer.addGestureRecognizer(sR) let sL = UISwipeGestureRecognizer(target: self, action: #selector(swipeLeft)) - sL.direction = UISwipeGestureRecognizerDirection.Left + sL.direction = UISwipeGestureRecognizerDirection.left sL.numberOfTouchesRequired = 1 moviePlayer.addGestureRecognizer(sL) let sR2 = UISwipeGestureRecognizer(target: self, action: #selector(swipeDown)) - sR2.direction = UISwipeGestureRecognizerDirection.Down + sR2.direction = UISwipeGestureRecognizerDirection.down sR2.numberOfTouchesRequired = 1 moviePlayer.addGestureRecognizer(sR2) let sR3 = UISwipeGestureRecognizer(target: self, action: #selector(swipeUp)) - sR3.direction = UISwipeGestureRecognizerDirection.Up + sR3.direction = UISwipeGestureRecognizerDirection.up sR3.numberOfTouchesRequired = 1 moviePlayer.addGestureRecognizer(sR3) @@ -279,7 +279,7 @@ print("play") index = 0 player.contentURL = currentItem!.playerURL player.play() - NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: #selector(update), userInfo: nil, repeats: false) + Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(update), userInfo: nil, repeats: false) return } @@ -322,7 +322,7 @@ print("play") player.contentURL = currentItem!.playerURL player.play() - NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: #selector(update), userInfo: nil, repeats: false) + Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(update), userInfo: nil, repeats: false) return } @@ -343,8 +343,8 @@ print("play") if edit { thumbnailTime = moviePlayer!.currentPlaybackTime print("tap \(thumbnailTime)") - moviePlayer!.requestThumbnailImagesAtTimes([thumbnailTime], - timeOption: MPMovieTimeOption.Exact); + moviePlayer!.requestThumbnailImages(atTimes: [thumbnailTime], + timeOption: MPMovieTimeOption.exact); } else { NetworkManager.sharedInstance.favItem(currentItem!) diff --git a/kplayer/master/MasterViewController.swift b/kplayer/master/MasterViewController.swift index 6646efa..4dd06b8 100644 --- a/kplayer/master/MasterViewController.swift +++ b/kplayer/master/MasterViewController.swift @@ -15,7 +15,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { override func awakeFromNib() { super.awakeFromNib() - if UIDevice.currentDevice().userInterfaceIdiom == .Pad { + if UIDevice.current.userInterfaceIdiom == .pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } @@ -35,11 +35,11 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { // Dispose of any resources that can be recreated. } - func updateSearchResultsForSearchController(search: UISearchController) { + func updateSearchResults(for search: UISearchController) { let str = search.searchBar.text! if str.hasSuffix("*") { - let txt = str[str.startIndex ..< str.endIndex.advancedBy(-1)] + let txt = str[str.startIndex ..< str.characters.index(str.endIndex, offsetBy: -1)] let neu = MediaItem(name: txt, path: model.items[0].parent!.path + "*" + txt, root: model.items[0].parent!.root, type: ItemType.DETAILS) model.items.append(neu) neu.parent = model.items[0].parent @@ -47,14 +47,14 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } } - func selectLoadedItem(selectedItem: MediaItem) { + func selectLoadedItem(_ selectedItem: MediaItem) { switch selectedItem.type { case ItemType.DETAILS: - performSegueWithIdentifier("showDetail", sender: self) + performSegue(withIdentifier: "showDetail", sender: self) case ItemType.FOLDER: if selectedItem.children.first?.type == ItemType.VIDEO { - performSegueWithIdentifier("showDetail", sender: self) + performSegue(withIdentifier: "showDetail", sender: self) } else { gotoNextFolder(selectedItem) } @@ -63,7 +63,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } } - override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("\(indexPath.row)") let selectedItem = model.items[indexPath.row] @@ -125,15 +125,15 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } } - private func gotoNextFolder(selectedItem: MediaItem) { + fileprivate func gotoNextFolder(_ selectedItem: MediaItem) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) - let vc = mainStoryboard.instantiateViewControllerWithIdentifier("mastertable") as! MasterViewController + let vc = mainStoryboard.instantiateViewController(withIdentifier: "mastertable") as! MasterViewController vc.navigationItem.title = selectedItem.name; vc.model.items = selectedItem.children navigationController!.pushViewController(vc, animated: true) } - private func gotoDetails(selectedItem: MediaItem) { + fileprivate func gotoDetails(_ selectedItem: MediaItem) { let weiter: NetworkManager.Weiter = { (g) in @@ -145,7 +145,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { selectedItem.children = model.items selectedItem.loaded = false - if selectedItem.path.containsString("*") { + if selectedItem.path.contains("*") { selectedItem.loaded = true } else { @@ -170,7 +170,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } } } - self.performSegueWithIdentifier("showDetail", sender: self) + self.performSegue(withIdentifier: "showDetail", sender: self) return } @@ -186,16 +186,16 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } } - override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { + override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { return false; } // MARK: - Segues - override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let item = model.items[indexPath.row] - let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController + let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = item if item.isPic() { @@ -212,7 +212,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { } NetworkManager.sharedInstance.loadItems(item) - controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() + controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } @@ -220,33 +220,33 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { // MARK: - Table View - override func numberOfSectionsInTableView(tableView: UITableView) -> Int { + override func numberOfSections(in tableView: UITableView) -> Int { return 1 } - override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model.items.count } - override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } - override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { + override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } - override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { - if editingStyle == .Delete { + override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { + if editingStyle == .delete { } } - func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { + func configureCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) { let object = model.items[indexPath.row] if (object.path.characters.count == 0) { cell.textLabel!.text = "'" + object.name @@ -254,7 +254,7 @@ class MasterViewController: UITableViewController, UISearchResultsUpdating { cell.textLabel!.text = object.path } - cell.accessoryType = UITableViewCellAccessoryType.None + cell.accessoryType = UITableViewCellAccessoryType.none } } diff --git a/kplayer/photo/MediaPhotoController.swift b/kplayer/photo/MediaPhotoController.swift index 5810933..76ae044 100644 --- a/kplayer/photo/MediaPhotoController.swift +++ b/kplayer/photo/MediaPhotoController.swift @@ -7,36 +7,36 @@ import Foundation import Nimbus import Alamofire -class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollViewDataSource, NIPhotoScrubberViewDataSource, NSURLSessionDelegate { +class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollViewDataSource, NIPhotoScrubberViewDataSource, URLSessionDelegate { var items = [MediaItem]() var completionHandler: ((Void) -> Void)? var requests = Array() - var imageCache = NSCache() + var imageCache = NSCache() var total = 0 var slide = 0 - var timer: NSTimer? + var timer: Timer? var currentIndex = 80 - var urlSession: NSURLSession? + var urlSession: Foundation.URLSession? var sessionOwner = false - let dateFormatter = NSDateFormatter() + let dateFormatter = DateFormatter() - lazy var operationQueue: NSOperationQueue = { - var queue = NSOperationQueue() + lazy var operationQueue: OperationQueue = { + var queue = OperationQueue() queue.name = "Photo queue" queue.maxConcurrentOperationCount = 3 return queue }() - override func viewDidDisappear(animated: Bool) { + override func viewDidDisappear(_ animated: Bool) { operationQueue.cancelAllOperations() } @@ -46,7 +46,7 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView title = "(\(idx + 1) / \(photoAlbumView.numberOfPages)) \(selected.path) \(selected.name)" } - public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { + open func URLSession(_ session: Foundation.URLSession, didBecomeInvalidWithError error: NSError?) { print(error) } @@ -55,21 +55,21 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView if urlSession == nil { sessionOwner = true - let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration(); // backgroundSessionConfigurationWithIdentifier("imageLoad"); - configuration.HTTPMaximumConnectionsPerHost = 10; + let configuration = URLSessionConfiguration.ephemeral; // backgroundSessionConfigurationWithIdentifier("imageLoad"); + configuration.httpMaximumConnectionsPerHost = 10; configuration.timeoutIntervalForRequest = 100; configuration.timeoutIntervalForResource = 200; - urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil); + urlSession = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil); } imageCache.totalCostLimit = 1024 * 1024 * 1024 - let backButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(MediaPhotoController.back)) - let slideButton = UIBarButtonItem(barButtonSystemItem: .FastForward, target: self, action: #selector(MediaPhotoController.slideShow)) + let backButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(MediaPhotoController.back)) + let slideButton = UIBarButtonItem(barButtonSystemItem: .fastForward, target: self, action: #selector(MediaPhotoController.slideShow)) navigationItem.leftBarButtonItems = [backButton, slideButton] - let playButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: #selector(MediaPhotoController.play)) - let shotButton = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: #selector(MediaPhotoController.shot)) + let playButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(MediaPhotoController.play)) + let shotButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(MediaPhotoController.shot)) navigationItem.rightBarButtonItems = [playButton, shotButton] setChromeVisibility(true, animated: true) @@ -82,17 +82,17 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView preload(60, count: 20) } - func loadData(d: NSData, start: Int, end: Int) { - let bytes = Array(UnsafeBufferPointer(start: UnsafePointer(d.bytes), count: d.length)) - let string1 = NSString(data: d, encoding: NSUTF8StringEncoding) + func loadData(_ d: Data, start: Int, end: Int) { + let bytes = Array(UnsafeBufferPointer(start: (d as NSData).bytes.bindMemory(to: UInt8.self, capacity: d.count), count: d.count)) + let string1 = NSString(data: d, encoding: String.Encoding.utf8.rawValue) print(string1) var index = 0 let fHi = (Int(bytes[index]) << 24) + (Int(bytes[index+1]) << 16) let f = fHi + (Int(bytes[index+2]) << 8) + Int(bytes[index+3]) // let f = (bytes[index++] << 24)+(bytes[index++] << 16)+(bytes[index++] << 8) + bytes[index++] index += 4 - let time = dateFormatter.stringFromDate(NSDate()) - print("\(time) start \(start) count \(f) size \(d.length)") + let time = dateFormatter.string(from: Date()) + print("\(time) start \(start) count \(f) size \(d.count)") var rest = self.items.count - self.currentIndex @@ -104,34 +104,34 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView self.preload(self.currentIndex, count: rest) self.currentIndex += rest } else { - dispatch_async(dispatch_get_main_queue(), { + DispatchQueue.main.async(execute: { () -> Void in self.photoScrubberView.reloadData(); }) } - for var bild = start; bild < end; bild++ { + for bild in start ..< end { let sizeHi = (Int(bytes[index]) << 24) + (Int(bytes[index+1]) << 16) let size = (Int(bytes[index+2]) << 8) + Int(bytes[index+3]) + sizeHi index += 4 if size > 0 { // var buf = //UnsafeMutablePointer(&bytes[index]) - let part = d.subdataWithRange(NSMakeRange(index, size)) + let part = d.subdata(in: index ..< (index + size)) if let img = UIImage(data: part) { - let imageRef = img.CGImage; - self.total += d.length + let imageRef = img.cgImage; + self.total += d.count let i = self.items[bild] // print("\(time) preload combi image loaded \(i.name) cost \(cost) total\(self.total)") - self.imageCache.setObject(img, forKey: i.thumbUrlAbsolute, cost: size) + self.imageCache.setObject(img, forKey: i.thumbUrlAbsolute as AnyObject, cost: size) } } index += size } } - func preload(start: Int, count: Int) { + func preload(_ start: Int, count: Int) { dateFormatter.dateFormat = "HH:mm:ss.SSSZ" @@ -140,29 +140,34 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView if end > items.count { end = items.count } - for var k = start; k < end; k++ { - let tu = items[k].thumbUrl!.stringByReplacingOccurrencesOfString("?preview=true", withString: "") + + if end < start { + return + } + + for k in start ..< end { + let tu = items[k].thumbUrl!.replacingOccurrences(of: "?preview=true", with: "") preview += "\(tu);" } - preview = preview.stringByAddingPercentEscapesUsingEncoding(NSISOLatin1StringEncoding)! + preview = preview.addingPercentEscapes(using: String.Encoding.isoLatin1)! let u2 = "\(NetworkManager.sharedInstance.baseurl)/service/preload?preview=\(preview)" - let u3 = NSURL(string: u2) + let u3 = URL(string: u2) if let URL = u3 { - let time = dateFormatter.stringFromDate(NSDate()) + let time = dateFormatter.string(from: Date()) print("\(time) preload image \(u2)") - urlSession!.dataTaskWithURL(URL) { + urlSession!.dataTask(with: URL, completionHandler: { (da, response, error) in if let d = da { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { + DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.high).async { () -> Void in self.loadData(d, start: start, end: end) } } - }.resume() + }) .resume() // op1.qualityOfService = NSQualityOfService.Background // backgroundOperationQueue.addOperation(op1) } else { @@ -179,13 +184,13 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView func shot() { let currentItem = items[photoAlbumView.centerPageIndex] - var imageUrl = currentItem.thumbUrl!.stringByReplacingOccurrencesOfString("_thumb.jpg", withString: ".jpg") - imageUrl = imageUrl.stringByReplacingOccurrencesOfString("?preview=true", withString: "") + var imageUrl = currentItem.thumbUrl!.replacingOccurrences(of: "_thumb.jpg", with: ".jpg") + imageUrl = imageUrl.replacingOccurrences(of: "?preview=true", with: "") let url = NetworkManager.sharedInstance.baseurl + "/service/linkfavpic" + imageUrl print(url) - Alamofire.request(.GET, url).responseString { - (_, _, string) in + Alamofire.request(url).responseString { + (result) in print("ok") } } @@ -219,11 +224,11 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView nextItem = 0 } - photoAlbumView.moveToPageAtIndex(nextItem, animated: false); + photoAlbumView.moveToPage(at: nextItem, animated: false); photoScrubberView.setSelectedPhotoIndex(nextItem, animated: true) if (slide > 0) { - timer = NSTimer.scheduledTimerWithTimeInterval(Double(slide) / 2.0, target: self, selector: #selector(showItem), userInfo: nil, repeats: false) + timer = Timer.scheduledTimer(timeInterval: Double(slide) / 2.0, target: self, selector: #selector(showItem), userInfo: nil, repeats: false) } else { timer = nil } @@ -241,18 +246,18 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView print(items) print(url) - Alamofire.request(.GET, url).responseJSON { - (request, response, result) in + Alamofire.request(url).responseJSON { + (response) in var im = [MediaItem]() - if let json = result.value { + if let json = response.result.value { for s in json as! [String] { if s.hasSuffix(".jpg") { - let l = s.length + let l = s.characters.count let name = NSURL(fileURLWithPath: s).lastPathComponent! - var pathlen = l - len - name.length + var pathlen = l - len - name.characters.count // if (pathlen > 1000) { print(pathlen) @@ -263,14 +268,14 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView pathlen = 2 } - let path = (s as NSString).substringWithRange(NSMakeRange(len + 1, pathlen - 2)) + let path = (s as NSString).substring(with: NSMakeRange(len + 1, pathlen - 2)) let folderName = NSURL(fileURLWithPath: path).lastPathComponent! - let fl = path.length - let pfl = fl - folderName.length + let fl = path.length() + let pfl = fl - folderName.length() print("\(folderName) \(pfl)") - let fpath = (s as NSString).substringWithRange(NSMakeRange(0, pfl)) + let fpath = s.substringLeft(pfl) let i = MediaItem(name: folderName, path: fpath, root: items.root, type: ItemType.PICS) i.thumbUrl = "\(s)?preview=true" @@ -285,11 +290,11 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView pc.items = im pc.completionHandler = { - self.dismissViewControllerAnimated(true, completion: nil); + self.dismiss(animated: true, completion: nil); } let navController = UINavigationController(rootViewController: pc) // Creating a navigation controller with pc at the root of the navigation stack. - self.presentViewController(navController, animated: false, completion: nil) + self.present(navController, animated: false, completion: nil) } } return @@ -301,13 +306,13 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView controller.currentItem = currentItem controller.navigationItem.leftItemsSupplementBackButton = true - navigationController!.navigationBar.barTintColor = UIColor.blackColor() + navigationController!.navigationBar.barTintColor = UIColor.black navigationController!.pushViewController(controller, animated: true) controller.completionHandler = { () in // NetworkManager.sharedInstance.saveItem(self.currentItem!) - self.dismissViewControllerAnimated(true, completion: nil); + self.dismiss(animated: true, completion: nil); } } @@ -316,18 +321,17 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView photoAlbumView.dataSource = self photoScrubberView.dataSource = self - toolbarIsTranslucent = true + isToolbarTranslucent = true hidesChromeWhenScrolling = true chromeCanBeHidden = true - scrubberIsEnabled = true + isScrubberEnabled = true // Toolbar Setup let bounds = self.view.bounds; let toolbarHeight = CGFloat(120.0) - toolbar.frame = CGRectMake(0, bounds.size.height - toolbarHeight, bounds.size.width, toolbarHeight); - - photoAlbumView.zoomingAboveOriginalSizeIsEnabled = true; + toolbar.frame = CGRect(x: 0, y: bounds.size.height - toolbarHeight, width: bounds.size.width, height: toolbarHeight) + photoAlbumView.isZoomingAboveOriginalSizeEnabled = true; // This title will be displayed until we get the results back for the album information. self.title = "loading" @@ -336,12 +340,12 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView print("\(items.count)") } - func photoAlbumScrollView(photoAlbumScrollView: NIPhotoAlbumScrollView!, photoAtIndex: Int, photoSize: UnsafeMutablePointer, + func photoAlbumScrollView(_ photoAlbumScrollView: NIPhotoAlbumScrollView!, photoAt photoAtIndex: Int, photoSize: UnsafeMutablePointer, isLoading: UnsafeMutablePointer, originalPhotoDimensions: UnsafeMutablePointer) -> UIImage! { let newItem = items[photoAtIndex] - let u1 = NSURL(string: newItem.imageUrlAbsolute) - let u2 = NSURL(string: newItem.thumbUrlAbsolute) - if let hqURL = u1, URL = u2 { + let u1 = URL(string: newItem.imageUrlAbsolute) + let u2 = URL(string: newItem.thumbUrlAbsolute) + if let hqURL = u1, let u5 = u2 { var image: UIImage? = nil @@ -350,8 +354,8 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView for r in requests { let pages = self.photoAlbumView.visiblePages() as NSMutableSet! var ok = false - for page in pages.allObjects { - if (page.pageIndex == r.index) { + for page in (pages?.allObjects)! { + if ((page as AnyObject).pageIndex == r.index) { ok = true break } @@ -359,32 +363,32 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView if !ok { r.cancel() - requests.removeAtIndex(requests.indexOf(r)!) + requests.remove(at: requests.index(of: r)!) } } - image = imageCache.objectForKey(URL.absoluteString) as? UIImage + image = imageCache.object(forKey: u5.absoluteString as AnyObject) as? UIImage if image != nil { size = NIPhotoScrollViewPhotoSizeThumbnail isLoading[0] = false } else { - let URL = NSURL(string: newItem.thumbUrlAbsolute)! + let ur = URL(string: newItem.thumbUrlAbsolute)! - let op3 = DataLoadOperation(imageURL: URL, succeeder: { + let op3 = DataLoadOperation(imageURL: ur, succeeder: { d in - if d.length > 0 { + if d.count > 0 { if let i = UIImage(data: d) { // println("thumb preload image loaded \(newItem.imageUrlAbsolute)") - let imageRef = i.CGImage; - self.imageCache.setObject(d, forKey: newItem.thumbUrlAbsolute, cost: d.length) + let imageRef = i.cgImage; + self.imageCache.setObject(d as AnyObject, forKey: newItem.thumbUrlAbsolute as AnyObject, cost: d.count) size = NIPhotoScrollViewPhotoSizeThumbnail - self.photoAlbumView.didLoadPhoto(i, atIndex: photoAtIndex, photoSize: size) - self.photoScrubberView.didLoadThumbnail(i, atIndex: photoAtIndex); + self.photoAlbumView.didLoadPhoto(i, at: photoAtIndex, photoSize: size) + self.photoScrubberView.didLoadThumbnail(i, at: photoAtIndex); } } }, index: photoAtIndex, session: urlSession!) - op3.qualityOfService = NSQualityOfService.UserInteractive + op3.qualityOfService = QualityOfService.userInteractive operationQueue.addOperation(op3) } @@ -393,10 +397,10 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView i in // println("image loaded \(newItem.imageUrlAbsolute) at \(photoAtIndex)") size = NIPhotoScrollViewPhotoSizeOriginal - self.photoAlbumView.didLoadPhoto(i, atIndex: photoAtIndex, photoSize: size) + self.photoAlbumView.didLoadPhoto(i, at: photoAtIndex, photoSize: size) photoSize[0] = size }, index: photoAtIndex) - op2.qualityOfService = NSQualityOfService.UserInitiated + op2.qualityOfService = QualityOfService.userInitiated requests.append(op2) operationQueue.addOperation(op2) @@ -414,7 +418,7 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView } } - func numberOfPagesInPagingScrollView(pagingScrollView: NIPagingScrollView) -> Int { + func numberOfPages(in pagingScrollView: NIPagingScrollView) -> Int { let c = items.count return c } @@ -425,8 +429,8 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView * You should always try to reuse pages by calling dequeueReusablePageWithIdentifier: on the * paging scroll view before allocating a new page. */ - func pagingScrollView(pagingScrollView: NIPagingScrollView, pageViewForIndex: Int) -> UIView { - let view = photoAlbumView.pagingScrollView(pagingScrollView, pageViewForIndex: pageViewForIndex) as! NIPhotoScrollView + func pagingScrollView(_ pagingScrollView: NIPagingScrollView, pageViewFor pageViewForIndex: Int) -> UIView { + let view = photoAlbumView.pagingScrollView(pagingScrollView, pageViewFor: pageViewForIndex) as! NIPhotoScrollView view.maximumScale = 3; @@ -434,7 +438,7 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView return view; } - func numberOfPhotosInScrubberView(photoScrubberView: NIPhotoScrubberView!) -> Int { + func numberOfPhotos(in photoScrubberView: NIPhotoScrubberView!) -> Int { let c = items.count return c } @@ -444,30 +448,30 @@ class MediaPhotoController: NIToolbarPhotoViewController, NIPhotoAlbumScrollView * * Please read and understand the performance considerations for this data source. */ - func photoScrubberView(photoScrubberView: NIPhotoScrubberView!, thumbnailAtIndex thumbnailIndex: Int) -> UIImage! { + func photoScrubberView(_ photoScrubberView: NIPhotoScrubberView!, thumbnailAt thumbnailIndex: Int) -> UIImage! { if thumbnailIndex < 0 { return nil } var image: UIImage? let newItem = items[thumbnailIndex] - let u1 = NSURL(string: newItem.thumbUrlAbsolute) + let u1 = URL(string: newItem.thumbUrlAbsolute) if let URL = u1 { - image = imageCache.objectForKey(URL.absoluteString) as? UIImage + image = imageCache.object(forKey: URL.absoluteString as AnyObject) as? UIImage if (image == nil) { - urlSession!.dataTaskWithURL(URL) { + urlSession!.dataTask(with: URL) { (da, response, error) in if let d = da { if let i = UIImage(data: d) { // println("thumb image loaded \(newItem.thumbUrlAbsolute)") - let imageRef = i.CGImage; - self.imageCache.setObject(i, forKey: newItem.thumbUrlAbsolute, cost: d.length) + let imageRef = i.cgImage; + self.imageCache.setObject(i, forKey: newItem.thumbUrlAbsolute as AnyObject, cost: d.count) - self.photoScrubberView.didLoadThumbnail(i, atIndex: thumbnailIndex); + self.photoScrubberView.didLoadThumbnail(i, at: thumbnailIndex); } } } diff --git a/kplayer/util/DataLoadOperation.swift b/kplayer/util/DataLoadOperation.swift index 27c99f8..efc0e5a 100644 --- a/kplayer/util/DataLoadOperation.swift +++ b/kplayer/util/DataLoadOperation.swift @@ -8,19 +8,19 @@ import Alamofire import Darwin -class DataLoadOperation: NSOperation { - internal typealias Succeeder = (NSData) -> () +class DataLoadOperation: Operation { + internal typealias Succeeder = (Data) -> () - let imageURL: NSURL + let imageURL: URL let succeeder: Succeeder let index: Int var ready1 = false - let backgroundSession: NSURLSession - var downloadTask: NSURLSessionDataTask? + let backgroundSession: URLSession + var downloadTask: URLSessionDataTask? - init(imageURL: NSURL, succeeder: Succeeder, index: Int, session: NSURLSession) { + init(imageURL: URL, succeeder: @escaping Succeeder, index: Int, session: URLSession) { self.imageURL = imageURL self.succeeder = succeeder self.index = index @@ -28,17 +28,17 @@ class DataLoadOperation: NSOperation { } override func main() { - if self.cancelled { + if self.isCancelled { return } - let dateFormatter = NSDateFormatter() + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss.SSS" // var configuration = NSURLSessionConfiguration.defaultSessionConfiguration(); // backgroundSessionConfigurationWithIdentifier("imageLoad"); // configuration.HTTPMaximumConnectionsPerHost = 100; // var backgroundSession = NSURLSession(configuration: configuration, delegate: nil, delegateQueue: nil); - let url = NSURLRequest(URL: imageURL); - downloadTask = backgroundSession.dataTaskWithRequest(url, completionHandler: { + let url = URLRequest(url: imageURL); + downloadTask = backgroundSession.dataTask(with: url, completionHandler: { data,response,error in if error == nil { @@ -46,7 +46,7 @@ class DataLoadOperation: NSOperation { // let time = dateFormatter.stringFromDate(NSDate()) // print("\(time) preloaded image \(self.imageURL)") - dispatch_async(dispatch_get_main_queue(), { + DispatchQueue.main.async(execute: { () -> Void in self.succeeder(d) }) diff --git a/kplayer/util/HanekeFetchOperation.swift b/kplayer/util/HanekeFetchOperation.swift index e3cbbff..56f4eea 100644 --- a/kplayer/util/HanekeFetchOperation.swift +++ b/kplayer/util/HanekeFetchOperation.swift @@ -6,25 +6,25 @@ import Foundation import Haneke -class HanekeFetchOperation: NSOperation { - let baseUrl: NSURL +class HanekeFetchOperation: Operation { + let baseUrl: URL let succeeder: Fetch.Succeeder let index: Int - init(baseUrl: NSURL, succeeder: Fetch.Succeeder, index: Int) { + init(baseUrl: URL, succeeder: @escaping Fetch.Succeeder, index: Int) { self.baseUrl = baseUrl self.succeeder = succeeder self.index = index } override func main() { - if self.cancelled { + if self.isCancelled { return } Shared.imageCache.fetch(URL: baseUrl).onSuccess { i in - dispatch_async(dispatch_get_main_queue(), { self.succeeder(i) }) + DispatchQueue.main.async(execute: { self.succeeder(i) }) } } diff --git a/kplayer/util/ImageLoadOperation.swift b/kplayer/util/ImageLoadOperation.swift index a5db54f..da9fdd8 100644 --- a/kplayer/util/ImageLoadOperation.swift +++ b/kplayer/util/ImageLoadOperation.swift @@ -7,48 +7,48 @@ import Foundation import Alamofire import Darwin -class ImageLoadOperation: NSOperation { +class ImageLoadOperation: Operation { internal typealias Succeeder = (UIImage) -> () - let imageURL: NSURL + let imageURL: URL let succeeder: Succeeder let index: Int - var request: Request? + var request: DataRequest? - var manager: Manager? + var manager: SessionManager? var ready1 = false - init(imageURL: NSURL, succeeder: Succeeder, index: Int) { + init(imageURL: URL, succeeder: @escaping Succeeder, index: Int) { self.imageURL = imageURL self.succeeder = succeeder self.index = index } override func main() { - if self.cancelled { + if self.isCancelled { return } - let r = NSMutableURLRequest(URL: imageURL) - r.HTTPBody = nil - r.addValue("0", forHTTPHeaderField: "Content-Length") + let r = URLRequest(url: imageURL) +// r.httpBody = nil +// r.addValue("0", forHTTPHeaderField: "Content-Length") if let m = manager { - request = m.request(.GET, r) + request = m.request(r) } else { - request = Alamofire.request(.GET, r) + request = Alamofire.request(r) } - request!.validate().response { (request, response, data, error) in - if let e = error as? NSError { + request!.response { (response) in + if let e = response.error as? NSError { if (e.code != -999) { print(e) } } - else if let d = data { + else if let d = response.data { self.succeeder(UIImage(data: d, scale: 1)!) } } diff --git a/kplayer/util/LayoutTools.swift b/kplayer/util/LayoutTools.swift index bd0a3f7..6a3a00f 100644 --- a/kplayer/util/LayoutTools.swift +++ b/kplayer/util/LayoutTools.swift @@ -8,15 +8,15 @@ import UIKit public extension UIView { - func autolayout(views: [String:UIView!], constraints: Any...) { + func autolayout(_ views: [String:UIView?], constraints: Any...) { autolay(views, constraints:constraints) } - func autolay(views: [String:UIView!], constraints: [Any]) { + func autolay(_ views: [String:UIView?], constraints: [Any]) { var index = 0; for value in views.values { - let vv: UIView = value + let vv: UIView = value! addSubview(vv) vv.translatesAutoresizingMaskIntoConstraints = false } @@ -25,15 +25,15 @@ public extension UIView { let c = constraints[index] if c is String { if index + 1 < constraints.count && !(constraints[index + 1] is String) { - index++ - let constr: NSArray = NSLayoutConstraint.constraintsWithVisualFormat(c as! String, + index += 1 + let constr: NSArray = NSLayoutConstraint.constraints(withVisualFormat: c as! String, options: constraints[index] as! NSLayoutFormatOptions, metrics: nil, - views: views) + views: views) as NSArray addConstraints(constr as! [NSLayoutConstraint]) } else { - let constr: NSArray = NSLayoutConstraint.constraintsWithVisualFormat(c as! String, - options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) + let constr: NSArray = NSLayoutConstraint.constraints(withVisualFormat: c as! String, + options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) as NSArray addConstraints(constr as! [NSLayoutConstraint]) } } @@ -41,11 +41,11 @@ public extension UIView { } } - func recursiveSearchForViewWithName(classname: String) -> UIView? { + func recursiveSearchForViewWithName(_ classname: String) -> UIView? { for v in subviews { let sv = v let result = sv.recursiveSearchForViewWithName(classname) - let cn = String(v.dynamicType) + let cn = String(describing: type(of: v)) if cn == classname { return v @@ -59,4 +59,4 @@ public extension UIView { } -} \ No newline at end of file +} diff --git a/kplayer/util/NetData.swift b/kplayer/util/NetData.swift index 8de6cf1..a2c4857 100644 --- a/kplayer/util/NetData.swift +++ b/kplayer/util/NetData.swift @@ -33,10 +33,10 @@ enum MimeType: String { class NetData { - let data: NSData + let data: Data let mimeType: MimeType let filename: String - init(data: NSData, mimeType: MimeType, filename: String) { + init(data: Data, mimeType: MimeType, filename: String) { self.data = data self.mimeType = mimeType self.filename = filename diff --git a/kplayer/util/NetworkHelper.swift b/kplayer/util/NetworkHelper.swift index 20452f2..cb5811a 100644 --- a/kplayer/util/NetworkHelper.swift +++ b/kplayer/util/NetworkHelper.swift @@ -6,54 +6,56 @@ import Foundation import Alamofire -func urlRequestWithComponents(urlString: String, parameters: NSDictionary) -> (URLRequestConvertible, NSData) { - // create url request to send - let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!) - mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue - //let boundaryConstant = "myRandomBoundary12345" - let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" - let contentType = "multipart/form-data;boundary=" + boundaryConstant - mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") - - // create upload data to send - let uploadData = NSMutableData() - - // add parameters - for (key, value) in parameters { - - uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) - - if value is NetData { - // add image - let postData = value as! NetData - - //uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) - - // append content disposition - let filenameClause = " filename=\"\(postData.filename)\"" - let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" - let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding) - uploadData.appendData(contentDispositionData!) - - - // append content type - //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this. - let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n" - let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding) - uploadData.appendData(contentTypeData!) - uploadData.appendData(postData.data) - - } else { - uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) - } - } - uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) - - // return URLRequestConvertible and NSData - return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData) -} +//func urlRequestWithComponents(_ urlString: String, parameters: NSDictionary) -> (URLRequestConvertible, NSData) { +// +// // create url request to send +// let mutableURLRequest = MutableURLRequest(url: URL(string: urlString)!) +// mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue +// //let boundaryConstant = "myRandomBoundary12345" +// let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" +// let contentType = "multipart/form-data;boundary=" + boundaryConstant +// mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") +// +// +// // create upload data to send +// let uploadData = NSMutableData() +// +// // add parameters +// for (key, value) in parameters { +// +// uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!) +// +// if value is NetData { +// // add image +// let postData = value as! NetData +// +// //uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) +// +// // append content disposition +// let filenameClause = " filename=\"\(postData.filename)\"" +// let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" +// let contentDispositionData = contentDispositionString.data(using: String.Encoding.utf8) +// uploadData.append(contentDispositionData!) +// +// +// // append content type +// //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this. +// let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n" +// let contentTypeData = contentTypeString.data(using: String.Encoding.utf8) +// uploadData.append(contentTypeData!) +// uploadData.append(postData.data) +// +// } else { +// uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!) +// } +// } +// uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!) +// +// // return URLRequestConvertible and NSData +// return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData) +//} class NetworkHelper { } diff --git a/kplayer/util/UIImageExtension.swift b/kplayer/util/UIImageExtension.swift index a631ca7..46e1eef 100644 --- a/kplayer/util/UIImageExtension.swift +++ b/kplayer/util/UIImageExtension.swift @@ -7,21 +7,21 @@ import Foundation import UIKit extension UIImage { - func scaleToSize(width: CGFloat, height: CGFloat) -> UIImage { - UIGraphicsBeginImageContext(CGSizeMake(width, height)); + func scaleToSize(_ width: CGFloat, height: CGFloat) -> UIImage { + UIGraphicsBeginImageContext(CGSize(width: width, height: height)); let context = UIGraphicsGetCurrentContext(); - CGContextTranslateCTM(context, 0.0, height); - CGContextScaleCTM(context, 1.0, -1.0); + context?.translateBy(x: 0.0, y: height); + context?.scaleBy(x: 1.0, y: -1.0); - CGContextDrawImage(context, CGRectMake(0.0, 0.0, width, height), self.CGImage); + context?.draw(self.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: width, height: height)); let scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); - return scaledImage; + return scaledImage!; } -} \ No newline at end of file +} diff --git a/kplayer/util/UploadOperation.swift b/kplayer/util/UploadOperation.swift index 79db128..0ef4e36 100644 --- a/kplayer/util/UploadOperation.swift +++ b/kplayer/util/UploadOperation.swift @@ -6,46 +6,51 @@ import Foundation import Alamofire -class UploadOperation: NSOperation { +class UploadOperation: Operation { let baseUrl: String - let data: NSData + let data: Data let path: String - init(baseUrl: String, data: NSData, path: String) { + init(baseUrl: String, data: Data, path: String) { self.baseUrl = baseUrl self.data = data self.path = path } override func main() { - if self.cancelled { + if self.isCancelled { return } - let parameters = [ - "file": NetData(data: data, mimeType: MimeType.Json, filename: path), - "name": path - ] - print("PATH: \(path)") - let urlRequest = urlRequestWithComponents(baseUrl, parameters: parameters) - Alamofire.upload(urlRequest.0, data: urlRequest.1) - - // success: todo set url to item + Alamofire.upload(multipartFormData: { multipartFormData in + multipartFormData.append(self.data, withName: "file", fileName: self.path, mimeType: MimeType.Json.rawValue) + multipartFormData.append(self.path.data(using: String.Encoding.utf8)!, withName: "name") + }, to: baseUrl, + encodingCompletion: { encodingResult in + switch encodingResult { + case .success(let upload, _, _): + upload.responseJSON { response in + print(response.result.value) + } + case .failure(let error): + print(error) + } + }) // .progress { // (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in // print("progress : \(totalBytesWritten) / \(totalBytesExpectedToWrite)") // } - .response { (request, response, data, error) in - if let d = data { - let datastring = NSString(data: d, encoding:NSUTF8StringEncoding) - print("d \(datastring)") - } - if let e = error { - print("e \(e)") - } - } +// .response { (request, response, data, error) in +// if let d = data { +// let datastring = NSString(data: d, encoding:NSUTF8StringEncoding) +// print("d \(datastring)") +// } +// if let e = error { +// print("e \(e)") +// } +// } } } diff --git a/kplayer/util/ViewControllerExtensions.swift b/kplayer/util/ViewControllerExtensions.swift index 67fc035..fef54b0 100644 --- a/kplayer/util/ViewControllerExtensions.swift +++ b/kplayer/util/ViewControllerExtensions.swift @@ -16,9 +16,9 @@ public extension UIView { public extension UIViewController { - func findControllerInHierachy(_: T.Type) -> T? { + func findControllerInHierachy(_: T.Type) -> T? where T:UIViewController { var currentVC = self - while let parentVC = currentVC.parentViewController { + while let parentVC = currentVC.parent { print("comparing \(parentVC) to \(T.description())") if let result = parentVC as? T { // (XXX) @@ -29,7 +29,7 @@ public extension UIViewController { return nil } - func findChildController(my: T.Type) -> T? { + func findChildController(_ my: T.Type) -> T? { for child in childViewControllers { if let result = child as? T { // (XXX) @@ -43,7 +43,7 @@ public extension UIViewController { return nil } - func removeAllConstraints(otherView: UIView) { + func removeAllConstraints(_ otherView: UIView) { var cons = [NSLayoutConstraint]() for con:NSLayoutConstraint in self.view.constraints { if (con.firstItem as? UIView == otherView || con.secondItem as? UIView == otherView) { @@ -57,10 +57,10 @@ public extension UIViewController { otherView.translatesAutoresizingMaskIntoConstraints = true; } - func embedChildViewController(vc: UIViewController, inView: UIView) { + func embedChildViewController(_ vc: UIViewController, inView: UIView) { vc.view.frame = inView.bounds; addChildViewController(vc); inView.removeAllSubViews(); inView.addSubview(vc.view); } -} \ No newline at end of file +} diff --git a/kplayer/util/stringutil.swift b/kplayer/util/stringutil.swift index 2e1aa68..59a46b7 100644 --- a/kplayer/util/stringutil.swift +++ b/kplayer/util/stringutil.swift @@ -6,11 +6,39 @@ import Foundation public extension String { - func beginsWith (str: String) -> Bool { + func beginsWith (_ str: String) -> Bool { return hasPrefix(str) } - func endsWith (str: String) -> Bool { + func endsWith (_ str: String) -> Bool { return hasSuffix(str) } -} \ No newline at end of file + + // die ersten X Zeichen + func substringLeft(_ idx: Int) -> String { + let ix = index(startIndex, offsetBy: idx) + return substring(to: ix) + } + + // ohne die letzten X zeichen + func substringWithoutLast(_ idx: Int) -> String { + let ix = index(endIndex, offsetBy: idx * -1) + return substring(to: ix) + } + + // ab X bis zum Ende + func substringStartingFrom(_ idx: Int) -> String { + let ix = index(startIndex, offsetBy: idx) + return substring(from: ix) + } + + // die letzten X Zeichen + func substringRight (_ idx: Int) -> String { + let ix = index(endIndex, offsetBy: idx * -1) + return substring(from: ix) + } + + func length() -> Int { + return characters.count + } +} diff --git a/kplayerTests/kplayerTests.swift b/kplayerTests/kplayerTests.swift index 9839bf6..9639b15 100644 --- a/kplayerTests/kplayerTests.swift +++ b/kplayerTests/kplayerTests.swift @@ -33,7 +33,7 @@ class kplayerTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock() { + self.measure() { // Put the code you want to measure the time of here. } }