diff --git a/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj b/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj new file mode 100644 index 00000000..ac115c5a --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor.xcodeproj/project.pbxproj @@ -0,0 +1,349 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 0B8FFC90250083F600C2AFE9 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B8FFC8F250083F600C2AFE9 /* AppDelegate.swift */; }; + 0B8FFC92250083F600C2AFE9 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B8FFC91250083F600C2AFE9 /* SceneDelegate.swift */; }; + 0B8FFC97250083F600C2AFE9 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0B8FFC95250083F600C2AFE9 /* Main.storyboard */; }; + 0B8FFC99250083F800C2AFE9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0B8FFC98250083F800C2AFE9 /* Assets.xcassets */; }; + 0B8FFC9C250083F800C2AFE9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 0B8FFC9A250083F800C2AFE9 /* LaunchScreen.storyboard */; }; + 0B8FFCA4250084D100C2AFE9 /* Filters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B8FFCA3250084D100C2AFE9 /* Filters.swift */; }; + 0BFB3BC325008A7F0027F38F /* ImagePostViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BFB3BC225008A7F0027F38F /* ImagePostViewController.swift */; }; + 0BFB3BC525008E4E0027F38F /* UIImage+Scaling.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BFB3BC425008E4E0027F38F /* UIImage+Scaling.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 0B8FFC8C250083F600C2AFE9 /* ImageFilterEditor.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ImageFilterEditor.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 0B8FFC8F250083F600C2AFE9 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 0B8FFC91250083F600C2AFE9 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 0B8FFC96250083F600C2AFE9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 0B8FFC98250083F800C2AFE9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 0B8FFC9B250083F800C2AFE9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 0B8FFC9D250083F800C2AFE9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0B8FFCA3250084D100C2AFE9 /* Filters.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Filters.swift; sourceTree = ""; }; + 0BFB3BC225008A7F0027F38F /* ImagePostViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagePostViewController.swift; sourceTree = ""; }; + 0BFB3BC425008E4E0027F38F /* UIImage+Scaling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Scaling.swift"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0B8FFC89250083F600C2AFE9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0B8FFC83250083F600C2AFE9 = { + isa = PBXGroup; + children = ( + 0B8FFC8E250083F600C2AFE9 /* ImageFilterEditor */, + 0B8FFC8D250083F600C2AFE9 /* Products */, + ); + sourceTree = ""; + }; + 0B8FFC8D250083F600C2AFE9 /* Products */ = { + isa = PBXGroup; + children = ( + 0B8FFC8C250083F600C2AFE9 /* ImageFilterEditor.app */, + ); + name = Products; + sourceTree = ""; + }; + 0B8FFC8E250083F600C2AFE9 /* ImageFilterEditor */ = { + isa = PBXGroup; + children = ( + 0B8FFC8F250083F600C2AFE9 /* AppDelegate.swift */, + 0B8FFC91250083F600C2AFE9 /* SceneDelegate.swift */, + 0B8FFC95250083F600C2AFE9 /* Main.storyboard */, + 0B8FFC98250083F800C2AFE9 /* Assets.xcassets */, + 0B8FFC9A250083F800C2AFE9 /* LaunchScreen.storyboard */, + 0B8FFC9D250083F800C2AFE9 /* Info.plist */, + 0B8FFCA3250084D100C2AFE9 /* Filters.swift */, + 0BFB3BC225008A7F0027F38F /* ImagePostViewController.swift */, + 0BFB3BC425008E4E0027F38F /* UIImage+Scaling.swift */, + ); + path = ImageFilterEditor; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 0B8FFC8B250083F600C2AFE9 /* ImageFilterEditor */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0B8FFCA0250083F800C2AFE9 /* Build configuration list for PBXNativeTarget "ImageFilterEditor" */; + buildPhases = ( + 0B8FFC88250083F600C2AFE9 /* Sources */, + 0B8FFC89250083F600C2AFE9 /* Frameworks */, + 0B8FFC8A250083F600C2AFE9 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ImageFilterEditor; + productName = ImageFilterEditor; + productReference = 0B8FFC8C250083F600C2AFE9 /* ImageFilterEditor.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 0B8FFC84250083F600C2AFE9 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1160; + LastUpgradeCheck = 1160; + ORGANIZATIONNAME = "Clayton Watkins"; + TargetAttributes = { + 0B8FFC8B250083F600C2AFE9 = { + CreatedOnToolsVersion = 11.6; + }; + }; + }; + buildConfigurationList = 0B8FFC87250083F600C2AFE9 /* Build configuration list for PBXProject "ImageFilterEditor" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 0B8FFC83250083F600C2AFE9; + productRefGroup = 0B8FFC8D250083F600C2AFE9 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 0B8FFC8B250083F600C2AFE9 /* ImageFilterEditor */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 0B8FFC8A250083F600C2AFE9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0B8FFC9C250083F800C2AFE9 /* LaunchScreen.storyboard in Resources */, + 0B8FFC99250083F800C2AFE9 /* Assets.xcassets in Resources */, + 0B8FFC97250083F600C2AFE9 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0B8FFC88250083F600C2AFE9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0BFB3BC325008A7F0027F38F /* ImagePostViewController.swift in Sources */, + 0BFB3BC525008E4E0027F38F /* UIImage+Scaling.swift in Sources */, + 0B8FFCA4250084D100C2AFE9 /* Filters.swift in Sources */, + 0B8FFC90250083F600C2AFE9 /* AppDelegate.swift in Sources */, + 0B8FFC92250083F600C2AFE9 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 0B8FFC95250083F600C2AFE9 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 0B8FFC96250083F600C2AFE9 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 0B8FFC9A250083F800C2AFE9 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 0B8FFC9B250083F800C2AFE9 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 0B8FFC9E250083F800C2AFE9 /* 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.6; + 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; + }; + 0B8FFC9F250083F800C2AFE9 /* 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.6; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 0B8FFCA1250083F800C2AFE9 /* 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.claytonwatkins.ImageFilterEditor; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 0B8FFCA2250083F800C2AFE9 /* 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.claytonwatkins.ImageFilterEditor; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 0B8FFC87250083F600C2AFE9 /* Build configuration list for PBXProject "ImageFilterEditor" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0B8FFC9E250083F800C2AFE9 /* Debug */, + 0B8FFC9F250083F800C2AFE9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0B8FFCA0250083F800C2AFE9 /* Build configuration list for PBXNativeTarget "ImageFilterEditor" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0B8FFCA1250083F800C2AFE9 /* Debug */, + 0B8FFCA2250083F800C2AFE9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 0B8FFC84250083F600C2AFE9 /* Project object */; +} diff --git a/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift b/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift new file mode 100644 index 00000000..cd2fa633 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/AppDelegate.swift @@ -0,0 +1,37 @@ +// +// AppDelegate.swift +// ImageFilterEditor +// +// Created by Clayton Watkins on 9/2/20. +// Copyright © 2020 Clayton Watkins. 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/Assets.xcassets/spirited.imageset/Contents.json b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/spirited.imageset/Contents.json new file mode 100644 index 00000000..3bdb8cbf --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/spirited.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "filename" : "spirited.jpg", + "idiom" : "universal", + "scale" : "1x" + }, + { + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/spirited.imageset/spirited.jpg b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/spirited.imageset/spirited.jpg new file mode 100644 index 00000000..f774df89 Binary files /dev/null and b/ImageFilterEditor/ImageFilterEditor/Assets.xcassets/spirited.imageset/spirited.jpg differ 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..b37a8b2b --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Base.lproj/Main.storyboard @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ImageFilterEditor/ImageFilterEditor/Filters.swift b/ImageFilterEditor/ImageFilterEditor/Filters.swift new file mode 100644 index 00000000..ada5f7c1 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Filters.swift @@ -0,0 +1,26 @@ +// +// Filters.swift +// ImageFilterEditor +// +// Created by Clayton Watkins on 9/2/20. +// Copyright © 2020 Clayton Watkins. All rights reserved. +// + +import Foundation +import CoreImage +import CoreImage.CIFilterBuiltins + + +class Filters { + + // MARK: - Properties + let blurFilter = CIFilter.gaussianBlur() + let falseColorFilter = CIFilter.falseColor() + let vignetteFilter = CIFilter.vignette() + let whitePointFilter = CIFilter.whitePointAdjust() + let monoChromaticFilter = CIFilter.photoEffectMono() + + + + +} diff --git a/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift b/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift new file mode 100644 index 00000000..fc986733 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/ImagePostViewController.swift @@ -0,0 +1,127 @@ +// +// ImagePostViewController.swift +// ImageFilterEditor +// +// Created by Clayton Watkins on 9/2/20. +// Copyright © 2020 Clayton Watkins. All rights reserved. +// + +import UIKit +import CoreImage +import CoreImage.CIFilterBuiltins + +class ImagePostViewController: UIViewController { + + // MARK: - IBOutlets + @IBOutlet weak var blurSlider: UISlider! + @IBOutlet weak var vignetteSilder: UISlider! + @IBOutlet weak var whitePointSlider: UISlider! + @IBOutlet weak var falseColorSilder: UISlider! + @IBOutlet weak var monoChromaticSlider: UISlider! + @IBOutlet weak var imageView: UIImageView! + + // MARK: - Properties + var originalImage: UIImage?{ + didSet{ + guard let originalImage = originalImage else { + scaledImage = nil + return + } + + var scaledSize = imageView.bounds.size + let scale = imageView.contentScaleFactor + + scaledSize = CGSize(width: scaledSize.width*scale, height: scaledSize.height*scale) + + guard let scaledUIImage = originalImage.imageByScaling(toSize: scaledSize) else { + scaledImage = nil + return + } + + scaledImage = CIImage(image: scaledUIImage) + } + } + + var scaledImage: CIImage?{ + didSet{ + updateImage() + } + } + + let context = CIContext() + + // MARK: - Lifecycle + override func viewDidLoad() { + super.viewDidLoad() + originalImage = imageView.image + } + + // MARK: - Methods + private func image(byFiltering image: CIImage) -> UIImage? { + let inputImage = image + + // Blur + let blurFilter = CIFilter.gaussianBlur() + blurFilter.inputImage = inputImage + blurFilter.radius = blurSlider.value + + // Sharpen + let sharpenFilter = CIFilter.sharpenLuminance() + sharpenFilter.inputImage = blurFilter.outputImage?.clampedToExtent() + sharpenFilter.sharpness = falseColorSilder.value + + // Vignette + let vignetteFilter = CIFilter.vignette() + vignetteFilter.inputImage = sharpenFilter.outputImage?.clampedToExtent() + vignetteFilter.intensity = vignetteSilder.value + vignetteFilter.radius = vignetteSilder.value + + // Sepia + let sepiaFilter = CIFilter.sepiaTone() + sepiaFilter.inputImage = vignetteFilter.outputImage?.clampedToExtent() + sepiaFilter.intensity = whitePointSlider.value + + // MonoChromatic + let monochromaticFilter = CIFilter.colorMonochrome() + monochromaticFilter.inputImage = sepiaFilter.outputImage?.clampedToExtent() + monochromaticFilter.intensity = monoChromaticSlider.value + + guard let outputImage = monochromaticFilter.outputImage else { return nil } + + guard let renderedCGImage = context.createCGImage(outputImage, from: inputImage.extent) else { return nil} + + return UIImage(cgImage: renderedCGImage) + + } + + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + // MARK: - IBActions + @IBAction func blurChanged(_ sender: Any) { + updateImage() + } + + @IBAction func vignetteChanged(_ sender: Any) { + updateImage() + } + + @IBAction func whitePointChanged(_ sender: Any) { + updateImage() + } + + @IBAction func falseColorChanged(_ sender: Any) { + updateImage() + } + + @IBAction func monoChromaticChanged(_ sender: Any) { + updateImage() + } + + +} diff --git a/ImageFilterEditor/ImageFilterEditor/Info.plist b/ImageFilterEditor/ImageFilterEditor/Info.plist new file mode 100644 index 00000000..2a3483c0 --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/Info.plist @@ -0,0 +1,64 @@ + + + + + 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..e21f578e --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/SceneDelegate.swift @@ -0,0 +1,53 @@ +// +// SceneDelegate.swift +// ImageFilterEditor +// +// Created by Clayton Watkins on 9/2/20. +// Copyright © 2020 Clayton Watkins. 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/ImageFilterEditor/ImageFilterEditor/UIImage+Scaling.swift b/ImageFilterEditor/ImageFilterEditor/UIImage+Scaling.swift new file mode 100644 index 00000000..40e02ffe --- /dev/null +++ b/ImageFilterEditor/ImageFilterEditor/UIImage+Scaling.swift @@ -0,0 +1,38 @@ +// +// UIImage+Scaling.swift +// ImageFilterEditor +// +// Created by Clayton Watkins on 9/2/20. +// Copyright © 2020 Clayton Watkins. 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.xcodeproj/project.pbxproj b/LambdaTimeline.xcodeproj/project.pbxproj index b2af5414..8e88072e 100644 --- a/LambdaTimeline.xcodeproj/project.pbxproj +++ b/LambdaTimeline.xcodeproj/project.pbxproj @@ -7,6 +7,11 @@ objects = { /* Begin PBXBuildFile section */ + 0B43785B25017D92009599C4 /* UIImage+Scaling.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B43785A25017D92009599C4 /* UIImage+Scaling.swift */; }; + 0B78558E250ACACB0073FC82 /* PostLocationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B78558D250ACACB0073FC82 /* PostLocationViewController.swift */; }; + 0B8396BF250307D2009DF3ED /* AudioCommentTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B8396BE250307D2009DF3ED /* AudioCommentTableViewCell.swift */; }; + 0B88760C2502E5ED00B6AAED /* AudioVisualizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B88760B2502E5ED00B6AAED /* AudioVisualizer.swift */; }; + 0B88760E2502E65600B6AAED /* AudioCommentViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B88760D2502E65600B6AAED /* AudioCommentViewController.swift */; }; 4646377C216FDE4B00E7FF73 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4646377B216FDE4B00E7FF73 /* AppDelegate.swift */; }; 46463783216FDE4C00E7FF73 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 46463782216FDE4C00E7FF73 /* Assets.xcassets */; }; 46463786216FDE4C00E7FF73 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 46463784216FDE4C00E7FF73 /* LaunchScreen.storyboard */; }; @@ -25,6 +30,11 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 0B43785A25017D92009599C4 /* UIImage+Scaling.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Scaling.swift"; sourceTree = ""; }; + 0B78558D250ACACB0073FC82 /* PostLocationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PostLocationViewController.swift; sourceTree = ""; }; + 0B8396BE250307D2009DF3ED /* AudioCommentTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioCommentTableViewCell.swift; sourceTree = ""; }; + 0B88760B2502E5ED00B6AAED /* AudioVisualizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioVisualizer.swift; sourceTree = ""; }; + 0B88760D2502E65600B6AAED /* AudioCommentViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioCommentViewController.swift; 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 = ""; }; 46463782216FDE4C00E7FF73 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -90,6 +100,7 @@ children = ( 4646378F216FFD1B00E7FF73 /* Post.swift */, 46463791216FFDD900E7FF73 /* Comment.swift */, + 0B88760B2502E5ED00B6AAED /* AudioVisualizer.swift */, ); path = Models; sourceTree = ""; @@ -128,6 +139,8 @@ 46A0366921700F5100E7FF73 /* PostsCollectionViewController.swift */, 46CFE6F421707D0000E7FF73 /* ImagePostViewController.swift */, 46D571F72173FC2700E7FF73 /* ImagePostDetailTableViewController.swift */, + 0B88760D2502E65600B6AAED /* AudioCommentViewController.swift */, + 0B78558D250ACACB0073FC82 /* PostLocationViewController.swift */, ); path = "View Controllers"; sourceTree = ""; @@ -136,6 +149,7 @@ isa = PBXGroup; children = ( 46CFE7022171572600E7FF73 /* ImagePostCollectionViewCell.swift */, + 0B8396BE250307D2009DF3ED /* AudioCommentTableViewCell.swift */, ); path = Views; sourceTree = ""; @@ -145,6 +159,7 @@ children = ( 46D571F62173D6D200E7FF73 /* Extensions */, 46CFE6F82170862C00E7FF73 /* ShiftableViewController.swift */, + 0B43785A25017D92009599C4 /* UIImage+Scaling.swift */, ); path = Helpers; sourceTree = ""; @@ -230,10 +245,15 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 0B88760C2502E5ED00B6AAED /* AudioVisualizer.swift in Sources */, + 0B88760E2502E65600B6AAED /* AudioCommentViewController.swift in Sources */, + 0B78558E250ACACB0073FC82 /* PostLocationViewController.swift in Sources */, + 0B8396BF250307D2009DF3ED /* AudioCommentTableViewCell.swift in Sources */, 46A0366D2170158900E7FF73 /* SignInViewController.swift in Sources */, 46CFE6F92170862C00E7FF73 /* ShiftableViewController.swift in Sources */, 4646377C216FDE4B00E7FF73 /* AppDelegate.swift in Sources */, 46CFE6F521707D0000E7FF73 /* ImagePostViewController.swift in Sources */, + 0B43785B25017D92009599C4 /* UIImage+Scaling.swift in Sources */, 46463790216FFD1B00E7FF73 /* Post.swift in Sources */, 46D571F82173FC2700E7FF73 /* ImagePostDetailTableViewController.swift in Sources */, 46CFE7032171572600E7FF73 /* ImagePostCollectionViewCell.swift in Sources */, diff --git a/LambdaTimeline/Helpers/UIImage+Scaling.swift b/LambdaTimeline/Helpers/UIImage+Scaling.swift new file mode 100644 index 00000000..27c55318 --- /dev/null +++ b/LambdaTimeline/Helpers/UIImage+Scaling.swift @@ -0,0 +1,39 @@ +// +// UIImage+Scaling.swift +// LambdaTimeline +// +// Created by Clayton Watkins on 9/3/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import Foundation +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 3df87148..058411b8 100644 --- a/LambdaTimeline/Model Controllers/PostController.swift +++ b/LambdaTimeline/Model Controllers/PostController.swift @@ -7,20 +7,23 @@ // import UIKit +import MapKit class PostController { + static let shared = PostController() + var posts: [Post] = [] var currentUser: String? { UserDefaults.standard.string(forKey: "username") } - func createImagePost(with title: String, image: UIImage, ratio: CGFloat?) { + func createImagePost(with title: String, image: UIImage, ratio: CGFloat?, audioURL: URL?, location: CLLocationCoordinate2D) { guard let currentUser = currentUser else { return } - let post = Post(title: title, mediaType: .image(image), ratio: ratio, author: currentUser) + let post = Post(title: title, mediaType: .image(image), ratio: ratio, author: currentUser, audioURL: audioURL, location: location) posts.append(post) } @@ -29,8 +32,15 @@ class PostController { guard let currentUser = currentUser else { return } - let comment = Comment(text: text, author: currentUser) + let comment = Comment(text: text, author: currentUser, audioURL: nil) post.comments.append(comment) } + + func addAudioComment(with url: URL, to post: inout Post) { + guard let currentUser = currentUser else { return } + + let comment = Comment(author: currentUser, audioURL: url) + post.comments.append(comment) + } } diff --git a/LambdaTimeline/Models/AudioVisualizer.swift b/LambdaTimeline/Models/AudioVisualizer.swift new file mode 100644 index 00000000..675da911 --- /dev/null +++ b/LambdaTimeline/Models/AudioVisualizer.swift @@ -0,0 +1,276 @@ +// +// AudioVisualizer.swift +// LambdaTimeline +// +// Created by Clayton Watkins on 9/4/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/Models/Comment.swift b/LambdaTimeline/Models/Comment.swift index a7dad6f5..e8770549 100644 --- a/LambdaTimeline/Models/Comment.swift +++ b/LambdaTimeline/Models/Comment.swift @@ -17,11 +17,13 @@ class Comment: Hashable { let text: String? let author: String let timestamp: Date + let audioURL: URL? - init(text: String? = nil, author: String, timestamp: Date = Date()) { + init(text: String? = nil, author: String, timestamp: Date = Date(), audioURL: URL?) { self.text = text self.author = author self.timestamp = timestamp + self.audioURL = audioURL } func hash(into hasher: inout Hasher) { diff --git a/LambdaTimeline/Models/Post.swift b/LambdaTimeline/Models/Post.swift index 15e1d65c..a9bb4232 100644 --- a/LambdaTimeline/Models/Post.swift +++ b/LambdaTimeline/Models/Post.swift @@ -7,12 +7,17 @@ // import UIKit +import MapKit enum MediaType { case image(UIImage) } -class Post: Equatable { +struct Locations { + static let discordLocation = CLLocationCoordinate2D(latitude: 37.76331329345703, longitude: -122.40142822265625) +} + +class Post: NSObject { let mediaType: MediaType let author: String @@ -20,21 +25,39 @@ class Post: Equatable { var comments: [Comment] var ratio: CGFloat? var id: String? + let location: CLLocationCoordinate2D + var title: String? { - return comments.first?.text + comments.first?.text } - init(title: String, mediaType: MediaType, ratio: CGFloat?, author: String, timestamp: Date = Date()) { + var audioURL: URL? { + comments.first?.audioURL + } + + init(title: String, mediaType: MediaType, ratio: CGFloat?, author: String, timestamp: Date = Date(), audioURL: URL?, location: CLLocationCoordinate2D? = nil) { self.mediaType = mediaType self.ratio = ratio self.author = author - self.comments = [Comment(text: title, author: author)] + self.comments = [Comment(text: title, author: author, audioURL: audioURL)] self.timestamp = timestamp self.id = UUID().uuidString + self.location = location ?? Locations.discordLocation } + static func ==(lhs: Post, rhs: Post) -> Bool { return lhs.id == rhs.id } } + +extension Post: MKAnnotation { + var coordinate: CLLocationCoordinate2D { + CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) + } + + var postTitle: String? { title } + + var subtitle: String? { author } +} diff --git a/LambdaTimeline/Resources/Info.plist b/LambdaTimeline/Resources/Info.plist index dab10c0a..1f6399e6 100644 --- a/LambdaTimeline/Resources/Info.plist +++ b/LambdaTimeline/Resources/Info.plist @@ -33,6 +33,10 @@ NSPhotoLibraryUsageDescription In order to allow you to add photos to posts + NSMicrophoneUsageDescription + $(PRODUCT_NAME) would like access to the microphone to record audio. + NSLocationWhenInUseUsageDescription + $(PRODUCT_NAME) would like access to the GPS in order to save your location. UILaunchStoryboardName LaunchScreen UIMainStoryboardFile diff --git a/LambdaTimeline/Storyboards/Main.storyboard b/LambdaTimeline/Storyboards/Main.storyboard index 9e2d25d6..9c65e018 100644 --- a/LambdaTimeline/Storyboards/Main.storyboard +++ b/LambdaTimeline/Storyboards/Main.storyboard @@ -1,8 +1,7 @@ - - + + - @@ -13,7 +12,7 @@ - + @@ -24,7 +23,7 @@ - + @@ -34,19 +33,19 @@ - + - + diff --git a/LambdaTimeline/View Controllers/AudioCommentViewController.swift b/LambdaTimeline/View Controllers/AudioCommentViewController.swift new file mode 100644 index 00000000..4e906c66 --- /dev/null +++ b/LambdaTimeline/View Controllers/AudioCommentViewController.swift @@ -0,0 +1,295 @@ +// +// AudioCommentController.swift +// LambdaTimeline +// +// Created by Clayton Watkins on 9/4/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import AVFoundation + +protocol VoiceCommentAddedDelegate { + func reloadData() +} + +class AudioCommentViewController: UIViewController { + + // MARK: - IBOutlets + @IBOutlet var playButton: UIButton! + @IBOutlet var recordButton: UIButton! + @IBOutlet var timeElapsedLabel: UILabel! + @IBOutlet var timeRemainingLabel: UILabel! + @IBOutlet var timeSlider: UISlider! + @IBOutlet var audioVisualizer: AudioVisualizer! + + //MARK: - Properties + var audioPlayer: AVAudioPlayer?{ + didSet { + guard let audioPlayer = audioPlayer else { return } + + audioPlayer.delegate = self + audioPlayer.isMeteringEnabled = true + updateViews() + } + } + + weak var timer: Timer? + var audioRecorder: AVAudioRecorder? + + let postController = PostController.shared + var post: Post! + var delegate: VoiceCommentAddedDelegate? + var recordingURL: URL? + + 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) + } + + 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 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("Can't play audio: \(error)") + } + } + + func pause() { + audioPlayer?.pause() + updateViews() + cancelTimer() + } + + + // MARK: - Recording + + var isRecording: Bool { + audioRecorder?.isRecording ?? false + } + + + 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 newRecordingURL() -> URL { + let fm = FileManager.default + let documentsDir = try! fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + + let randomId = Int.random(in: 0...1_000_00) + + return documentsDir.appendingPathComponent("TestRecording" + "\(randomId)").appendingPathExtension("caf") + } + + func startRecording() { + do{ + try prepareAudioSession() + } catch { + print("Can't record audio: \(error)") + return + } + + recordingURL = newRecordingURL() + + let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)! + 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 \(format)") + } + } + + func stopRecording() { + audioRecorder?.stop() + updateViews() + cancelTimer() + } + + @IBAction func saveRecording(_ sender: Any) { + self.postController.addAudioComment(with: recordingURL!, to: &self.post) + self.delegate?.reloadData() + } + + // 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() + } + } +} + +extension AudioCommentViewController: 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 AudioCommentViewController: AVAudioRecorderDelegate { + func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { + if let recordingURL = recordingURL { + audioPlayer = try? AVAudioPlayer(contentsOf: recordingURL) + } + cancelTimer() + } + + func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { + if let error = error{ + print("Recoder Player Error: \(error)") + } + } +} + diff --git a/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift b/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift index c108edd7..314bf187 100644 --- a/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift +++ b/LambdaTimeline/View Controllers/ImagePostDetailTableViewController.swift @@ -17,7 +17,7 @@ class ImagePostDetailTableViewController: UITableViewController { @IBOutlet weak var commentButton: UIBarButtonItem! var post: Post! - var postController: PostController! + let postController = PostController.shared var imageData: Data? override func viewDidLoad() { @@ -41,32 +41,53 @@ 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: "New Comment", message: "Which kind of comment do you want to create?", preferredStyle: .actionSheet) - var commentTextField: UITextField? - - alert.addTextField { (textField) in - textField.placeholder = "Comment:" - commentTextField = textField - } - - let addCommentAction = UIAlertAction(title: "Add Comment", style: .default) { (_) in + // If comment is a Text Post + let textPostAction = UIAlertAction(title: "Text", style: .default) { _ in + let alert = UIAlertController(title: "Add a comment", message: "Write your comment below:", preferredStyle: .alert) - guard let commentText = commentTextField?.text else { return } + var commentTextField: UITextField? - self.postController.addComment(with: commentText, to: &self.post!) + alert.addTextField { (textField) in + textField.placeholder = "Comment:" + commentTextField = textField + } - DispatchQueue.main.async { - self.tableView.reloadData() + let addCommentAction = UIAlertAction(title: "Add Comment", style: .default) { (_) in + + guard let commentText = commentTextField?.text else { return } + + self.postController.addComment(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) + + self.present(alert, animated: true, completion: nil) + } + + // If comment is a voice comment + let voicePostAction = UIAlertAction(title: "Voice", style: .default) { _ in + let storyboard = UIStoryboard(name: "Main", bundle: nil) + let vc = storyboard.instantiateViewController(withIdentifier: "AudioCommentController") as! AudioCommentViewController + vc.post = self.post + vc.delegate = self + self.navigationController?.pushViewController(vc, animated: true) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) - alert.addAction(addCommentAction) + alert.addAction(textPostAction) + alert.addAction(voicePostAction) alert.addAction(cancelAction) - present(alert, animated: true, completion: nil) + self.present(alert, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { @@ -74,13 +95,39 @@ 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 - - return cell + if comment?.audioURL != nil { + guard let cell = tableView.dequeueReusableCell(withIdentifier: "AudioCommentCell", for: indexPath) as? AudioCommentTableViewCell else { return UITableViewCell()} + let comment = post?.comments[indexPath.row + 1] + cell.recordingURL = comment?.audioURL + cell.usernameLabel.text = comment?.author + return cell + } else { + + 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 + + return cell + } + } + + @IBAction func undwindSegue(_ sender: UIStoryboardSegue){} +} + +extension ImagePostDetailTableViewController: VoiceCommentAddedDelegate { + func reloadData() { + tableView.reloadData() + } + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + guard let mapViewVC = segue.destination as? PostLocationViewController else { return } + mapViewVC.location = post.location + mapViewVC.postTitle = post.title + mapViewVC.postAuthor = post.author } } diff --git a/LambdaTimeline/View Controllers/ImagePostViewController.swift b/LambdaTimeline/View Controllers/ImagePostViewController.swift index 9cffbbbb..c0533ef7 100644 --- a/LambdaTimeline/View Controllers/ImagePostViewController.swift +++ b/LambdaTimeline/View Controllers/ImagePostViewController.swift @@ -8,37 +8,139 @@ import UIKit import Photos +import CoreImage +import CoreImage.CIFilterBuiltins +import MapKit class ImagePostViewController: ShiftableViewController { + // MARK: - IBOutlets @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! + @IBOutlet weak var blurSlider: UISlider! + @IBOutlet weak var sharpenSlider: UISlider! + @IBOutlet weak var vignetteSlider: UISlider! + @IBOutlet weak var sepiaSlider: UISlider! + @IBOutlet weak var monoChromaticSlider: UISlider! + @IBOutlet weak var locationSwitch: UISwitch! - var postController: PostController! + // MARK: - Properties + let postController = PostController.shared var post: Post? var imageData: Data? + var originalImage: UIImage?{ + didSet{ + guard let originalImage = originalImage else { + scaledImage = nil + return + } + + var scaledSize = imageView.bounds.size + let scale = imageView.contentScaleFactor + + scaledSize = CGSize(width: scaledSize.width*scale, height: scaledSize.height*scale) + + guard let scaledUIImage = originalImage.imageByScaling(toSize: scaledSize) else { + scaledImage = nil + return + } + + scaledImage = CIImage(image: scaledUIImage) + } + } + + var scaledImage: CIImage?{ + didSet{ + updateImage() + } + } + + let context = CIContext() + + let locationManager = CLLocationManager() + + // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() - setImageViewHeight(with: 1.0) + originalImage = imageView.image + locationManager.delegate = self + locationManager.requestWhenInUseAuthorization() + } + + // MARK: - Methods + private func image(byFiltering image: CIImage) -> UIImage? { + let inputImage = image + + // Blur + let blurFilter = CIFilter.gaussianBlur() + blurFilter.inputImage = inputImage + blurFilter.radius = blurSlider.value + + // Sharpen + let sharpenFilter = CIFilter.sharpenLuminance() + sharpenFilter.inputImage = blurFilter.outputImage?.clampedToExtent() + sharpenFilter.sharpness = sharpenSlider.value + + // Vignette + let vignetteFilter = CIFilter.vignette() + vignetteFilter.inputImage = sharpenFilter.outputImage?.clampedToExtent() + vignetteFilter.intensity = vignetteSlider.value * 2 + vignetteFilter.radius = vignetteSlider.value * 100 + + // Sepia + let sepiaFilter = CIFilter.sepiaTone() + sepiaFilter.inputImage = vignetteFilter.outputImage?.clampedToExtent() + sepiaFilter.intensity = sepiaSlider.value + + // MonoChromatic + let monochromaticFilter = CIFilter.colorMonochrome() + monochromaticFilter.inputImage = sepiaFilter.outputImage?.clampedToExtent() + monochromaticFilter.intensity = monoChromaticSlider.value + + guard let outputImage = monochromaticFilter.outputImage else { return nil } + + guard let renderedCGImage = context.createCGImage(outputImage, from: inputImage.extent) else { return nil} + + return UIImage(cgImage: renderedCGImage) + } + private func updateImage() { + if let scaledImage = scaledImage { + imageView.image = image(byFiltering: scaledImage) + } else { + imageView.image = nil + } + } + + 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) + DispatchQueue.main.async { + let imagePicker = UIImagePickerController() + imagePicker.delegate = self + imagePicker.sourceType = .photoLibrary + + self.present(imagePicker, animated: true, completion: nil) + } + } + + @IBAction func locationSwitchIsOn(_ sender: UISwitch) { + if sender.isOn { + if CLLocationManager.locationServicesEnabled() { + locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters + locationManager.startUpdatingLocation() + } + } } @IBAction func createPost(_ sender: Any) { @@ -50,8 +152,10 @@ class ImagePostViewController: ShiftableViewController { presentInformationalAlertController(title: "Uh-oh", message: "Make sure that you add a photo and a caption before posting.") return } - - postController.createImagePost(with: title, image: image, ratio: image.ratio) + + let newLocation = locationManager.location?.coordinate + + postController.createImagePost(with: title, image: image, ratio: image.ratio, audioURL: nil, location: newLocation!) navigationController?.popViewController(animated: true) } @@ -96,24 +200,61 @@ class ImagePostViewController: ShiftableViewController { view.layoutSubviews() } + + // MARK: - IBActions + @IBAction func blurSliderChanged(_ sender: Any) { + updateImage() + } + + @IBAction func sharpenSliderChanged(_ sender: Any) { + updateImage() + } + + @IBAction func vignetteSliderChanged(_ sender: Any) { + updateImage() + } + + @IBAction func sepiaSliderChanged(_ sender: Any) { + updateImage() + } + + @IBAction func monoChromaticSliderChanged(_ sender: Any) { + updateImage() + } + } +// MARK: - Extenstions extension ImagePostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { - + chooseImageButton.setTitle("", for: []) - picker.dismiss(animated: true, completion: nil) + if let image = info[.editedImage] as? UIImage { + originalImage = image + } else if let image = info[.originalImage] as? UIImage { + originalImage = image + } - guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return } + picker.dismiss(animated: true, completion: nil) - imageView.image = image - setImageViewHeight(with: image.ratio) + // setImageViewHeight(with: image.ratio) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } + +extension ImagePostViewController: CLLocationManagerDelegate { + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return } + print("locations = \(locValue.latitude) \(locValue.longitude)") + } + + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { + print(error) + } +} diff --git a/LambdaTimeline/View Controllers/PostLocationViewController.swift b/LambdaTimeline/View Controllers/PostLocationViewController.swift new file mode 100644 index 00000000..87560045 --- /dev/null +++ b/LambdaTimeline/View Controllers/PostLocationViewController.swift @@ -0,0 +1,59 @@ +// +// PostLocationViewController.swift +// LambdaTimeline +// +// Created by Clayton Watkins on 9/10/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import MapKit + +class PostLocationViewController: UIViewController { + + // MARK: - IBOutlets + @IBOutlet weak var mapView: MKMapView! + + // MARK: - Properties + var location: CLLocationCoordinate2D? + var postTitle: String? + var postAuthor: String? + + // MARK: - Lifecycle + override func viewDidLoad() { + super.viewDidLoad() + mapView.mapType = .standard +// if let userLocation = location { +// let viewRegion = MKCoordinateRegion(center: userLocation, latitudinalMeters: 200, longitudinalMeters: 200) +// mapView.setRegion(viewRegion, animated: false) +// } + mapView.register(MKAnnotationView.self, forAnnotationViewWithReuseIdentifier: .annotationReuseIdentifier) + mapView.delegate = self + setPinUsingMKPointAnnotation(location: location!) + } + + func setPinUsingMKPointAnnotation(location: CLLocationCoordinate2D){ + let annotation = MKPointAnnotation() + annotation.coordinate = location + annotation.title = postTitle + annotation.subtitle = postAuthor + let coordinateRegion = MKCoordinateRegion(center: annotation.coordinate, latitudinalMeters: 200, longitudinalMeters: 200) + mapView.setRegion(coordinateRegion, animated: true) + mapView.addAnnotation(annotation) + } +} + +extension String { + static let annotationReuseIdentifier = "PostLocationView" +} + +extension PostLocationViewController: MKMapViewDelegate { + // func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { + // guard let post = annotation as? Post else { return nil } + // let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: .annotationReuseIdentifier, for: post) + // + // return annotationView + // } + + +} diff --git a/LambdaTimeline/View Controllers/PostsCollectionViewController.swift b/LambdaTimeline/View Controllers/PostsCollectionViewController.swift index b9ed6b54..55c81303 100644 --- a/LambdaTimeline/View Controllers/PostsCollectionViewController.swift +++ b/LambdaTimeline/View Controllers/PostsCollectionViewController.swift @@ -10,7 +10,7 @@ import UIKit class PostsCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { - var postController: PostController! + let postController = PostController.shared override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) @@ -37,7 +37,7 @@ class PostsCollectionViewController: UICollectionViewController, UICollectionVie // MARK: UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return postController?.posts.count ?? 0 + return postController.posts.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { @@ -85,7 +85,6 @@ class PostsCollectionViewController: UICollectionViewController, UICollectionVie override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "AddImagePost" { let destinationVC = segue.destination as? ImagePostViewController - destinationVC?.postController = postController } else if segue.identifier == "ViewImagePost" { @@ -93,7 +92,6 @@ class PostsCollectionViewController: UICollectionViewController, UICollectionVie guard let indexPath = collectionView.indexPathsForSelectedItems?.first else { return } - destinationVC?.postController = postController destinationVC?.post = postController.posts[indexPath.row] } } diff --git a/LambdaTimeline/View Controllers/SignInViewController.swift b/LambdaTimeline/View Controllers/SignInViewController.swift index c81bb748..997311f6 100644 --- a/LambdaTimeline/View Controllers/SignInViewController.swift +++ b/LambdaTimeline/View Controllers/SignInViewController.swift @@ -38,7 +38,6 @@ class SignInViewController: UIViewController { if segue.identifier == "ModalPostsVC" { guard let postsVC = (segue.destination as? UINavigationController)?.topViewController as? PostsCollectionViewController else { return } - postsVC.postController = postController } } } diff --git a/LambdaTimeline/Views/AudioCommentTableViewCell.swift b/LambdaTimeline/Views/AudioCommentTableViewCell.swift new file mode 100644 index 00000000..5fbd839d --- /dev/null +++ b/LambdaTimeline/Views/AudioCommentTableViewCell.swift @@ -0,0 +1,40 @@ +// +// AudioCommentTableViewCell.swift +// LambdaTimeline +// +// Created by Clayton Watkins on 9/4/20. +// Copyright © 2020 Lambda School. All rights reserved. +// + +import UIKit +import AVFoundation + +class AudioCommentTableViewCell: UITableViewCell { + + var recordingURL: URL? + var audioPlayer: AVAudioPlayer? + + @IBOutlet weak var usernameLabel: UILabel! + + func prepareAudioSession() throws { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playback, options: [.defaultToSpeaker]) + try session.setActive(true, options: []) // can fail if on a phone call, for instance + } + + @IBAction func playButtonTapped(_ sender: Any) { + print(recordingURL!) + do { + try prepareAudioSession() + if let recordingURL = recordingURL{ + print(recordingURL) + audioPlayer = try AVAudioPlayer(contentsOf: recordingURL) + guard let audioPlayer = self.audioPlayer else { return } + audioPlayer.play() + } + + } catch { + preconditionFailure("Failure to load audio file at path \(recordingURL!): \(error)") + } + } +}