diff --git a/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj b/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj new file mode 100644 index 00000000..bcf11861 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj @@ -0,0 +1,389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 02C7B54A2500114200C4A310 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B5492500114200C4A310 /* AppDelegate.swift */; }; + 02C7B54C2500114200C4A310 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B54B2500114200C4A310 /* SceneDelegate.swift */; }; + 02C7B5512500114200C4A310 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 02C7B54F2500114200C4A310 /* Main.storyboard */; }; + 02C7B5532500114A00C4A310 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 02C7B5522500114A00C4A310 /* Assets.xcassets */; }; + 02C7B5562500114A00C4A310 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 02C7B5542500114A00C4A310 /* LaunchScreen.storyboard */; }; + 02C7B55E2500132300C4A310 /* ImagePostViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B55D2500132300C4A310 /* ImagePostViewController.swift */; }; + 02C7B56025001AF000C4A310 /* UIImage+Scaling.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B55F25001AF000C4A310 /* UIImage+Scaling.swift */; }; + 02C7B56225001CD900C4A310 /* Image+Ratio.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56125001CD900C4A310 /* Image+Ratio.swift */; }; + 02C7B56425001DDB00C4A310 /* UIViewController+InformationalAlert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56325001DDB00C4A310 /* UIViewController+InformationalAlert.swift */; }; + 02C7B56625001E4300C4A310 /* BlurViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56525001E4300C4A310 /* BlurViewController.swift */; }; + 02C7B56A25001E9E00C4A310 /* ColorViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56925001E9E00C4A310 /* ColorViewController.swift */; }; + 02C7B56C25001EBE00C4A310 /* DistortionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56B25001EBE00C4A310 /* DistortionViewController.swift */; }; + 02C7B57025001EE600C4A310 /* SharpenViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B56F25001EE600C4A310 /* SharpenViewController.swift */; }; + 02C7B572250140EB00C4A310 /* ColorInvertViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B571250140EB00C4A310 /* ColorInvertViewController.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 02C7B5462500114200C4A310 /* ImageFilterEditor.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ImageFilterEditor.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 02C7B5492500114200C4A310 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 02C7B54B2500114200C4A310 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 02C7B5502500114200C4A310 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 02C7B5522500114A00C4A310 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 02C7B5552500114A00C4A310 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 02C7B5572500114A00C4A310 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 02C7B55D2500132300C4A310 /* ImagePostViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagePostViewController.swift; sourceTree = ""; }; + 02C7B55F25001AF000C4A310 /* UIImage+Scaling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Scaling.swift"; sourceTree = ""; }; + 02C7B56125001CD900C4A310 /* Image+Ratio.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Image+Ratio.swift"; sourceTree = ""; }; + 02C7B56325001DDB00C4A310 /* UIViewController+InformationalAlert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIViewController+InformationalAlert.swift"; sourceTree = ""; }; + 02C7B56525001E4300C4A310 /* BlurViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlurViewController.swift; sourceTree = ""; }; + 02C7B56925001E9E00C4A310 /* ColorViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorViewController.swift; sourceTree = ""; }; + 02C7B56B25001EBE00C4A310 /* DistortionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DistortionViewController.swift; sourceTree = ""; }; + 02C7B56F25001EE600C4A310 /* SharpenViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharpenViewController.swift; sourceTree = ""; }; + 02C7B571250140EB00C4A310 /* ColorInvertViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorInvertViewController.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 02C7B5432500114200C4A310 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02C7B53D2500114200C4A310 = { + isa = PBXGroup; + children = ( + 02C7B5482500114200C4A310 /* ImageFilterEditor */, + 02C7B5472500114200C4A310 /* Products */, + ); + sourceTree = ""; + }; + 02C7B5472500114200C4A310 /* Products */ = { + isa = PBXGroup; + children = ( + 02C7B5462500114200C4A310 /* ImageFilterEditor.app */, + ); + name = Products; + sourceTree = ""; + }; + 02C7B5482500114200C4A310 /* ImageFilterEditor */ = { + isa = PBXGroup; + children = ( + 02C7B55D2500132300C4A310 /* ImagePostViewController.swift */, + 02C7B56825001E5A00C4A310 /* Filter View Controllers */, + 02C7B56725001E4B00C4A310 /* Helper */, + 02C7B5492500114200C4A310 /* AppDelegate.swift */, + 02C7B54B2500114200C4A310 /* SceneDelegate.swift */, + 02C7B54F2500114200C4A310 /* Main.storyboard */, + 02C7B5522500114A00C4A310 /* Assets.xcassets */, + 02C7B5542500114A00C4A310 /* LaunchScreen.storyboard */, + 02C7B5572500114A00C4A310 /* Info.plist */, + ); + path = ImageFilterEditor; + sourceTree = ""; + }; + 02C7B56725001E4B00C4A310 /* Helper */ = { + isa = PBXGroup; + children = ( + 02C7B55F25001AF000C4A310 /* UIImage+Scaling.swift */, + 02C7B56125001CD900C4A310 /* Image+Ratio.swift */, + 02C7B56325001DDB00C4A310 /* UIViewController+InformationalAlert.swift */, + ); + path = Helper; + sourceTree = ""; + }; + 02C7B56825001E5A00C4A310 /* Filter View Controllers */ = { + isa = PBXGroup; + children = ( + 02C7B56525001E4300C4A310 /* BlurViewController.swift */, + 02C7B56925001E9E00C4A310 /* ColorViewController.swift */, + 02C7B56B25001EBE00C4A310 /* DistortionViewController.swift */, + 02C7B56F25001EE600C4A310 /* SharpenViewController.swift */, + 02C7B571250140EB00C4A310 /* ColorInvertViewController.swift */, + ); + path = "Filter View Controllers"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 02C7B5452500114200C4A310 /* ImageFilterEditor */ = { + isa = PBXNativeTarget; + buildConfigurationList = 02C7B55A2500114A00C4A310 /* Build configuration list for PBXNativeTarget "ImageFilterEditor" */; + buildPhases = ( + 02C7B5422500114200C4A310 /* Sources */, + 02C7B5432500114200C4A310 /* Frameworks */, + 02C7B5442500114200C4A310 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ImageFilterEditor; + productName = ImageFilterEditor; + productReference = 02C7B5462500114200C4A310 /* ImageFilterEditor.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 02C7B53E2500114200C4A310 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1150; + LastUpgradeCheck = 1150; + ORGANIZATIONNAME = "Morgan Smith"; + TargetAttributes = { + 02C7B5452500114200C4A310 = { + CreatedOnToolsVersion = 11.5; + }; + }; + }; + buildConfigurationList = 02C7B5412500114200C4A310 /* Build configuration list for PBXProject "ImageFilterEditor" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 02C7B53D2500114200C4A310; + productRefGroup = 02C7B5472500114200C4A310 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 02C7B5452500114200C4A310 /* ImageFilterEditor */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 02C7B5442500114200C4A310 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 02C7B5562500114A00C4A310 /* LaunchScreen.storyboard in Resources */, + 02C7B5532500114A00C4A310 /* Assets.xcassets in Resources */, + 02C7B5512500114200C4A310 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 02C7B5422500114200C4A310 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 02C7B56625001E4300C4A310 /* BlurViewController.swift in Sources */, + 02C7B572250140EB00C4A310 /* ColorInvertViewController.swift in Sources */, + 02C7B54A2500114200C4A310 /* AppDelegate.swift in Sources */, + 02C7B56A25001E9E00C4A310 /* ColorViewController.swift in Sources */, + 02C7B56025001AF000C4A310 /* UIImage+Scaling.swift in Sources */, + 02C7B55E2500132300C4A310 /* ImagePostViewController.swift in Sources */, + 02C7B56C25001EBE00C4A310 /* DistortionViewController.swift in Sources */, + 02C7B54C2500114200C4A310 /* SceneDelegate.swift in Sources */, + 02C7B57025001EE600C4A310 /* SharpenViewController.swift in Sources */, + 02C7B56225001CD900C4A310 /* Image+Ratio.swift in Sources */, + 02C7B56425001DDB00C4A310 /* UIViewController+InformationalAlert.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 02C7B54F2500114200C4A310 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 02C7B5502500114200C4A310 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 02C7B5542500114A00C4A310 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 02C7B5552500114A00C4A310 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 02C7B5582500114A00C4A310 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.5; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 02C7B5592500114A00C4A310 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.5; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 02C7B55B2500114A00C4A310 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = ImageFilterEditor/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.ImageFilterEditor; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 02C7B55C2500114A00C4A310 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = ImageFilterEditor/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.ImageFilterEditor; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 02C7B5412500114200C4A310 /* Build configuration list for PBXProject "ImageFilterEditor" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 02C7B5582500114A00C4A310 /* Debug */, + 02C7B5592500114A00C4A310 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 02C7B55A2500114A00C4A310 /* Build configuration list for PBXNativeTarget "ImageFilterEditor" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 02C7B55B2500114A00C4A310 /* Debug */, + 02C7B55C2500114A00C4A310 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 02C7B53E2500114200C4A310 /* Project object */; +} diff --git a/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift b/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift new file mode 100644 index 00000000..e47fb9bc --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift @@ -0,0 +1,37 @@ +// +// AppDelegate.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + // MARK: UISceneSession Lifecycle + + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + } + + +} + diff --git a/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/AppIcon.appiconset/Contents.json b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..9221b9bb --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/Contents.json b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ImageFilterEditor/ImageFilterEditor/Base.lproj/LaunchScreen.storyboard b/ImageFilterEditor/ImageFilterEditor/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..865e9329 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ImageFilterEditor/ImageFilterEditor/Base.lproj/Main.storyboard b/ImageFilterEditor/ImageFilterEditor/Base.lproj/Main.storyboard new file mode 100644 index 00000000..070abde0 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Base.lproj/Main.storyboard @@ -0,0 +1,628 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/BlurViewController.swift b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/BlurViewController.swift new file mode 100644 index 00000000..0fc5c4e7 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/BlurViewController.swift @@ -0,0 +1,107 @@ +// +// BlurViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class BlurViewController: UIViewController { + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var blurSlider: UISlider! + + private let context = CIContext(options: nil) + let filter = CIFilter(name: "CIGaussianBlur")! + + let imagePostController = ImagePostViewController.sharedPhoto + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + setUpBlurSlider() + imageView.image = imagePostController + originalImage = imageView.image + } + + @IBAction func saveTapped(_ sender: Any) { + + } + + @IBAction func blurChanged(_ sender: UISlider) { + updateImage() + } + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(blurSlider.value, forKey: "inputRadius") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + func setUpBlurSlider() { + if let inputRadiusDictionary = filter.attributes["inputRadius"] as? [String: Any], + let sliderMin = inputRadiusDictionary[kCIAttributeSliderMin] as? Float, + let sliderMax = inputRadiusDictionary[kCIAttributeSliderMax] as? Float, + let identity = inputRadiusDictionary[kCIAttributeIdentity] as? Float { + + blurSlider.minimumValue = sliderMin + blurSlider.maximumValue = sliderMax + blurSlider.value = identity + } + } + + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveBlur" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} diff --git a/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorInvertViewController.swift b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorInvertViewController.swift new file mode 100644 index 00000000..6549e1ed --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorInvertViewController.swift @@ -0,0 +1,89 @@ +// +// ColorInvertViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class ColorInvertViewController: UIViewController { + @IBOutlet weak var imageView: UIImageView! + private let context = CIContext(options: nil) + + let imagePostController = ImagePostViewController.sharedPhoto + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + imageView.image = imagePostController + originalImage = imageView.image + } + + @IBAction func saveTapped(_ sender: Any) { + + } + @IBAction func invertTapped(_ sender: Any) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let filter = CIFilter(name: "CIColorInvert")! + filter.setValue(ciImage, forKey: "inputImage") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveColorInvert" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + + } + diff --git a/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorViewController.swift b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorViewController.swift new file mode 100644 index 00000000..f986e867 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/ColorViewController.swift @@ -0,0 +1,115 @@ +// +// ColorViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class ColorViewController: UIViewController { + + @IBOutlet weak var brightnessSlider: UISlider! + @IBOutlet weak var contrastSlider: UISlider! + @IBOutlet weak var saturationSlider: UISlider! + @IBOutlet weak var imageView: UIImageView! + + private let context = CIContext(options: nil) + + let imagePostController = ImagePostViewController.sharedPhoto + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + imageView.image = imagePostController + originalImage = imageView.image + } + + @IBAction func brightnessChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func contrastChanged(_ sender: Any) { + updateImage() + } + + @IBAction func saturationChanged(_ sender: Any) { + updateImage() + } + + + @IBAction func cancelTapped(_ sender: Any) { + navigationController?.popViewController(animated: true) + } + + @IBAction func saveTapped(_ sender: Any) { + + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + + let filter = CIFilter(name: "CIColorControls")! + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(saturationSlider.value, forKey: "inputSaturation") + filter.setValue(brightnessSlider.value, forKey: "inputBrightness") + filter.setValue(contrastSlider.value, forKey: "inputContrast") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + + + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveColor" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + + +} diff --git a/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/DistortionViewController.swift b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/DistortionViewController.swift new file mode 100644 index 00000000..d7c42cfc --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/DistortionViewController.swift @@ -0,0 +1,116 @@ +// +// DistortionViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class DistortionViewController: UIViewController { + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var radiusSlider: UISlider! + @IBOutlet weak var angleSlider: UISlider! + @IBOutlet weak var xCenterSlider: UISlider! + @IBOutlet weak var yCenterSlider: UISlider! + + + private let context = CIContext(options: nil) + let filter = CIFilter(name: "CIVortexDistortion")! + + let imagePostController = ImagePostViewController.sharedPhoto + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + imageView.image = imagePostController + originalImage = imageView.image + } + + @IBAction func saveTapped(_ sender: Any) { + + } + + @IBAction func radiusChanged(_ sender: UISlider) { + updateImage() + } + @IBAction func angleChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func xCenterChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func yCenterChanged(_ sender: UISlider) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let center = CIVector(x: CGFloat(xCenterSlider.value), y: CGFloat(yCenterSlider.value)) + + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(radiusSlider.value, forKey: "inputRadius") + filter.setValue(angleSlider.value, forKey: "inputAngle") + filter.setValue(center, forKey: "inputCenter") + + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveDistortion" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} + diff --git a/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/SharpenViewController.swift b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/SharpenViewController.swift new file mode 100644 index 00000000..5e546846 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filter View Controllers/SharpenViewController.swift @@ -0,0 +1,93 @@ +// +// SharpenViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class SharpenViewController: UIViewController { + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var sharpenSlider: UISlider! + + private let context = CIContext(options: nil) + + let imagePostController = ImagePostViewController.sharedPhoto + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + imageView.image = imagePostController + originalImage = imageView.image + } + + @IBAction func saveTapped(_ sender: Any) { + + } + @IBAction func sharpenTapped(_ sender: Any) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let filter = CIFilter(name: "CISharpenLuminance")! + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(sharpenSlider.value, forKey: "inputSharpness") + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveSharpen" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} + + diff --git a/ImageFilterEditor/ImageFilterEditor/Helper/Image+Ratio.swift b/ImageFilterEditor/ImageFilterEditor/Helper/Image+Ratio.swift new file mode 100644 index 00000000..a80e2b92 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Helper/Image+Ratio.swift @@ -0,0 +1,16 @@ +// +// Image+Ratio.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + + +import UIKit + +extension UIImage { + var ratio: CGFloat { + return size.height / size.width + } +} diff --git a/ImageFilterEditor/ImageFilterEditor/Helper/UIImage+Scaling.swift b/ImageFilterEditor/ImageFilterEditor/Helper/UIImage+Scaling.swift new file mode 100644 index 00000000..d60f0c4a --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Helper/UIImage+Scaling.swift @@ -0,0 +1,38 @@ +// +// UIImage+Scaling.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// +import UIKit + +extension UIImage { + + /// Resize the image to a max dimension from size parameter + func imageByScaling(toSize size: CGSize) -> UIImage? { + guard size.width > 0 && size.height > 0 else { return nil } + + let originalAspectRatio = self.size.width/self.size.height + var correctedSize = size + + if correctedSize.width > correctedSize.width*originalAspectRatio { + correctedSize.width = correctedSize.width*originalAspectRatio + } else { + correctedSize.height = correctedSize.height/originalAspectRatio + } + + return UIGraphicsImageRenderer(size: correctedSize, format: imageRendererFormat).image { context in + draw(in: CGRect(origin: .zero, size: correctedSize)) + } + } + + /// Renders the image if the pixel data was rotated due to orientation of camera + var flattened: UIImage { + if imageOrientation == .up { return self } + return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { context in + draw(at: .zero) + } + } +} + diff --git a/ImageFilterEditor/ImageFilterEditor/Helper/UIViewController+InformationalAlert.swift b/ImageFilterEditor/ImageFilterEditor/Helper/UIViewController+InformationalAlert.swift new file mode 100644 index 00000000..f39803cf --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Helper/UIViewController+InformationalAlert.swift @@ -0,0 +1,22 @@ +// +// UIViewController+InformationalAlert.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +extension UIViewController { + + func presentInformationalAlertController(title: String?, message: String?, dismissActionCompletion: ((UIAlertAction) -> Void)? = nil, completion: (() -> Void)? = nil) { + let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) + let dismissAction = UIAlertAction(title: "Dismiss", style: .cancel, handler: dismissActionCompletion) + + alertController.addAction(dismissAction) + + present(alertController, animated: true, completion: completion) + } +} + diff --git a/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift b/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift new file mode 100644 index 00000000..383bc73d --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift @@ -0,0 +1,132 @@ +// +// ImagePostViewController.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +import CoreImage.CIFilterBuiltins + +class ImagePostViewController: UIViewController { + + var imageData: Data? + var filteredImage: UIImage? + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var titleTextField: UITextField! + @IBOutlet weak var chooseImageButton: UIBarButtonItem! + @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint! + @IBOutlet weak var postButton: UIBarButtonItem! + + static var sharedPhoto = UIImage() + + override func viewDidLoad() { + super.viewDidLoad() + if let filtered = filteredImage { + imageView.image = filtered + } else { + updateViews() + } + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(true) + if let filtered = filteredImage { + imageView.image = filtered + } else { + updateViews() + } + } + + func updateViews() { + guard let imageData = imageData, + let image = UIImage(data: imageData) else { + title = "New Post" + return + } + title = "New Title" + imageView.image = image + } + + + @IBAction func filterPhoto(_ sender: Any) { + ImagePostViewController.sharedPhoto = imageView.image ?? UIImage(systemName: "photo")! + } + + + @IBAction func chooseImage(_ sender: Any) { + + let authorizationStatus = PHPhotoLibrary.authorizationStatus() + + switch authorizationStatus { + case .authorized: + presentImagePickerController() + case .notDetermined: + + PHPhotoLibrary.requestAuthorization { (status) in + + guard status == .authorized else { + NSLog("User did not authorize access to the photo library") + self.presentInformationalAlertController(title: "Error", message: "In order to access the photo library, you must allow this application access to it.") + return + } + + self.presentImagePickerController() + } + + case .denied: + self.presentInformationalAlertController(title: "Error", message: "In order to access the photo library, you must allow this application access to it.") + case .restricted: + self.presentInformationalAlertController(title: "Error", message: "Unable to access the photo library. Your device's restrictions do not allow access.") + + @unknown default: + print("FatalError") + } + presentImagePickerController() + + } + + private func presentImagePickerController() { + + guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else { + presentInformationalAlertController(title: "Error", message: "The photo library is unavailable") + return + } + + let imagePicker = UIImagePickerController() + + imagePicker.delegate = self + + imagePicker.sourceType = .photoLibrary + + present(imagePicker, animated: true, completion: nil) + } + + + + // MARK: - Navigation + +} + +extension ImagePostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { + + func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { + + + picker.dismiss(animated: true, completion: nil) + + guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } + + imageView.image = image + + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + picker.dismiss(animated: true, completion: nil) + } +} + diff --git a/ImageFilterEditor/ImageFilterEditor/Info.plist b/ImageFilterEditor/ImageFilterEditor/Info.plist new file mode 100644 index 00000000..491ec2ac --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Info.plist @@ -0,0 +1,68 @@ + + + + + NSPhotoLibraryUsageDescription + User can filter photos + NSPhotoLibraryAddUsageDescription + User can add photos + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ImageFilterEditor/ImageFilterEditor/SceneDelegate.swift b/ImageFilterEditor/ImageFilterEditor/SceneDelegate.swift new file mode 100644 index 00000000..87746ffc --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/SceneDelegate.swift @@ -0,0 +1,53 @@ +// +// SceneDelegate.swift +// ImageFilterEditor +// +// Created by Morgan Smith on 9/2/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. + // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + guard let _ = (scene as? UIWindowScene) else { return } + } + + func sceneDidDisconnect(_ scene: UIScene) { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). + } + + func sceneDidBecomeActive(_ scene: UIScene) { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + } + + func sceneWillResignActive(_ scene: UIScene) { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). + } + + func sceneWillEnterForeground(_ scene: UIScene) { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. + } + + func sceneDidEnterBackground(_ scene: UIScene) { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. + } + + +} + diff --git a/LambdaTimeline.xcodeproj/project.pbxproj b/LambdaTimeline.xcodeproj/project.pbxproj index 95ea1e3d..20f0d028 100644 --- a/LambdaTimeline.xcodeproj/project.pbxproj +++ b/LambdaTimeline.xcodeproj/project.pbxproj @@ -7,6 +7,17 @@ objects = { /* Begin PBXBuildFile section */ + 02C7B57625015DCC00C4A310 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 02C7B57525015DCC00C4A310 /* GoogleService-Info.plist */; }; + 02C7B579250184C400C4A310 /* BlurViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B578250184C300C4A310 /* BlurViewController.swift */; }; + 02C7B57B250184E200C4A310 /* ColorViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B57A250184E200C4A310 /* ColorViewController.swift */; }; + 02C7B57D250184F500C4A310 /* DistortionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B57C250184F500C4A310 /* DistortionViewController.swift */; }; + 02C7B57F2501850200C4A310 /* SharpenViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B57E2501850200C4A310 /* SharpenViewController.swift */; }; + 02C7B5812501850F00C4A310 /* ColorInvertViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B5802501850F00C4A310 /* ColorInvertViewController.swift */; }; + 02C7B5832501857600C4A310 /* UIImage+Scaling.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B5822501857600C4A310 /* UIImage+Scaling.swift */; }; + 02C7B5852501B54600C4A310 /* CIImage+JPEG.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C7B5842501B54600C4A310 /* CIImage+JPEG.swift */; }; + 02F737DC250872C100C0E9AD /* AudioVisualizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02F737DB250872C100C0E9AD /* AudioVisualizer.swift */; }; + 02F737DE2508736500C0E9AD /* AudioViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02F737DD2508736500C0E9AD /* AudioViewController.swift */; }; + 02F737E0250883AD00C0E9AD /* CommentTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02F737DF250883AD00C0E9AD /* CommentTableViewCell.swift */; }; 4646377C216FDE4B00E7FF73 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4646377B216FDE4B00E7FF73 /* AppDelegate.swift */; }; 46463781216FDE4B00E7FF73 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4646377F216FDE4B00E7FF73 /* Main.storyboard */; }; 46463783216FDE4C00E7FF73 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 46463782216FDE4C00E7FF73 /* Assets.xcassets */; }; @@ -33,6 +44,17 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 02C7B57525015DCC00C4A310 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; + 02C7B578250184C300C4A310 /* BlurViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlurViewController.swift; sourceTree = ""; }; + 02C7B57A250184E200C4A310 /* ColorViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorViewController.swift; sourceTree = ""; }; + 02C7B57C250184F500C4A310 /* DistortionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DistortionViewController.swift; sourceTree = ""; }; + 02C7B57E2501850200C4A310 /* SharpenViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharpenViewController.swift; sourceTree = ""; }; + 02C7B5802501850F00C4A310 /* ColorInvertViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorInvertViewController.swift; sourceTree = ""; }; + 02C7B5822501857600C4A310 /* UIImage+Scaling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Scaling.swift"; sourceTree = ""; }; + 02C7B5842501B54600C4A310 /* CIImage+JPEG.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CIImage+JPEG.swift"; sourceTree = ""; }; + 02F737DB250872C100C0E9AD /* AudioVisualizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioVisualizer.swift; sourceTree = ""; }; + 02F737DD2508736500C0E9AD /* AudioViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioViewController.swift; sourceTree = ""; }; + 02F737DF250883AD00C0E9AD /* CommentTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommentTableViewCell.swift; sourceTree = ""; }; 33A2B89DE9E21538434BD640 /* Pods-LambdaTimeline.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-LambdaTimeline.debug.xcconfig"; path = "Pods/Target Support Files/Pods-LambdaTimeline/Pods-LambdaTimeline.debug.xcconfig"; sourceTree = ""; }; 46463778216FDE4B00E7FF73 /* LambdaTimeline.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LambdaTimeline.app; sourceTree = BUILT_PRODUCTS_DIR; }; 4646377B216FDE4B00E7FF73 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -74,6 +96,18 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 02C7B5772501849800C4A310 /* Filter View Controllers */ = { + isa = PBXGroup; + children = ( + 02C7B578250184C300C4A310 /* BlurViewController.swift */, + 02C7B57A250184E200C4A310 /* ColorViewController.swift */, + 02C7B57C250184F500C4A310 /* DistortionViewController.swift */, + 02C7B57E2501850200C4A310 /* SharpenViewController.swift */, + 02C7B5802501850F00C4A310 /* ColorInvertViewController.swift */, + ); + path = "Filter View Controllers"; + sourceTree = ""; + }; 2B7D7DE8669C7C706445FCCC /* Pods */ = { isa = PBXGroup; children = ( @@ -104,6 +138,8 @@ 4646377A216FDE4B00E7FF73 /* LambdaTimeline */ = { isa = PBXGroup; children = ( + 02C7B57525015DCC00C4A310 /* GoogleService-Info.plist */, + 02C7B5772501849800C4A310 /* Filter View Controllers */, 46CFE7042171572900E7FF73 /* Views */, 46A0366B21700F6100E7FF73 /* View Controllers */, 4646379A2170090900E7FF73 /* Model Controllers */, @@ -159,6 +195,7 @@ 46A0366921700F5100E7FF73 /* PostsCollectionViewController.swift */, 46CFE6F421707D0000E7FF73 /* ImagePostViewController.swift */, 46D571F72173FC2700E7FF73 /* ImagePostDetailTableViewController.swift */, + 02F737DD2508736500C0E9AD /* AudioViewController.swift */, ); path = "View Controllers"; sourceTree = ""; @@ -167,6 +204,7 @@ isa = PBXGroup; children = ( 46CFE7022171572600E7FF73 /* ImagePostCollectionViewCell.swift */, + 02F737DF250883AD00C0E9AD /* CommentTableViewCell.swift */, ); path = Views; sourceTree = ""; @@ -189,6 +227,7 @@ 464637982170048900E7FF73 /* FirebaseConvertible.swift */, 46CFE6FC217154F500E7FF73 /* Networking.swift */, 46CFE6F82170862C00E7FF73 /* ShiftableViewController.swift */, + 02F737DB250872C100C0E9AD /* AudioVisualizer.swift */, ); path = Helpers; sourceTree = ""; @@ -199,6 +238,8 @@ 46CFE6F22170757F00E7FF73 /* User+DictionaryRepresentation.swift */, 46D571F42173CF3E00E7FF73 /* UIImage+Ratio.swift */, 46CFE6F621707FA600E7FF73 /* UIViewController+InformationalAlert.swift */, + 02C7B5822501857600C4A310 /* UIImage+Scaling.swift */, + 02C7B5842501B54600C4A310 /* CIImage+JPEG.swift */, ); path = Extensions; sourceTree = ""; @@ -274,6 +315,7 @@ buildActionMask = 2147483647; files = ( 46463786216FDE4C00E7FF73 /* LaunchScreen.storyboard in Resources */, + 02C7B57625015DCC00C4A310 /* GoogleService-Info.plist in Resources */, 46463783216FDE4C00E7FF73 /* Assets.xcassets in Resources */, 46463781216FDE4B00E7FF73 /* Main.storyboard in Resources */, ); @@ -346,23 +388,33 @@ buildActionMask = 2147483647; files = ( 46A0366D2170158900E7FF73 /* SignInViewController.swift in Sources */, + 02C7B5832501857600C4A310 /* UIImage+Scaling.swift in Sources */, 46CFE6FB21714E6100E7FF73 /* Author.swift in Sources */, 46CFE6F92170862C00E7FF73 /* ShiftableViewController.swift in Sources */, + 02C7B579250184C400C4A310 /* BlurViewController.swift in Sources */, + 02F737DE2508736500C0E9AD /* AudioViewController.swift in Sources */, + 02C7B5852501B54600C4A310 /* CIImage+JPEG.swift in Sources */, + 02C7B57B250184E200C4A310 /* ColorViewController.swift in Sources */, 4646377C216FDE4B00E7FF73 /* AppDelegate.swift in Sources */, 46CFE6FD217154F500E7FF73 /* Networking.swift in Sources */, 46CFE6F521707D0000E7FF73 /* ImagePostViewController.swift in Sources */, 46CFE6FF2171556D00E7FF73 /* ConcurrentOperation.swift in Sources */, + 02C7B57D250184F500C4A310 /* DistortionViewController.swift in Sources */, 46463790216FFD1B00E7FF73 /* Post.swift in Sources */, 46CFE6F32170757F00E7FF73 /* User+DictionaryRepresentation.swift in Sources */, + 02C7B57F2501850200C4A310 /* SharpenViewController.swift in Sources */, 46D571F32172D43B00E7FF73 /* Cache.swift in Sources */, 46CFE7012171559500E7FF73 /* FetchMediaOperation.swift in Sources */, 46D571F82173FC2700E7FF73 /* ImagePostDetailTableViewController.swift in Sources */, + 02C7B5812501850F00C4A310 /* ColorInvertViewController.swift in Sources */, + 02F737E0250883AD00C0E9AD /* CommentTableViewCell.swift in Sources */, 46CFE7032171572600E7FF73 /* ImagePostCollectionViewCell.swift in Sources */, 4646379C2170091A00E7FF73 /* PostController.swift in Sources */, 464637992170048900E7FF73 /* FirebaseConvertible.swift in Sources */, 46A0366A21700F5100E7FF73 /* PostsCollectionViewController.swift in Sources */, 46D571F52173CF3E00E7FF73 /* UIImage+Ratio.swift in Sources */, 46463792216FFDD900E7FF73 /* Comment.swift in Sources */, + 02F737DC250872C100C0E9AD /* AudioVisualizer.swift in Sources */, 46CFE6F721707FA600E7FF73 /* UIViewController+InformationalAlert.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -511,13 +563,13 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; + DEVELOPMENT_TEAM = QQ666D93S6; INFOPLIST_FILE = "$(SRCROOT)/LambdaTimeline/Resources/Info.plist"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = ""; + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.timeline; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -530,13 +582,13 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = ""; + DEVELOPMENT_TEAM = QQ666D93S6; INFOPLIST_FILE = "$(SRCROOT)/LambdaTimeline/Resources/Info.plist"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = ""; + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.timeline; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; diff --git a/LambdaTimeline/Filter View Controllers/BlurViewController.swift b/LambdaTimeline/Filter View Controllers/BlurViewController.swift new file mode 100644 index 00000000..4ae74c96 --- /dev/null +++ b/LambdaTimeline/Filter View Controllers/BlurViewController.swift @@ -0,0 +1,117 @@ +// +// BlurViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import CoreImage +import Photos + +class BlurViewController: UIViewController { + + @IBOutlet weak var blurSlider: UISlider! + @IBOutlet weak var imageView: UIImageView! + + private let context = CIContext(options: nil) + let filter = CIFilter(name: "CIGaussianBlur")! + + var originalImagePost: UIImage? + var savedPhoto: UIImage? + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + setUpBlurSlider() + guard let postImage = originalImagePost else { return } + originalImage = postImage + imageView.image = originalImage + } + + @IBAction func saveTapped(_ sender: Any) { + + } + + @IBAction func doneEditing(_ sender: Any) { + + } + + + @IBAction func blurChanged(_ sender: UISlider) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(blurSlider.value, forKey: "inputRadius") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + savedPhoto = UIImage(cgImage: outputCGImage) + return UIImage(cgImage: outputCGImage) + } + + + func setUpBlurSlider() { + if let inputRadiusDictionary = filter.attributes["inputRadius"] as? [String: Any], + let sliderMin = inputRadiusDictionary[kCIAttributeSliderMin] as? Float, + let sliderMax = inputRadiusDictionary[kCIAttributeSliderMax] as? Float, + let identity = inputRadiusDictionary[kCIAttributeIdentity] as? Float { + + blurSlider.minimumValue = sliderMin + blurSlider.maximumValue = sliderMax + blurSlider.value = identity + } + } + + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveBlur" { + if let imageVC = segue.destination as? ImagePostViewController, let photo = savedPhoto { + imageVC.filteredImage = photo + } + } + } + +} + diff --git a/LambdaTimeline/Filter View Controllers/ColorInvertViewController.swift b/LambdaTimeline/Filter View Controllers/ColorInvertViewController.swift new file mode 100644 index 00000000..5ccae1e1 --- /dev/null +++ b/LambdaTimeline/Filter View Controllers/ColorInvertViewController.swift @@ -0,0 +1,113 @@ +// +// ColorInvertViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import CoreImage +import Photos + +class ColorInvertViewController: UIViewController { + @IBOutlet weak var imageView: UIImageView! + private let context = CIContext(options: nil) + var originalImagePost: UIImage? + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + guard let postImage = originalImagePost else { return } + originalImage = postImage + imageView.image = originalImage + } + + @IBAction func saveTapped(_ sender: Any) { + guard let originalImage = originalImage else { return } + + let filteredImage = image(byFiltering: originalImage) + + PHPhotoLibrary.requestAuthorization { (status) in + + guard status == .authorized else { + NSLog("The user has not authorized permission for photo library usage.") + return + + PHPhotoLibrary.shared().performChanges({ + + PHAssetCreationRequest.creationRequestForAsset(from: filteredImage) + + }) { (success, error) in + if let error = error { + NSLog("Error saving photo asset: \(error)") + return + } + + } + } + + } + + + } + @IBAction func invertTapped(_ sender: Any) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let filter = CIFilter(name: "CIColorInvert")! + filter.setValue(ciImage, forKey: "inputImage") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveColorInvert" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} + diff --git a/LambdaTimeline/Filter View Controllers/ColorViewController.swift b/LambdaTimeline/Filter View Controllers/ColorViewController.swift new file mode 100644 index 00000000..6ed1ff1c --- /dev/null +++ b/LambdaTimeline/Filter View Controllers/ColorViewController.swift @@ -0,0 +1,133 @@ +// +// ColorViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import CoreImage +import Photos + +class ColorViewController: UIViewController { + + @IBOutlet weak var brightnessSlider: UISlider! + @IBOutlet weak var contrastSlider: UISlider! + @IBOutlet weak var saturationSlider: UISlider! + @IBOutlet weak var imageView: UIImageView! + + private let context = CIContext(options: nil) + var originalImagePost: UIImage? + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + guard let postImage = originalImagePost else { return } + originalImage = postImage + imageView.image = originalImage + } + + @IBAction func brightnessChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func contrastChanged(_ sender: Any) { + updateImage() + } + + @IBAction func saturationChanged(_ sender: Any) { + updateImage() + } + + + @IBAction func saveTapped(_ sender: Any) { + guard let originalImage = originalImage else { return } + + let filteredImage = image(byFiltering: originalImage) + + PHPhotoLibrary.requestAuthorization { (status) in + + guard status == .authorized else { + NSLog("The user has not authorized permission for photo library usage.") + return + + PHPhotoLibrary.shared().performChanges({ + + PHAssetCreationRequest.creationRequestForAsset(from: filteredImage) + + }) { (success, error) in + if let error = error { + NSLog("Error saving photo asset: \(error)") + return + } + + } + } + + } + + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + + let filter = CIFilter(name: "CIColorControls")! + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(saturationSlider.value, forKey: "inputSaturation") + filter.setValue(brightnessSlider.value, forKey: "inputBrightness") + filter.setValue(contrastSlider.value, forKey: "inputContrast") + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + + + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveColor" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } +} + diff --git a/LambdaTimeline/Filter View Controllers/DistortionViewController.swift b/LambdaTimeline/Filter View Controllers/DistortionViewController.swift new file mode 100644 index 00000000..cf2f2a58 --- /dev/null +++ b/LambdaTimeline/Filter View Controllers/DistortionViewController.swift @@ -0,0 +1,138 @@ +// +// DistortionViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// +import UIKit +import CoreImage +import Photos + +class DistortionViewController: UIViewController { + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var radiusSlider: UISlider! + @IBOutlet weak var angleSlider: UISlider! + @IBOutlet weak var xCenterSlider: UISlider! + @IBOutlet weak var yCenterSlider: UISlider! + + + private let context = CIContext(options: nil) + let filter = CIFilter(name: "CIVortexDistortion")! + var originalImagePost: UIImage? + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + guard let postImage = originalImagePost else { return } + originalImage = postImage + imageView.image = originalImage + } + + @IBAction func saveTapped(_ sender: Any) { + guard let originalImage = originalImage else { return } + + let filteredImage = image(byFiltering: originalImage) + + PHPhotoLibrary.requestAuthorization { (status) in + + guard status == .authorized else { + NSLog("The user has not authorized permission for photo library usage.") + return + + PHPhotoLibrary.shared().performChanges({ + + PHAssetCreationRequest.creationRequestForAsset(from: filteredImage) + + }) { (success, error) in + if let error = error { + NSLog("Error saving photo asset: \(error)") + return + } + + } + } + + } + + + } + + @IBAction func radiusChanged(_ sender: UISlider) { + updateImage() + } + @IBAction func angleChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func xCenterChanged(_ sender: UISlider) { + updateImage() + } + + @IBAction func yCenterChanged(_ sender: UISlider) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let center = CIVector(x: CGFloat(xCenterSlider.value), y: CGFloat(yCenterSlider.value)) + + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(radiusSlider.value, forKey: "inputRadius") + filter.setValue(angleSlider.value, forKey: "inputAngle") + filter.setValue(center, forKey: "inputCenter") + + + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveDistortion" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} diff --git a/LambdaTimeline/Filter View Controllers/SharpenViewController.swift b/LambdaTimeline/Filter View Controllers/SharpenViewController.swift new file mode 100644 index 00000000..df14fbca --- /dev/null +++ b/LambdaTimeline/Filter View Controllers/SharpenViewController.swift @@ -0,0 +1,117 @@ +// +// SharpenViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import CoreImage +import Photos + +class SharpenViewController: UIViewController { + + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var sharpenSlider: UISlider! + + private let context = CIContext(options: nil) + var originalImagePost: UIImage? + + var originalImage: UIImage? { + didSet { + guard let image = originalImage else { return } + + var scaledSize = imageView.bounds.size + let scale = UIScreen.main.scale + + scaledSize = CGSize(width: scaledSize.width * scale, height: scaledSize.height * scale) + + let scaledImage = image.imageByScaling(toSize: scaledSize) + self.scaledImage = scaledImage + } + } + + var scaledImage: UIImage? { + didSet { + imageView.image = scaledImage + } + } + + + override func viewDidLoad() { + super.viewDidLoad() + guard let postImage = originalImagePost else { return } + originalImage = postImage + imageView.image = originalImage + } + + @IBAction func saveTapped(_ sender: Any) { + guard let originalImage = originalImage else { return } + + let filteredImage = image(byFiltering: originalImage) + + PHPhotoLibrary.requestAuthorization { (status) in + + guard status == .authorized else { + NSLog("The user has not authorized permission for photo library usage.") + return + + PHPhotoLibrary.shared().performChanges({ + + PHAssetCreationRequest.creationRequestForAsset(from: filteredImage) + + }) { (success, error) in + if let error = error { + NSLog("Error saving photo asset: \(error)") + return + } + + } + } + + } + + + } + @IBAction func sharpenTapped(_ sender: Any) { + updateImage() + } + + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + private func image(byFiltering image: UIImage) -> UIImage { + + guard let cgImage = image.cgImage else { return image} + + let ciImage = CIImage(cgImage: cgImage) + let filter = CIFilter(name: "CISharpenLuminance")! + filter.setValue(ciImage, forKey: "inputImage") + filter.setValue(sharpenSlider.value, forKey: "inputSharpness") + guard let outputImage = filter.outputImage else { return image } + + guard let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } + + return UIImage(cgImage: outputCGImage) + } + + // MARK: - Navigation + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveSharpen" { + if let imageVC = segue.destination as? ImagePostViewController { + imageVC.filteredImage = imageView.image + } + } + } + +} + + diff --git a/LambdaTimeline/GoogleService-Info.plist b/LambdaTimeline/GoogleService-Info.plist new file mode 100644 index 00000000..884b02df --- /dev/null +++ b/LambdaTimeline/GoogleService-Info.plist @@ -0,0 +1,38 @@ + + + + + CLIENT_ID + 408849830962-1k5k0es64ef2la2sa67att0u07tosd87.apps.googleusercontent.com + NSMicrophoneUsageDescription + $(PRODUCT_NAME) needs access to microphone + REVERSED_CLIENT_ID + com.googleusercontent.apps.408849830962-1k5k0es64ef2la2sa67att0u07tosd87 + API_KEY + AIzaSyBykBDXjQrcDxtFZPQ4RymzQ_Ahx9ag6Es + GCM_SENDER_ID + 408849830962 + PLIST_VERSION + 1 + BUNDLE_ID + com.morgansmith.timeline + PROJECT_ID + morgan-s-timeline + STORAGE_BUCKET + morgan-s-timeline.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:408849830962:ios:c98be8ae0f90273ff3d82b + DATABASE_URL + https://morgan-s-timeline.firebaseio.com + + diff --git a/LambdaTimeline/Helpers/AudioVisualizer.swift b/LambdaTimeline/Helpers/AudioVisualizer.swift new file mode 100644 index 00000000..5d35e0f7 --- /dev/null +++ b/LambdaTimeline/Helpers/AudioVisualizer.swift @@ -0,0 +1,277 @@ +// +// AudioVisualizer.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/8/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit + +@IBDesignable +public class AudioVisualizer: UIView { + + // MARK: IBInspectable Properties + + /// The width of a bar in points. + @IBInspectable public var barWidth: CGFloat = 10 { + didSet { + updateBars() + } + } + + /// The corner radius of a bar in points. If less than `0`, then it will default to half of the width of the bar. + @IBInspectable public var barCornerRadius: CGFloat = -1 { + didSet { + updateBars() + } + } + + /// The spacing between bars in points. + @IBInspectable public var barSpacing: CGFloat = 4 { + didSet { + updateBars() + } + } + + /// The color of a bar. + @IBInspectable public var barColor: UIColor = .systemGray { + didSet { + for bar in bars { + bar.backgroundColor = barColor + } + } + } + + /// The amount of time before a bar decays into the adjacent spot + @IBInspectable public var decaySpeed: Double = 0.01 { + didSet { + decayTimer?.invalidate() + decayTimer = nil + } + } + + /// The fraction the newest value will decay by if not updated by the time a decay starts + @IBInspectable public var decayAmount: Double = 0.8 + + // MARK: Internal Properties + + private var bars = [UIView]() + private var values = [Double]() + + private weak var decayTimer: Timer? + private var newestValue: Double = 0 + + // MARK: - Object Lifecycle + + override init(frame: CGRect) { + super.init(frame: frame) + + initialSetup() + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + + initialSetup() + } + + func initialSetup() { + // Pre-fill values for Interface Builder preview + #if TARGET_INTERFACE_BUILDER + values = [ + 0.19767167952644904, + 0.30975147553721694, + 0.2717680681330001, + 0.25914398105158504, + 0.3413322535900626, + 0.311223010327166, + 0.3302641160440099, + 0.303853272136915, + 0.2659123465612464, + 0.2860924489760262, + 0.26477145407733543, + 0.23180693200970012, + 0.24445487891619533, + 0.21484121767935302, + 0.19688917099112885, + 0.19020094289324854, + 0.17402194532721785, + 0.1600055988294578, + 0.15120753744055154, + 0.13789741397752767, + 0.13231033268544698, + 0.1270923459375989, + 0.1121238175344413, + 0.12400069790665748, + 0.24978783142512598, + 0.233063298365594, + 0.5375441947045457, + 0.47456518731446534, + 0.5236630241490436, + 0.4692151822551929, + 0.4255172022748686, + 0.46023063710569184, + 0.42934908823397355, + 0.37221041959882545, + 0.4685050055667653, + 0.4209394065681193, + 0.46643118034506187, + 0.4292307341708633, + 0.3814422662003417, + 0.4386719969186142, + 0.3956598546828729 + ] + #endif + + // Build the inner bars + self.updateBars() + } + + deinit { + // Invalidate the timer if it is still active + decayTimer?.invalidate() + } + + // MARK: - Layout + override public func layoutSubviews() { + updateBars() + } + + private func updateBars() { + // Clean up old bars + for bar in bars { + bar.removeFromSuperview() + } + + var newBars = [UIView]() + + + // Make sure the width of a bar and spacing is greater than 0, and that the available width is also greater than 0 + guard round(barWidth) > 0, barSpacing >= 0, bounds.width > 0, bounds.height > 0 else { + // Not enough information to create a single bar, so bail early + bars = [] + return + } + + // Calculate number of bars we will be able to display + var numberOfBarsToCreate = Int(bounds.width/(barWidth + barSpacing)) + + // Helper function for creating bars + func createBar(_ positionFromCenter: Int) { + let bar = UIView(frame: frame(forBar: positionFromCenter)) + bar.backgroundColor = barColor + bar.layer.cornerRadius = (barCornerRadius < 0 || barCornerRadius > barWidth/2) ? floor(barWidth/3) : barCornerRadius + + numberOfBarsToCreate -= 1 + newBars.append(bar) + self.addSubview(bar) + } + + // Create the center bar + createBar(0) + + // Keep creating bars in pairs until there is no more room + var position = 1 + while numberOfBarsToCreate > 0 { + // Create the symmetric pairs of bars starting from the center + createBar(-position) + createBar(position) + + position += 1 + } + + bars = newBars + } + + /// Calculate the frame of a particular bar + /// - Parameter positionFromCenter: The distance of the bar from the center (which is 0) + private func frame(forBar positionFromCenter: Int) -> CGRect { + let valueIndex = Int(positionFromCenter.magnitude) + + return frame(forBar: positionFromCenter, value: (valueIndex < values.count) ? values[valueIndex] : 0) + } + + /// Calculate the frame of a particular bar, specifying a value + /// - Parameter positionFromCenter: The distance of the bar from the center (which is 0) + private func frame(forBar positionFromCenter: Int, value: Double) -> CGRect { + let maxValue = (1 - CGFloat(positionFromCenter.magnitude)*(barWidth + barSpacing)/bounds.width/2)*bounds.height/2 + let height = CGFloat(value)*maxValue + + return CGRect(x: floor(bounds.width/2) + CGFloat(positionFromCenter)*(barWidth + barSpacing) - barWidth/2, y: floor(bounds.height/2) - height, width: barWidth, height: height*2) + } + + // MARK: - Animation + + /// Start the decay timer, but only if if hasn't been created yet + private func startTimer() { + guard decayTimer == nil else { return } + + decayTimer = Timer.scheduledTimer(withTimeInterval: decaySpeed, repeats: true) { [weak self] (_) in + guard let self = self else { return } + + self.decayNewestValue() + } + } + + private func decayNewestValue() { + values.insert(newestValue, at: 0) + + // Trim the end of the values array if there are too many for the number of bars + let currentCount = values.count + let maxCount = (bars.count + 1)/2 + /* + Note that the amount of bars will always be either 0, or an odd number (since the bars are counted in pairs after the first central bar), so we chose a "transformation" (a mathematical function) that satisfies this: value index = floor((bar index + 1)/2) + + Bar index: 0 1 2 3 4 5 6 7 8 9 ... + (valid bar index): 0 1 - 3 - 5 - 7 - 9 ... + Value index: 0 1 1 2 2 3 3 4 4 5 ... + + */ + if currentCount > maxCount { + values.removeSubrange(maxCount ..< currentCount) + } + + // Update the frames of each bar + for (positionFromCenter, value) in values.enumerated() { + if positionFromCenter == 0 { + bars[0].frame = frame(forBar: positionFromCenter, value: value) + } else { + bars[positionFromCenter*2 - 1].frame = frame(forBar: -positionFromCenter, value: value) + bars[positionFromCenter*2].frame = frame(forBar: positionFromCenter, value: value) + } + } + + // Decay the newest value + newestValue = newestValue*decayAmount + + // Check if the values are empty + let totalValue = values.reduce(0.0) { $0 + $1 } + if totalValue <= 0.000001 { + // Note that total value may never reach 0, but this is small enough to clear everything out + decayTimer?.invalidate() + decayTimer = nil + } + } + + // MARK: - Public Methods + + /// Add a value to the visualizer. Be sure to call `AVAudioPlayer.isMeteringEnabled = true`, and `AVAudioPlayer.updateMeters()` before every call to `AVAudioPlayer.averagePower(forChannel: 0)` + /// - Parameter decibelValue: The value you would get out of `AVAudioPlayer.averagePower(forChannel: 0)` + public func addValue(decibelValue: Float) { + addValue(decibelValue: Double(decibelValue)) + } + + /// Add a value to the visualizer. Be sure to call `AVAudioPlayer.isMeteringEnabled = true`, and `AVAudioPlayer.updateMeters()` before every call to `AVAudioPlayer.averagePower(forChannel: 0)` + /// - Parameter decibelValue: The value you would get out of `AVAudioPlayer.averagePower(forChannel: 0)` + public func addValue(decibelValue: Double) { + let normalizedValue = __exp10(decibelValue/20) + + newestValue = normalizedValue + + startTimer() + } + +} + + diff --git a/LambdaTimeline/Helpers/Extensions/CIImage+JPEG.swift b/LambdaTimeline/Helpers/Extensions/CIImage+JPEG.swift new file mode 100644 index 00000000..423b71cf --- /dev/null +++ b/LambdaTimeline/Helpers/Extensions/CIImage+JPEG.swift @@ -0,0 +1,44 @@ +// +// CIImage+JPEG.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import CoreImage +import Photos +extension CIImage { + + func saveJPEG(_ name:String, inDirectoryURL:URL? = nil, quality:CGFloat = 1.0) -> String? { + + var destinationURL = inDirectoryURL + + if destinationURL == nil { + destinationURL = try? FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + } + + if var destinationURL = destinationURL { + + destinationURL = destinationURL.appendingPathComponent(name) + + if let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) { + + do { + + let context = CIContext() + + try context.writeJPEGRepresentation(of: self, to: destinationURL, colorSpace: colorSpace, options: [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption : quality]) + + return destinationURL.path + + } catch { + return nil + } + } + } + + return nil + } +} diff --git a/LambdaTimeline/Helpers/Extensions/UIImage+Scaling.swift b/LambdaTimeline/Helpers/Extensions/UIImage+Scaling.swift new file mode 100644 index 00000000..c5f5736f --- /dev/null +++ b/LambdaTimeline/Helpers/Extensions/UIImage+Scaling.swift @@ -0,0 +1,40 @@ +// +// UIImage+Scaling.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit + +extension UIImage { + + /// Resize the image to a max dimension from size parameter + func imageByScaling(toSize size: CGSize) -> UIImage? { + guard size.width > 0 && size.height > 0 else { return nil } + + let originalAspectRatio = self.size.width/self.size.height + var correctedSize = size + + if correctedSize.width > correctedSize.width*originalAspectRatio { + correctedSize.width = correctedSize.width*originalAspectRatio + } else { + correctedSize.height = correctedSize.height/originalAspectRatio + } + + return UIGraphicsImageRenderer(size: correctedSize, format: imageRendererFormat).image { context in + draw(in: CGRect(origin: .zero, size: correctedSize)) + } + } + + /// Renders the image if the pixel data was rotated due to orientation of camera + var flattened: UIImage { + if imageOrientation == .up { return self } + return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { context in + draw(at: .zero) + } + } +} + + diff --git a/LambdaTimeline/Model Controllers/PostController.swift b/LambdaTimeline/Model Controllers/PostController.swift index 29ce3869..d2d28dd6 100644 --- a/LambdaTimeline/Model Controllers/PostController.swift +++ b/LambdaTimeline/Model Controllers/PostController.swift @@ -29,23 +29,34 @@ class PostController { NSLog("Error posting image post: \(error)") completion(false) } - + completion(true) } } } - func addComment(with text: String, to post: inout Post) { + func addTextComment(with text: String, to post: inout Post) { guard let currentUser = Auth.auth().currentUser, let author = Author(user: currentUser) else { return } - let comment = Comment(text: text, author: author) + let comment = Comment(text: text, audio: nil, author: author) post.comments.append(comment) savePostToFirebase(post) } + func addAudioComment(with url: URL, to post: inout Post) { + + guard let currentUser = Auth.auth().currentUser, + let author = Author(user: currentUser) else { return } + let comment = Comment(text: "Audio Comment", audio: url, author: author) + post.comments.append(comment) + savePostToFirebase(post) + } + + + func observePosts(completion: @escaping (Error?) -> Void) { postsRef.observe(.value, with: { (snapshot) in diff --git a/LambdaTimeline/Models/Comment.swift b/LambdaTimeline/Models/Comment.swift index a71ffe4d..c86934d9 100644 --- a/LambdaTimeline/Models/Comment.swift +++ b/LambdaTimeline/Models/Comment.swift @@ -12,32 +12,36 @@ import FirebaseAuth class Comment: FirebaseConvertible, Equatable { static private let textKey = "text" + static private let audioKey = "audio" static private let author = "author" static private let timestampKey = "timestamp" - let text: String + let text: String? + let audio: URL? let author: Author let timestamp: Date - init(text: String, author: Author, timestamp: Date = Date()) { + init(text: String, audio: URL? = nil, author: Author, timestamp: Date = Date()) { self.text = text + self.audio = audio self.author = author self.timestamp = timestamp } init?(dictionary: [String : Any]) { - guard let text = dictionary[Comment.textKey] as? String, + guard let text = dictionary[Comment.textKey] as? String, let audioString = dictionary[Comment.audioKey] as? String, let audio = URL(string: audioString), let authorDictionary = dictionary[Comment.author] as? [String: Any], let author = Author(dictionary: authorDictionary), let timestampTimeInterval = dictionary[Comment.timestampKey] as? TimeInterval else { return nil } - self.text = text + self.audio = audio self.author = author self.timestamp = Date(timeIntervalSince1970: timestampTimeInterval) } var dictionaryRepresentation: [String: Any] { return [Comment.textKey: text, + Comment.audioKey: audio?.absoluteString ?? "No Audio", Comment.author: author.dictionaryRepresentation, Comment.timestampKey: timestamp.timeIntervalSince1970] } diff --git a/LambdaTimeline/Models/Post.swift b/LambdaTimeline/Models/Post.swift index ec961e9f..fc9f9fa0 100644 --- a/LambdaTimeline/Models/Post.swift +++ b/LambdaTimeline/Models/Post.swift @@ -11,6 +11,7 @@ import FirebaseAuth enum MediaType: String { case image + case audio } class Post { @@ -68,7 +69,7 @@ class Post { var title: String? { return comments.first?.text } - + static private let mediaKey = "media" static private let ratioKey = "ratio" static private let mediaTypeKey = "mediaType" diff --git a/LambdaTimeline/Resources/Info.plist b/LambdaTimeline/Resources/Info.plist index dab10c0a..fae134ee 100644 --- a/LambdaTimeline/Resources/Info.plist +++ b/LambdaTimeline/Resources/Info.plist @@ -4,6 +4,8 @@ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) + NSMicrophoneUsageDescription + $(PRODUCT_NAME) needs access to use microphone CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -23,7 +25,7 @@ Editor CFBundleURLSchemes - Copy-paste-your-REVERSED_CLIENT_ID-from-GoogleService-Info.plist + com.googleusercontent.apps.408849830962-1k5k0es64ef2la2sa67att0u07tosd87 @@ -33,6 +35,8 @@ NSPhotoLibraryUsageDescription In order to allow you to add photos to posts + NSPhotoLibraryAddUsageDescription + in order to edit photots that you post UILaunchStoryboardName LaunchScreen UIMainStoryboardFile diff --git a/LambdaTimeline/Storyboards/Base.lproj/Main.storyboard b/LambdaTimeline/Storyboards/Base.lproj/Main.storyboard index fcec352d..b1e5fa14 100644 --- a/LambdaTimeline/Storyboards/Base.lproj/Main.storyboard +++ b/LambdaTimeline/Storyboards/Base.lproj/Main.storyboard @@ -1,10 +1,11 @@ - + - + + @@ -111,16 +112,16 @@ - + - + - + @@ -150,8 +151,17 @@ + - + @@ -187,6 +197,7 @@ + @@ -255,7 +266,7 @@ - + @@ -305,29 +316,69 @@ - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -347,11 +398,673 @@ + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LambdaTimeline/View Controllers/AudioViewController.swift b/LambdaTimeline/View Controllers/AudioViewController.swift new file mode 100644 index 00000000..7cee25f9 --- /dev/null +++ b/LambdaTimeline/View Controllers/AudioViewController.swift @@ -0,0 +1,326 @@ +// +// AudioViewController.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/8/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import AVFoundation + +class AudioViewController: UIViewController { + + var audioPlayer: AVAudioPlayer? { + didSet { + guard let audioPlayer = audioPlayer else { + return + } + audioPlayer.delegate = self + audioPlayer.isMeteringEnabled = true + updateViews() + } + } + + weak var timer: Timer? + + var recordingURL: URL? + var savedRecording: URL? + + var post: Post! + var postController: PostController! + + var audioRecorder: AVAudioRecorder? + + @IBOutlet var playButton: UIButton! + @IBOutlet var recordButton: UIButton! + @IBOutlet var timeElapsedLabel: UILabel! + @IBOutlet var timeRemainingLabel: UILabel! + @IBOutlet var timeSlider: UISlider! + @IBOutlet var audioVisualizer: AudioVisualizer! + + private lazy var timeIntervalFormatter: DateComponentsFormatter = { + + let formatting = DateComponentsFormatter() + formatting.unitsStyle = .positional // 00:00 mm:ss + formatting.zeroFormattingBehavior = .pad + formatting.allowedUnits = [.minute, .second] + return formatting + }() + + + // MARK: - View Controller Lifecycle + + override func viewDidLoad() { + super.viewDidLoad() + + timeElapsedLabel.font = UIFont.monospacedDigitSystemFont(ofSize: timeElapsedLabel.font.pointSize, + weight: .regular) + timeRemainingLabel.font = UIFont.monospacedDigitSystemFont(ofSize: timeRemainingLabel.font.pointSize, + weight: .regular) + + loadAudio() + updateViews() + } + func updateViews() { + playButton.isEnabled = !isRecording + recordButton.isEnabled = !isPlaying + timeSlider.isEnabled = !isRecording + playButton.isSelected = isPlaying + recordButton.isSelected = isRecording + if !isRecording { + let elapsedTime = audioPlayer?.currentTime ?? 0 + let duration = audioPlayer?.duration ?? 0 + let timeRemaining = duration.rounded() - elapsedTime + timeElapsedLabel.text = timeIntervalFormatter.string(from: elapsedTime) + timeSlider.minimumValue = 0 + timeSlider.maximumValue = Float(duration) + timeSlider.value = Float(elapsedTime) + timeRemainingLabel.text = "-" + timeIntervalFormatter.string(from: timeRemaining)! + } else { + let elapsedTime = audioRecorder?.currentTime ?? 0 + timeElapsedLabel.text = "--:--" + timeSlider.minimumValue = 0 + timeSlider.maximumValue = 1 + timeSlider.value = 0 + timeRemainingLabel.text = timeIntervalFormatter.string(from: elapsedTime) + } + } + + + deinit { + timer?.invalidate() + } + + + // MARK: - Timer + + + func startTimer() { + timer?.invalidate() + + timer = Timer.scheduledTimer(withTimeInterval: 0.030, repeats: true) { [weak self] (_) in + + guard let self = self else { return } + + self.updateViews() + + if let audioRecorder = self.audioRecorder, + self.isRecording == true { + + audioRecorder.updateMeters() + self.audioVisualizer.addValue(decibelValue: audioRecorder.averagePower(forChannel: 0)) + + } + + if let audioPlayer = self.audioPlayer, + self.isPlaying == true { + + audioPlayer.updateMeters() + self.audioVisualizer.addValue(decibelValue: audioPlayer.averagePower(forChannel: 0)) + } + } + } + + func cancelTimer() { + timer?.invalidate() + timer = nil + } + + + + // MARK: - Playback + + var isPlaying: Bool { + audioPlayer?.isPlaying ?? false + } + + func loadAudio() { + guard let songURL = recordingURL else { return } + + do { + audioPlayer = try AVAudioPlayer(contentsOf: songURL) + } catch { + preconditionFailure("Failure to load audio file: \(error)") + } + } + + + func prepareAudioSession() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playAndRecord, options: [.defaultToSpeaker]) + try session.setActive(true, options: []) // can fail if on a phone call, for instance + } + + + func play() { + do { + try prepareAudioSession() + audioPlayer?.play() + updateViews() + startTimer() + } catch { + print("Cannot play audio: \(error)") + } + + + } + + func pause() { + audioPlayer?.pause() + updateViews() + cancelTimer() + } + + + // MARK: - Recording + + var isRecording: Bool { + audioRecorder?.isRecording ?? false + } + + func createNewRecordingURL() -> URL { + let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! + + let name = ISO8601DateFormatter.string(from: Date(), timeZone: .current, formatOptions: .withInternetDateTime) + let file = documents.appendingPathComponent(name, isDirectory: false).appendingPathExtension("caf") + + print("recording URL: \(file)") + return file + } + + + func requestPermissionOrStartRecording() { + switch AVAudioSession.sharedInstance().recordPermission { + case .undetermined: + AVAudioSession.sharedInstance().requestRecordPermission { granted in + guard granted == true else { + print("We need microphone access") + return + } + + print("Recording permission has been granted!") + // NOTE: Invite the user to tap record again, since we just interrupted them, and they may not have been ready to record + } + case .denied: + print("Microphone access has been blocked.") + + let alertController = UIAlertController(title: "Microphone Access Denied", message: "Please allow this app to access your Microphone.", preferredStyle: .alert) + + alertController.addAction(UIAlertAction(title: "Open Settings", style: .default) { (_) in + UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) + }) + + alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) + + present(alertController, animated: true, completion: nil) + case .granted: + startRecording() + @unknown default: + break + } + } + + + func startRecording() { + do { + try prepareAudioSession() + } catch { + print("Cannot record audio: \(error)") + return + } + + recordingURL = createNewRecordingURL() + + //can return option because you can give it invalid format and combinations + // let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)! + let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44_100, channels: 1, interleaved: false)! + + do { + audioRecorder = try AVAudioRecorder(url: recordingURL!, format: format) + audioRecorder?.delegate = self + audioRecorder?.isMeteringEnabled = true + audioRecorder?.record() + updateViews() + startTimer() + } catch { + preconditionFailure("The audio recorder could not be created with \(recordingURL!) and \(format)") + } + + } + + func stopRecording() { + audioRecorder?.stop() + updateViews() + cancelTimer() + } + + // MARK: - Actions + + @IBAction func togglePlayback(_ sender: Any) { + if isPlaying { + pause() + } else { + play() + } + + } + + @IBAction func updateCurrentTime(_ sender: UISlider) { + if isPlaying { + pause() + } + audioPlayer?.currentTime = TimeInterval(sender.value) + updateViews() + } + + @IBAction func toggleRecording(_ sender: Any) { + if isRecording { + stopRecording() + } else { + requestPermissionOrStartRecording() + } + } + + @IBAction func saveRecording(_ sender: Any) { + if let savedRecording = savedRecording { + postController.addAudioComment(with: savedRecording, to: &self.post) + } else { + print("adioCommentNotSaved)") + } + DispatchQueue.main.async { + self.navigationController?.popViewController(animated: true) + } + } + } + + extension AudioViewController: AVAudioPlayerDelegate { + + func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { + updateViews() + cancelTimer() + } + + func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { + if let error = error { + print("Audio Player Error: \(error)") + } + } + } + + extension AudioViewController: AVAudioRecorderDelegate { + func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { + if let recordingURL = recordingURL { + audioPlayer = try? AVAudioPlayer(contentsOf: recordingURL) + savedRecording = recordingURL + } + recordingURL = nil + + } + func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { + if let error = error { + print("Audio Recorder Error: \(error)") + } + } + +} diff --git a/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift b/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift index 31b43fa3..9f7f2595 100644 --- a/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift +++ b/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift @@ -13,7 +13,10 @@ class ImagePostDetailTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() updateViews() + self.tableView.dataSource = self + self.tableView.delegate = self } + func updateViews() { @@ -24,7 +27,7 @@ class ImagePostDetailTableViewController: UITableViewController { imageView.image = image - titleLabel.text = post.title + titleLabel.text = post?.title authorLabel.text = post.author.displayName } @@ -32,32 +35,57 @@ class ImagePostDetailTableViewController: UITableViewController { @IBAction func createComment(_ sender: Any) { - let alert = UIAlertController(title: "Add a comment", message: "Write your comment below:", preferredStyle: .alert) + let alert = UIAlertController(title: "Add a comment", message: "Choose text or audio", preferredStyle: .alert) - var commentTextField: UITextField? + + + let addCommentAction = UIAlertAction(title: "Add Text", style: .default) { (_) in + self.createTextComment() + } + + let addAudioAction = UIAlertAction(title: "Add Audio", style: .default) { (_) in + DispatchQueue.main.async { + self.performSegue(withIdentifier: "addAudioComment", sender: self) + } + } + + let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) + + alert.addAction(addCommentAction) + alert.addAction(addAudioAction) + alert.addAction(cancelAction) + present(alert, animated: true, completion: nil) + } + + func createTextComment() { + let alert = UIAlertController(title: "Add a comment", message: "Write your comment below:", preferredStyle: .alert) + + var commentTextField: UITextField? + alert.addTextField { (textField) in textField.placeholder = "Comment:" commentTextField = textField } - + let addCommentAction = UIAlertAction(title: "Add Comment", style: .default) { (_) in - + guard let commentText = commentTextField?.text else { return } - - self.postController.addComment(with: commentText, to: &self.post!) - + + self.postController.addTextComment(with: commentText, to: &self.post!) + DispatchQueue.main.async { self.tableView.reloadData() } } - + let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) - + alert.addAction(addCommentAction) alert.addAction(cancelAction) - + present(alert, animated: true, completion: nil) + } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -65,13 +93,11 @@ class ImagePostDetailTableViewController: UITableViewController { } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) - - let comment = post?.comments[indexPath.row + 1] - - cell.textLabel?.text = comment?.text - cell.detailTextLabel?.text = comment?.author.displayName - + + guard let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as? CommentTableViewCell else { return UITableViewCell() } + + guard let comment = post?.comments[indexPath.row + 1] else { return UITableViewCell() } + cell.comment = comment return cell } @@ -85,4 +111,14 @@ class ImagePostDetailTableViewController: UITableViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var imageViewAspectRatioConstraint: NSLayoutConstraint! + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "addAudioComment" { + + let destinationVC = segue.destination as? AudioViewController + + destinationVC?.postController = postController + destinationVC?.post = post + } + } } diff --git a/LambdaTimeline/View Controllers/ImagePostViewController.swift b/LambdaTimeline/View Controllers/ImagePostViewController.swift index 93c4b93e..0e10403e 100644 --- a/LambdaTimeline/View Controllers/ImagePostViewController.swift +++ b/LambdaTimeline/View Controllers/ImagePostViewController.swift @@ -7,23 +7,52 @@ // import UIKit +import CoreImage import Photos + class ImagePostViewController: ShiftableViewController { + @IBOutlet weak var editPhoto: UIButton! + @IBOutlet weak var imageView: UIImageView! + @IBOutlet weak var titleTextField: UITextField! + @IBOutlet weak var chooseImageButton: UIButton! + @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint! + @IBOutlet weak var postButton: UIBarButtonItem! + + var postController: PostController! + var post: Post? + var imageData: Data? + var filteredImage: UIImage? + var originalImagePost: UIImage? { + didSet { + print("set the original image in postController") + viewDidLoad() + } + } + override func viewDidLoad() { super.viewDidLoad() - - setImageViewHeight(with: 1.0) - - updateViews() + if let filteredImage = filteredImage { + setImageViewHeight(with: filteredImage.ratio) + imageView.image = filteredImage + editPhoto.setTitle("Edit Photo", for: .normal) + editPhoto.setTitleColor(.systemBlue, for: .normal) + title = "New Post" + chooseImageButton.setTitle("", for: []) + } else { + setImageViewHeight(with: 1.0) + updateViews() + } } func updateViews() { + editPhoto.setTitle("Edit Photo", for: .normal) guard let imageData = imageData, let image = UIImage(data: imageData) else { title = "New Post" + editPhoto.setTitleColor(.white, for: .normal) return } @@ -33,6 +62,8 @@ class ImagePostViewController: ShiftableViewController { imageView.image = image + editPhoto.setTitleColor(.systemBlue, for: .normal) + chooseImageButton.setTitle("", for: []) } @@ -42,14 +73,15 @@ class ImagePostViewController: ShiftableViewController { presentInformationalAlertController(title: "Error", message: "The photo library is unavailable") return } - - let imagePicker = UIImagePickerController() - - imagePicker.delegate = self - - imagePicker.sourceType = .photoLibrary - - present(imagePicker, animated: true, completion: nil) + DispatchQueue.main.async { + let imagePicker = UIImagePickerController() + + imagePicker.delegate = self + + imagePicker.sourceType = .photoLibrary + + self.present(imagePicker, animated: true, completion: nil) + } } @IBAction func createPost(_ sender: Any) { @@ -57,12 +89,12 @@ class ImagePostViewController: ShiftableViewController { view.endEditing(true) guard let imageData = imageView.image?.jpegData(compressionQuality: 0.1), - let title = titleTextField.text, title != "" else { - presentInformationalAlertController(title: "Uh-oh", message: "Make sure that you add a photo and a caption before posting.") - return + let title = titleTextField.text, title != "", let ratio = imageView.image?.ratio else { + presentInformationalAlertController(title: "Uh-oh", message: "Make sure that you add a photo and a caption before posting.") + return } - postController.createPost(with: title, ofType: .image, mediaData: imageData, ratio: imageView.image?.ratio) { (success) in + postController.createPost(with: title, ofType: .image, mediaData: imageData, ratio: ratio) { (success) in guard success else { DispatchQueue.main.async { self.presentInformationalAlertController(title: "Error", message: "Unable to create post. Try again.") @@ -105,8 +137,13 @@ class ImagePostViewController: ShiftableViewController { print("FatalError") } presentImagePickerController() + } + @IBAction func editPhoto(_ sender: Any) { + } + + func setImageViewHeight(with aspectRatio: CGFloat) { imageHeightConstraint.constant = imageView.frame.size.width * aspectRatio @@ -114,21 +151,33 @@ class ImagePostViewController: ShiftableViewController { view.layoutSubviews() } - var postController: PostController! - var post: Post? - var imageData: Data? + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "editPhotoSegue" { + if let tabController = segue.destination as? UITabBarController { + let blurController = tabController.children.first(where: { $0 is BlurViewController }) + (blurController as? BlurViewController)?.originalImagePost = self.originalImagePost + + let colorController = tabController.children.first(where: { $0 is ColorViewController }) + (colorController as? ColorViewController)?.originalImagePost = self.originalImagePost + + let distortionController = tabController.children.first(where: { $0 is DistortionViewController }) + (distortionController as? DistortionViewController)?.originalImagePost = self.originalImagePost + let sharpenController = tabController.children.first(where: { $0 is SharpenViewController }) + (sharpenController as? SharpenViewController)?.originalImagePost = self.originalImagePost + let colorInvertController = tabController.children.first(where: { $0 is ColorInvertViewController }) + (colorInvertController as? ColorInvertViewController)?.originalImagePost = self.originalImagePost + + } + } + } + - @IBOutlet weak var imageView: UIImageView! - @IBOutlet weak var titleTextField: UITextField! - @IBOutlet weak var chooseImageButton: UIButton! - @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint! - @IBOutlet weak var postButton: UIBarButtonItem! } extension ImagePostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { - + chooseImageButton.setTitle("", for: []) picker.dismiss(animated: true, completion: nil) @@ -136,8 +185,12 @@ extension ImagePostViewController: UIImagePickerControllerDelegate, UINavigation guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } imageView.image = image + originalImagePost = image setImageViewHeight(with: image.ratio) + + editPhoto.setTitleColor(.systemBlue, for: .normal) + } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { diff --git a/LambdaTimeline/Views/CommentTableViewCell.swift b/LambdaTimeline/Views/CommentTableViewCell.swift new file mode 100644 index 00000000..86ddc09f --- /dev/null +++ b/LambdaTimeline/Views/CommentTableViewCell.swift @@ -0,0 +1,121 @@ +// +// CommentTableViewCell.swift +// LambdaTimeline +// +// Created by Morgan Smith on 9/8/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import AVFoundation + +class CommentTableViewCell: UITableViewCell { + + @IBOutlet weak var playButton: UIButton! + @IBOutlet weak var commentText: UILabel! + + @IBOutlet weak var authorLabel: UILabel! + + var comment: Comment? { + didSet { + updateViews() + } + } + + var audioPlayer: AVAudioPlayer? { + didSet { + guard let audioPlayer = audioPlayer else { + return + } + audioPlayer.delegate = self + togglePlaying() + } + } + + func updateViews() { + guard let comment = comment else { return } + if comment.text != "Audio Comment" { + playButton.adjustsImageWhenDisabled = true + playButton.backgroundImage(for: .disabled) + commentText.text = comment.text + authorLabel.text = comment.author.displayName + + } else { + playButton.backgroundImage(for: .normal) + loadAudio() + togglePlaying() + commentText.text = "Audio Comment" + authorLabel.text = comment.author.displayName + } + } + + func togglePlaying() { + playButton.isSelected = isPlaying + } + + var isPlaying: Bool { + audioPlayer?.isPlaying ?? false + } + + func loadAudio() { + guard let comment = comment else { return } + if comment.audio?.absoluteString == "No Audio", comment.audio == nil { + return + } else { + guard let songURL = comment.audio else { return } + do { + audioPlayer = try AVAudioPlayer(contentsOf: songURL) + } catch { + preconditionFailure("Failure to load audio file: \(error)") + } + } + } + + func prepareAudioSession() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playAndRecord, options: [.defaultToSpeaker]) + try session.setActive(true, options: []) // can fail if on a phone call, for instance + } + + func play() { + do { + try prepareAudioSession() + audioPlayer?.play() + togglePlaying() + } catch { + print("Cannot play audio: \(error)") + } + + + } + + func pause() { + audioPlayer?.pause() + togglePlaying() + } + + @IBAction func togglePlayback(_ sender: UIButton) { + if isPlaying { + pause() + } else { + play() + } + } + + + +} + +extension CommentTableViewCell: AVAudioPlayerDelegate { + + func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { + togglePlaying() + } + + func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { + if let error = error { + print("Audio Player Error: \(error)") + } + } +} + diff --git a/LambdaTimeline/Views/ImagePostCollectionViewCell.swift b/LambdaTimeline/Views/ImagePostCollectionViewCell.swift index 3841cf65..88cdd3b7 100644 --- a/LambdaTimeline/Views/ImagePostCollectionViewCell.swift +++ b/LambdaTimeline/Views/ImagePostCollectionViewCell.swift @@ -25,7 +25,7 @@ class ImagePostCollectionViewCell: UICollectionViewCell { func updateViews() { guard let post = post else { return } - titleLabel.text = post.title + titleLabel.text = post.comments.first?.text authorLabel.text = post.author.displayName } diff --git a/Podfile.lock b/Podfile.lock index 9d835784..244d90e4 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -171,4 +171,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 28424f1a99ace6e65529f57867177322416678fa -COCOAPODS: 1.9.1 +COCOAPODS: 1.9.3 diff --git a/audioComments/audioComments.xcodeproj/project.pbxproj b/audioComments/audioComments.xcodeproj/project.pbxproj new file mode 100644 index 00000000..ea0fa0cf --- /dev/null +++ b/audioComments/audioComments.xcodeproj/project.pbxproj @@ -0,0 +1,359 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 02DBEB542507093800EDFB45 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB532507093800EDFB45 /* AppDelegate.swift */; }; + 02DBEB562507093800EDFB45 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB552507093800EDFB45 /* SceneDelegate.swift */; }; + 02DBEB5B2507093800EDFB45 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 02DBEB592507093800EDFB45 /* Main.storyboard */; }; + 02DBEB5D2507093D00EDFB45 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 02DBEB5C2507093D00EDFB45 /* Assets.xcassets */; }; + 02DBEB602507093D00EDFB45 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 02DBEB5E2507093D00EDFB45 /* LaunchScreen.storyboard */; }; + 02DBEB68250709C100EDFB45 /* AudioVisualizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB67250709C100EDFB45 /* AudioVisualizer.swift */; }; + 02DBEB6A250709DD00EDFB45 /* AudioRecorderViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB69250709DD00EDFB45 /* AudioRecorderViewController.swift */; }; + 02DBEB6C25070FBA00EDFB45 /* piano.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 02DBEB6B25070FBA00EDFB45 /* piano.mp3 */; }; + 02DBEB6E25083B8300EDFB45 /* RecordedCommentTableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB6D25083B8300EDFB45 /* RecordedCommentTableViewController.swift */; }; + 02DBEB7025083B9900EDFB45 /* RecordedCommentTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02DBEB6F25083B9900EDFB45 /* RecordedCommentTableViewCell.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 02DBEB502507093800EDFB45 /* audioComments.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = audioComments.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 02DBEB532507093800EDFB45 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 02DBEB552507093800EDFB45 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 02DBEB5A2507093800EDFB45 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 02DBEB5C2507093D00EDFB45 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 02DBEB5F2507093D00EDFB45 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 02DBEB612507093D00EDFB45 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 02DBEB67250709C100EDFB45 /* AudioVisualizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioVisualizer.swift; sourceTree = ""; }; + 02DBEB69250709DD00EDFB45 /* AudioRecorderViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioRecorderViewController.swift; sourceTree = ""; }; + 02DBEB6B25070FBA00EDFB45 /* piano.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = piano.mp3; sourceTree = ""; }; + 02DBEB6D25083B8300EDFB45 /* RecordedCommentTableViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordedCommentTableViewController.swift; sourceTree = ""; }; + 02DBEB6F25083B9900EDFB45 /* RecordedCommentTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordedCommentTableViewCell.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 02DBEB4D2507093800EDFB45 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02DBEB472507093800EDFB45 = { + isa = PBXGroup; + children = ( + 02DBEB522507093800EDFB45 /* audioComments */, + 02DBEB512507093800EDFB45 /* Products */, + ); + sourceTree = ""; + }; + 02DBEB512507093800EDFB45 /* Products */ = { + isa = PBXGroup; + children = ( + 02DBEB502507093800EDFB45 /* audioComments.app */, + ); + name = Products; + sourceTree = ""; + }; + 02DBEB522507093800EDFB45 /* audioComments */ = { + isa = PBXGroup; + children = ( + 02DBEB6B25070FBA00EDFB45 /* piano.mp3 */, + 02DBEB532507093800EDFB45 /* AppDelegate.swift */, + 02DBEB552507093800EDFB45 /* SceneDelegate.swift */, + 02DBEB592507093800EDFB45 /* Main.storyboard */, + 02DBEB5C2507093D00EDFB45 /* Assets.xcassets */, + 02DBEB5E2507093D00EDFB45 /* LaunchScreen.storyboard */, + 02DBEB612507093D00EDFB45 /* Info.plist */, + 02DBEB67250709C100EDFB45 /* AudioVisualizer.swift */, + 02DBEB69250709DD00EDFB45 /* AudioRecorderViewController.swift */, + 02DBEB6D25083B8300EDFB45 /* RecordedCommentTableViewController.swift */, + 02DBEB6F25083B9900EDFB45 /* RecordedCommentTableViewCell.swift */, + ); + path = audioComments; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 02DBEB4F2507093800EDFB45 /* audioComments */ = { + isa = PBXNativeTarget; + buildConfigurationList = 02DBEB642507093D00EDFB45 /* Build configuration list for PBXNativeTarget "audioComments" */; + buildPhases = ( + 02DBEB4C2507093800EDFB45 /* Sources */, + 02DBEB4D2507093800EDFB45 /* Frameworks */, + 02DBEB4E2507093800EDFB45 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = audioComments; + productName = audioComments; + productReference = 02DBEB502507093800EDFB45 /* audioComments.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 02DBEB482507093800EDFB45 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1150; + LastUpgradeCheck = 1150; + ORGANIZATIONNAME = "Morgan Smith"; + TargetAttributes = { + 02DBEB4F2507093800EDFB45 = { + CreatedOnToolsVersion = 11.5; + }; + }; + }; + buildConfigurationList = 02DBEB4B2507093800EDFB45 /* Build configuration list for PBXProject "audioComments" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 02DBEB472507093800EDFB45; + productRefGroup = 02DBEB512507093800EDFB45 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 02DBEB4F2507093800EDFB45 /* audioComments */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 02DBEB4E2507093800EDFB45 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 02DBEB602507093D00EDFB45 /* LaunchScreen.storyboard in Resources */, + 02DBEB5D2507093D00EDFB45 /* Assets.xcassets in Resources */, + 02DBEB6C25070FBA00EDFB45 /* piano.mp3 in Resources */, + 02DBEB5B2507093800EDFB45 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 02DBEB4C2507093800EDFB45 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 02DBEB6E25083B8300EDFB45 /* RecordedCommentTableViewController.swift in Sources */, + 02DBEB542507093800EDFB45 /* AppDelegate.swift in Sources */, + 02DBEB6A250709DD00EDFB45 /* AudioRecorderViewController.swift in Sources */, + 02DBEB7025083B9900EDFB45 /* RecordedCommentTableViewCell.swift in Sources */, + 02DBEB68250709C100EDFB45 /* AudioVisualizer.swift in Sources */, + 02DBEB562507093800EDFB45 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 02DBEB592507093800EDFB45 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 02DBEB5A2507093800EDFB45 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 02DBEB5E2507093D00EDFB45 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 02DBEB5F2507093D00EDFB45 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 02DBEB622507093D00EDFB45 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.5; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 02DBEB632507093D00EDFB45 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.5; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 02DBEB652507093D00EDFB45 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = QQ666D93S6; + INFOPLIST_FILE = audioComments/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.audioComments; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 02DBEB662507093D00EDFB45 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = QQ666D93S6; + INFOPLIST_FILE = audioComments/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.morgansmith.audioComments; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 02DBEB4B2507093800EDFB45 /* Build configuration list for PBXProject "audioComments" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 02DBEB622507093D00EDFB45 /* Debug */, + 02DBEB632507093D00EDFB45 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 02DBEB642507093D00EDFB45 /* Build configuration list for PBXNativeTarget "audioComments" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 02DBEB652507093D00EDFB45 /* Debug */, + 02DBEB662507093D00EDFB45 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 02DBEB482507093800EDFB45 /* Project object */; +} diff --git a/audioComments/audioComments/AppDelegate.swift b/audioComments/audioComments/AppDelegate.swift new file mode 100644 index 00000000..94384d88 --- /dev/null +++ b/audioComments/audioComments/AppDelegate.swift @@ -0,0 +1,37 @@ +// +// AppDelegate.swift +// audioComments +// +// Created by Morgan Smith on 9/7/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + // MARK: UISceneSession Lifecycle + + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + } + + +} + diff --git a/audioComments/audioComments/Assets.xcassets/AppIcon.appiconset/Contents.json b/audioComments/audioComments/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..9221b9bb --- /dev/null +++ b/audioComments/audioComments/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/audioComments/audioComments/Assets.xcassets/Contents.json b/audioComments/audioComments/Assets.xcassets/Contents.json new file mode 100644 index 00000000..73c00596 --- /dev/null +++ b/audioComments/audioComments/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/audioComments/audioComments/AudioRecorderViewController.swift b/audioComments/audioComments/AudioRecorderViewController.swift new file mode 100644 index 00000000..93b477d5 --- /dev/null +++ b/audioComments/audioComments/AudioRecorderViewController.swift @@ -0,0 +1,332 @@ +// +// AudioRecorderViewController.swift +// audioComments +// +// Created by Morgan Smith on 9/7/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import AVFoundation + +class AudioRecorderController: UIViewController { + + var audioPlayer: AVAudioPlayer? { + didSet { + guard let audioPlayer = audioPlayer else { + return + } + audioPlayer.delegate = self + audioPlayer.isMeteringEnabled = true + updateViews() + } + } + + weak var timer: Timer? + + var recordingURL: URL? + var savedRecording: URL? + + var audioRecorder: AVAudioRecorder? + + @IBOutlet var playButton: UIButton! + @IBOutlet var recordButton: UIButton! + @IBOutlet var timeElapsedLabel: UILabel! + @IBOutlet var timeRemainingLabel: UILabel! + @IBOutlet var timeSlider: UISlider! + @IBOutlet var audioVisualizer: AudioVisualizer! + + private lazy var timeIntervalFormatter: DateComponentsFormatter = { + // NOTE: DateComponentFormatter is good for minutes/hours/seconds + // DateComponentsFormatter is not good for milliseconds, use DateFormatter instead) + + let formatting = DateComponentsFormatter() + formatting.unitsStyle = .positional // 00:00 mm:ss + formatting.zeroFormattingBehavior = .pad + formatting.allowedUnits = [.minute, .second] + return formatting + }() + + + // MARK: - View Controller Lifecycle + + override func viewDidLoad() { + super.viewDidLoad() + + // Use a font that won't jump around as values change + timeElapsedLabel.font = UIFont.monospacedDigitSystemFont(ofSize: timeElapsedLabel.font.pointSize, + weight: .regular) + timeRemainingLabel.font = UIFont.monospacedDigitSystemFont(ofSize: timeRemainingLabel.font.pointSize, + weight: .regular) + + loadAudio() + updateViews() + } + func updateViews() { + playButton.isEnabled = !isRecording + recordButton.isEnabled = !isPlaying + timeSlider.isEnabled = !isRecording + playButton.isSelected = isPlaying + recordButton.isSelected = isRecording + if !isRecording { + let elapsedTime = audioPlayer?.currentTime ?? 0 + let duration = audioPlayer?.duration ?? 0 + let timeRemaining = duration.rounded() - elapsedTime + timeElapsedLabel.text = timeIntervalFormatter.string(from: elapsedTime) + timeSlider.minimumValue = 0 + timeSlider.maximumValue = Float(duration) + timeSlider.value = Float(elapsedTime) + timeRemainingLabel.text = "-" + timeIntervalFormatter.string(from: timeRemaining)! + } else { + let elapsedTime = audioRecorder?.currentTime ?? 0 + timeElapsedLabel.text = "--:--" + timeSlider.minimumValue = 0 + timeSlider.maximumValue = 1 + timeSlider.value = 0 + timeRemainingLabel.text = timeIntervalFormatter.string(from: elapsedTime) + } + } + + + deinit { + timer?.invalidate() + } + + + // MARK: - Timer + + + func startTimer() { + timer?.invalidate() + + // time interval always in seconds + //whenever have @escaping block, block that sticks around, be very careful about usage of self because it takes up memory... which is why use weak self. + // change the withTimeInterval to change the refresh display, generally dont go below 30 miliseconds + timer = Timer.scheduledTimer(withTimeInterval: 0.030, repeats: true) { [weak self] (_) in + //guard let deals with escaping blocks, so return before do anything + guard let self = self else { return } + + self.updateViews() + + if let audioRecorder = self.audioRecorder, + self.isRecording == true { + + audioRecorder.updateMeters() + self.audioVisualizer.addValue(decibelValue: audioRecorder.averagePower(forChannel: 0)) + + } + + if let audioPlayer = self.audioPlayer, + self.isPlaying == true { + + audioPlayer.updateMeters() + self.audioVisualizer.addValue(decibelValue: audioPlayer.averagePower(forChannel: 0)) + } + } + } + + func cancelTimer() { + //invalidate doesnt set property to nil, but keeps the timer from running + timer?.invalidate() + timer = nil + } + + + + // MARK: - Playback + + var isPlaying: Bool { + audioPlayer?.isPlaying ?? false + } + + func loadAudio() { + let songURL = Bundle.main.url(forResource: "piano", withExtension: "mp3")! + + do { + audioPlayer = try AVAudioPlayer(contentsOf: songURL) + } catch { + preconditionFailure("Failure to load audio file: \(error)") + } + } + + + func prepareAudioSession() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playAndRecord, options: [.defaultToSpeaker]) + try session.setActive(true, options: []) // can fail if on a phone call, for instance + } + + + func play() { + do { + try prepareAudioSession() + audioPlayer?.play() + updateViews() + startTimer() + } catch { + print("Cannot play audio: \(error)") + } + + + } + + func pause() { + audioPlayer?.pause() + updateViews() + cancelTimer() + } + + + // MARK: - Recording + + var isRecording: Bool { + audioRecorder?.isRecording ?? false + } + + func createNewRecordingURL() -> URL { + let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! + + let name = ISO8601DateFormatter.string(from: Date(), timeZone: .current, formatOptions: .withInternetDateTime) + let file = documents.appendingPathComponent(name, isDirectory: false).appendingPathExtension("caf") + + print("recording URL: \(file)") + return file + } + + + func requestPermissionOrStartRecording() { + switch AVAudioSession.sharedInstance().recordPermission { + case .undetermined: + AVAudioSession.sharedInstance().requestRecordPermission { granted in + guard granted == true else { + print("We need microphone access") + return + } + + print("Recording permission has been granted!") + // NOTE: Invite the user to tap record again, since we just interrupted them, and they may not have been ready to record + } + case .denied: + print("Microphone access has been blocked.") + + let alertController = UIAlertController(title: "Microphone Access Denied", message: "Please allow this app to access your Microphone.", preferredStyle: .alert) + + alertController.addAction(UIAlertAction(title: "Open Settings", style: .default) { (_) in + UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) + }) + + alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) + + present(alertController, animated: true, completion: nil) + case .granted: + startRecording() + @unknown default: + break + } + } + + + func startRecording() { + do { + try prepareAudioSession() + } catch { + print("Cannot record audio: \(error)") + return + } + + recordingURL = createNewRecordingURL() + + //can return option because you can give it invalid format and combinations + // let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)! + let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44_100, channels: 1, interleaved: false)! + + do { + audioRecorder = try AVAudioRecorder(url: recordingURL!, format: format) + audioRecorder?.delegate = self + audioRecorder?.isMeteringEnabled = true + audioRecorder?.record() + updateViews() + startTimer() + } catch { + preconditionFailure("The audio recorder could not be created with \(recordingURL!) and \(format)") + } + + } + + func stopRecording() { + audioRecorder?.stop() + updateViews() + cancelTimer() + } + + // MARK: - Actions + + @IBAction func togglePlayback(_ sender: Any) { + if isPlaying { + pause() + } else { + play() + } + + } + + @IBAction func updateCurrentTime(_ sender: UISlider) { + if isPlaying { + pause() + } + audioPlayer?.currentTime = TimeInterval(sender.value) + updateViews() + } + + @IBAction func toggleRecording(_ sender: Any) { + if isRecording { + stopRecording() + } else { + requestPermissionOrStartRecording() + } + } + + @IBAction func saveRecording(_ sender: Any) { + + } + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "saveRecording" { + if let tableVC = segue.destination as? RecordedCommentTableViewController, let recording = savedRecording { + tableVC.audioRecording = recording + } + } + } +} + +extension AudioRecorderController: AVAudioPlayerDelegate { + + func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { + updateViews() + cancelTimer() + } + + func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { + if let error = error { + print("Audio Player Error: \(error)") + } + } +} + +extension AudioRecorderController: AVAudioRecorderDelegate { + func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { + if let recordingURL = recordingURL { + audioPlayer = try? AVAudioPlayer(contentsOf: recordingURL) + savedRecording = recordingURL + } + recordingURL = nil + + } + func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { + if let error = error { + print("Audio Recorder Error: \(error)") + } + } +} + + diff --git a/audioComments/audioComments/AudioVisualizer.swift b/audioComments/audioComments/AudioVisualizer.swift new file mode 100644 index 00000000..56b7dc33 --- /dev/null +++ b/audioComments/audioComments/AudioVisualizer.swift @@ -0,0 +1,276 @@ +// +// AudioVisualizer.swift +// audioComments +// +// Created by Morgan Smith on 9/7/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +@IBDesignable +public class AudioVisualizer: UIView { + + // MARK: IBInspectable Properties + + /// The width of a bar in points. + @IBInspectable public var barWidth: CGFloat = 10 { + didSet { + updateBars() + } + } + + /// The corner radius of a bar in points. If less than `0`, then it will default to half of the width of the bar. + @IBInspectable public var barCornerRadius: CGFloat = -1 { + didSet { + updateBars() + } + } + + /// The spacing between bars in points. + @IBInspectable public var barSpacing: CGFloat = 4 { + didSet { + updateBars() + } + } + + /// The color of a bar. + @IBInspectable public var barColor: UIColor = .systemGray { + didSet { + for bar in bars { + bar.backgroundColor = barColor + } + } + } + + /// The amount of time before a bar decays into the adjacent spot + @IBInspectable public var decaySpeed: Double = 0.01 { + didSet { + decayTimer?.invalidate() + decayTimer = nil + } + } + + /// The fraction the newest value will decay by if not updated by the time a decay starts + @IBInspectable public var decayAmount: Double = 0.8 + + // MARK: Internal Properties + + private var bars = [UIView]() + private var values = [Double]() + + private weak var decayTimer: Timer? + private var newestValue: Double = 0 + + // MARK: - Object Lifecycle + + override init(frame: CGRect) { + super.init(frame: frame) + + initialSetup() + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + + initialSetup() + } + + func initialSetup() { + // Pre-fill values for Interface Builder preview + #if TARGET_INTERFACE_BUILDER + values = [ + 0.19767167952644904, + 0.30975147553721694, + 0.2717680681330001, + 0.25914398105158504, + 0.3413322535900626, + 0.311223010327166, + 0.3302641160440099, + 0.303853272136915, + 0.2659123465612464, + 0.2860924489760262, + 0.26477145407733543, + 0.23180693200970012, + 0.24445487891619533, + 0.21484121767935302, + 0.19688917099112885, + 0.19020094289324854, + 0.17402194532721785, + 0.1600055988294578, + 0.15120753744055154, + 0.13789741397752767, + 0.13231033268544698, + 0.1270923459375989, + 0.1121238175344413, + 0.12400069790665748, + 0.24978783142512598, + 0.233063298365594, + 0.5375441947045457, + 0.47456518731446534, + 0.5236630241490436, + 0.4692151822551929, + 0.4255172022748686, + 0.46023063710569184, + 0.42934908823397355, + 0.37221041959882545, + 0.4685050055667653, + 0.4209394065681193, + 0.46643118034506187, + 0.4292307341708633, + 0.3814422662003417, + 0.4386719969186142, + 0.3956598546828729 + ] + #endif + + // Build the inner bars + self.updateBars() + } + + deinit { + // Invalidate the timer if it is still active + decayTimer?.invalidate() + } + + // MARK: - Layout + override public func layoutSubviews() { + updateBars() + } + + private func updateBars() { + // Clean up old bars + for bar in bars { + bar.removeFromSuperview() + } + + var newBars = [UIView]() + + + // Make sure the width of a bar and spacing is greater than 0, and that the available width is also greater than 0 + guard round(barWidth) > 0, barSpacing >= 0, bounds.width > 0, bounds.height > 0 else { + // Not enough information to create a single bar, so bail early + bars = [] + return + } + + // Calculate number of bars we will be able to display + var numberOfBarsToCreate = Int(bounds.width/(barWidth + barSpacing)) + + // Helper function for creating bars + func createBar(_ positionFromCenter: Int) { + let bar = UIView(frame: frame(forBar: positionFromCenter)) + bar.backgroundColor = barColor + bar.layer.cornerRadius = (barCornerRadius < 0 || barCornerRadius > barWidth/2) ? floor(barWidth/3) : barCornerRadius + + numberOfBarsToCreate -= 1 + newBars.append(bar) + self.addSubview(bar) + } + + // Create the center bar + createBar(0) + + // Keep creating bars in pairs until there is no more room + var position = 1 + while numberOfBarsToCreate > 0 { + // Create the symmetric pairs of bars starting from the center + createBar(-position) + createBar(position) + + position += 1 + } + + bars = newBars + } + + /// Calculate the frame of a particular bar + /// - Parameter positionFromCenter: The distance of the bar from the center (which is 0) + private func frame(forBar positionFromCenter: Int) -> CGRect { + let valueIndex = Int(positionFromCenter.magnitude) + + return frame(forBar: positionFromCenter, value: (valueIndex < values.count) ? values[valueIndex] : 0) + } + + /// Calculate the frame of a particular bar, specifying a value + /// - Parameter positionFromCenter: The distance of the bar from the center (which is 0) + private func frame(forBar positionFromCenter: Int, value: Double) -> CGRect { + let maxValue = (1 - CGFloat(positionFromCenter.magnitude)*(barWidth + barSpacing)/bounds.width/2)*bounds.height/2 + let height = CGFloat(value)*maxValue + + return CGRect(x: floor(bounds.width/2) + CGFloat(positionFromCenter)*(barWidth + barSpacing) - barWidth/2, y: floor(bounds.height/2) - height, width: barWidth, height: height*2) + } + + // MARK: - Animation + + /// Start the decay timer, but only if if hasn't been created yet + private func startTimer() { + guard decayTimer == nil else { return } + + decayTimer = Timer.scheduledTimer(withTimeInterval: decaySpeed, repeats: true) { [weak self] (_) in + guard let self = self else { return } + + self.decayNewestValue() + } + } + + private func decayNewestValue() { + values.insert(newestValue, at: 0) + + // Trim the end of the values array if there are too many for the number of bars + let currentCount = values.count + let maxCount = (bars.count + 1)/2 + /* + Note that the amount of bars will always be either 0, or an odd number (since the bars are counted in pairs after the first central bar), so we chose a "transformation" (a mathematical function) that satisfies this: value index = floor((bar index + 1)/2) + + Bar index: 0 1 2 3 4 5 6 7 8 9 ... + (valid bar index): 0 1 - 3 - 5 - 7 - 9 ... + Value index: 0 1 1 2 2 3 3 4 4 5 ... + + */ + if currentCount > maxCount { + values.removeSubrange(maxCount ..< currentCount) + } + + // Update the frames of each bar + for (positionFromCenter, value) in values.enumerated() { + if positionFromCenter == 0 { + bars[0].frame = frame(forBar: positionFromCenter, value: value) + } else { + bars[positionFromCenter*2 - 1].frame = frame(forBar: -positionFromCenter, value: value) + bars[positionFromCenter*2].frame = frame(forBar: positionFromCenter, value: value) + } + } + + // Decay the newest value + newestValue = newestValue*decayAmount + + // Check if the values are empty + let totalValue = values.reduce(0.0) { $0 + $1 } + if totalValue <= 0.000001 { + // Note that total value may never reach 0, but this is small enough to clear everything out + decayTimer?.invalidate() + decayTimer = nil + } + } + + // MARK: - Public Methods + + /// Add a value to the visualizer. Be sure to call `AVAudioPlayer.isMeteringEnabled = true`, and `AVAudioPlayer.updateMeters()` before every call to `AVAudioPlayer.averagePower(forChannel: 0)` + /// - Parameter decibelValue: The value you would get out of `AVAudioPlayer.averagePower(forChannel: 0)` + public func addValue(decibelValue: Float) { + addValue(decibelValue: Double(decibelValue)) + } + + /// Add a value to the visualizer. Be sure to call `AVAudioPlayer.isMeteringEnabled = true`, and `AVAudioPlayer.updateMeters()` before every call to `AVAudioPlayer.averagePower(forChannel: 0)` + /// - Parameter decibelValue: The value you would get out of `AVAudioPlayer.averagePower(forChannel: 0)` + public func addValue(decibelValue: Double) { + let normalizedValue = __exp10(decibelValue/20) + + newestValue = normalizedValue + + startTimer() + } + +} + diff --git a/audioComments/audioComments/Base.lproj/LaunchScreen.storyboard b/audioComments/audioComments/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..865e9329 --- /dev/null +++ b/audioComments/audioComments/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/audioComments/audioComments/Base.lproj/Main.storyboard b/audioComments/audioComments/Base.lproj/Main.storyboard new file mode 100644 index 00000000..d8b489d3 --- /dev/null +++ b/audioComments/audioComments/Base.lproj/Main.storyboard @@ -0,0 +1,217 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/audioComments/audioComments/Info.plist b/audioComments/audioComments/Info.plist new file mode 100644 index 00000000..7da6c2db --- /dev/null +++ b/audioComments/audioComments/Info.plist @@ -0,0 +1,66 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + NSMicrophoneUsageDescription + $(PRODUCT_NAME) access to recording privacy + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/audioComments/audioComments/RecordedCommentTableViewCell.swift b/audioComments/audioComments/RecordedCommentTableViewCell.swift new file mode 100644 index 00000000..2e002e3a --- /dev/null +++ b/audioComments/audioComments/RecordedCommentTableViewCell.swift @@ -0,0 +1,113 @@ +// +// RecordedCommentTableViewCell.swift +// audioComments +// +// Created by Morgan Smith on 9/8/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import AVFoundation + +class RecordedCommentTableViewCell: UITableViewCell { + + override func awakeFromNib() { + super.awakeFromNib() + } + + var audioPlayer: AVAudioPlayer? { + didSet { + guard let audioPlayer = audioPlayer else { + return + } + audioPlayer.delegate = self + updateViews() + } + } + + var recordingURL: URL? { + didSet { + loadAudio() + updateViews() + } + } + + @IBOutlet weak var authorLabel: UILabel! + @IBOutlet weak var timeElapsedLabel: UILabel! + @IBOutlet weak var timeRemainingLabel: UILabel! + @IBOutlet weak var playButton: UIButton! + @IBOutlet weak var timeSlider: UISlider! + + + + func updateViews() { + playButton.isSelected = isPlaying + } + + + + + var isPlaying: Bool { + audioPlayer?.isPlaying ?? false + } + + + + func loadAudio() { + guard let songURL = recordingURL else { return } + + do { + audioPlayer = try AVAudioPlayer(contentsOf: songURL) + } catch { + preconditionFailure("Failure to load audio file: \(error)") + } + } + + func prepareAudioSession() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playAndRecord, options: [.defaultToSpeaker]) + try session.setActive(true, options: []) // can fail if on a phone call, for instance + } + + func play() { + do { + try prepareAudioSession() + audioPlayer?.play() + updateViews() + } catch { + print("Cannot play audio: \(error)") + } + + + } + + func pause() { + audioPlayer?.pause() + updateViews() + } + + @IBAction func togglePlayback(_ sender: Any) { + if isPlaying { + pause() + } else { + play() + } + } + + +} + + +extension RecordedCommentTableViewCell: AVAudioPlayerDelegate { + + func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { + updateViews() + } + + func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { + if let error = error { + print("Audio Player Error: \(error)") + } + } +} + diff --git a/audioComments/audioComments/RecordedCommentTableViewController.swift b/audioComments/audioComments/RecordedCommentTableViewController.swift new file mode 100644 index 00000000..8c0aabef --- /dev/null +++ b/audioComments/audioComments/RecordedCommentTableViewController.swift @@ -0,0 +1,75 @@ +// +// RecordedCommentTableViewController.swift +// audioComments +// +// Created by Morgan Smith on 9/8/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit +import AVFoundation + +class RecordedCommentTableViewController: UITableViewController { + + var audioRecordings: [URL] = [] { + didSet { + tableView.reloadData() + print("table view recordings: \(audioRecordings)") + } + } + + var audioRecording: URL? + + override func viewDidLoad() { + super.viewDidLoad() + if let audioRecording = audioRecording { + audioRecordings.append(audioRecording) + } + tableView.dataSource = self + tableView.delegate = self + } + + // MARK: - Table view data source + + + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return audioRecordings.count + } + + + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard let cell = tableView.dequeueReusableCell(withIdentifier: "audioCommentCell", for: indexPath) as? RecordedCommentTableViewCell else { return UITableViewCell() } + let recording = audioRecordings[indexPath.row] + + cell.recordingURL = recording + cell.playButton.isSelected = false + return cell + } + + + + + // Override to support editing the table view. + override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { + if editingStyle == .delete { + let recordingToDelete = audioRecordings[indexPath.row] + audioRecordings.removeAll { $0 == recordingToDelete } + tableView.deleteRows(at: [indexPath], with: .fade) + tableView.reloadData() + } + } + + + + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ + +} diff --git a/audioComments/audioComments/SceneDelegate.swift b/audioComments/audioComments/SceneDelegate.swift new file mode 100644 index 00000000..3b7851e8 --- /dev/null +++ b/audioComments/audioComments/SceneDelegate.swift @@ -0,0 +1,53 @@ +// +// SceneDelegate.swift +// audioComments +// +// Created by Morgan Smith on 9/7/20. +// Copyright © 2020 Morgan Smith. All rights reserved. +// + +import UIKit + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. + // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + guard let _ = (scene as? UIWindowScene) else { return } + } + + func sceneDidDisconnect(_ scene: UIScene) { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). + } + + func sceneDidBecomeActive(_ scene: UIScene) { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + } + + func sceneWillResignActive(_ scene: UIScene) { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). + } + + func sceneWillEnterForeground(_ scene: UIScene) { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. + } + + func sceneDidEnterBackground(_ scene: UIScene) { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. + } + + +} + diff --git a/audioComments/audioComments/piano.mp3 b/audioComments/audioComments/piano.mp3 new file mode 100644 index 00000000..87ed0dbc Binary files /dev/null and b/audioComments/audioComments/piano.mp3 differ