diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..a1157f77 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,63 @@ +name: Build +on: + push: + branches: + - gmsapi + pull_request: + types: [opened, synchronize, reopened] +jobs: + sonarcloud: + name: SonarCloud + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: SonarCloud Scan + uses: SonarSource/sonarcloud-github-action@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + + buildwithSigning: + runs-on: macos-12 + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - name: Install the Apple certificate and provisioning profile + env: + BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }} + P12_PASSWORD: ${{ secrets.P12_PASSWORD }} + BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.BUILD_PROVISION_PROFILE_BASE64 }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + run: | + # create variables + CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12 + PP_PATH=$RUNNER_TEMP/build_pp.mobileprovision + KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db + # import certificate and provisioning profile from secrets + echo -n "$BUILD_CERTIFICATE_BASE64" | base64 --decode --output $CERTIFICATE_PATH + echo -n "$BUILD_PROVISION_PROFILE_BASE64" | base64 --decode --output $PP_PATH + # create temporary keychain + security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH + security set-keychain-settings -lut 21600 $KEYCHAIN_PATH + security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH + # import certificate to keychain + security import $CERTIFICATE_PATH -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH + security list-keychain -d user -s $KEYCHAIN_PATH + # apply provisioning profile + mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles + cp $PP_PATH ~/Library/MobileDevice/Provisioning\ Profiles + - name: Build and test app + run: | + pod install + xcodebuild build -workspace PushSDK.xcworkspace -scheme PushSDK -destination 'platform=iOS Simulator,OS=15.5,name=iPhone 13 Pro Max' + xcodebuild test -workspace PushSDK.xcworkspace -scheme PushSDKTests -destination 'platform=iOS Simulator,OS=15.5,name=iPhone 13 Pro Max' + + - name: Clean up keychain and provisioning profile + if: ${{ always() }} + run: | + security delete-keychain $RUNNER_TEMP/app-signing.keychain-db + rm ~/Library/MobileDevice/Provisioning\ Profiles/build_pp.mobileprovision diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b42048d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +/.build +Packages +Pods/ +Podfile.lock +.swiftpm/ \ No newline at end of file diff --git a/Podfile b/Podfile index 8b9358a0..2776d82f 100644 --- a/Podfile +++ b/Podfile @@ -25,26 +25,9 @@ target 'PushSDK' do #pod 'Firebase/Core' #pod 'FirebaseInstanceID' + target 'PushSDKTests' do - inherit! :search_paths # Pods for testing - #pod 'Firebase/Core' - #pod 'Firebase/Messaging' - #pod 'Firebase/Auth' - #pod 'Firebase/AdMob' - #pod 'Firebase/Database' - #pod 'Firebase/Storage' - #pod 'Firebase/Firestore' - #pod 'Google-Mobile-Ads-SDK' - pod 'BoringSSL-GRPC' - pod 'CryptoSwift' - pod 'JSON' - pod 'SwiftyBeaver' - pod 'Alamofire' - #pod 'Firebase/Messaging' - #pod 'Firebase/Installations' - #pod 'FirebaseCore' - #pod 'Firebase/Core' - #pod 'FirebaseInstanceID' end + end diff --git a/PushSDK.podspec b/PushSDK.podspec index 45839cc5..2da89f91 100644 --- a/PushSDK.podspec +++ b/PushSDK.podspec @@ -1,168 +1,39 @@ -# -# Be sure to run `pod spec lint sksdk.podspec' to ensure this is a -# valid spec and to remove all comments including this before submitting the spec. -# -# To learn more about Podspec attributes see https://docs.cocoapods.org/specification.html -# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ -# - -Pod::Spec.new do |spec| - - # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # These will help people to find your library, and whilst it - # can feel like a chore to fill in it's definitely to your advantage. The - # summary should be tweet-length, and the description more in depth. - # - - spec.name = "PushSDK" - spec.version = "1.0.0.44" - spec.summary = "SDK for sending push messages to iOS devices." - - # This description is used to generate tags and improve search results. - # * Think: What does it do? Why did you write it? What is the focus? - # * Try to keep it short, snappy and to the point. - # * Write the description between the DESC delimiters below. - # * Finally, don't worry about the indent, CocoaPods strips it! - spec.description = <<-DESC - This is SDK for Push messages - DESC - - spec.homepage = "https://github.com/kirillkotov/Push-SDK-IOS" - # spec.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" - - - # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Licensing your code is important. See https://choosealicense.com for more info. - # CocoaPods will detect a license file if there is a named LICENSE* - # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. - # - - spec.license = { :type => 'MIT', :file => 'LICENSE' } - # spec.license = { :type => "MIT", :file => "FILE_LICENSE" } - - - # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Specify the authors of the library, with email addresses. Email addresses - # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also - # accepts just a name if you'd rather not provide an email address. - # - # Specify a social_media_url where others can refer to, for example a twitter - # profile URL. - # - - spec.author = { "Push" => "kir.kotov5@gmail.com" } - - # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # If this Pod runs only on iOS or OS X, then specify the platform and - # the deployment target. You can optionally include the target after the platform. - # - - # spec.platform = :ios - # spec.platform = :ios, "5.0" - spec.platform = :ios, '10.0' - - # When using multiple platforms - # spec.ios.deployment_target = "5.0" - # spec.osx.deployment_target = "10.7" - # spec.watchos.deployment_target = "2.0" - # spec.tvos.deployment_target = "9.0" - - - # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Specify the location from where the source should be retrieved. - # Supports git, hg, bzr, svn and HTTP. - # - - spec.source = { :git => "https://github.com/kirillkotov/Push-SDK-IOS.git", :tag => "#{spec.version}" } - - - # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # CocoaPods is smart about how it includes source code. For source files - # giving a folder will include any swift, h, m, mm, c & cpp files. - # For header files it will include any header in the folder. - # Not including the public_header_files will make all headers public. - # - - spec.source_files = "Classes", "Classes/**/*.{h,m}", "PushSDK/*.{h,m}", "PushSDK", "PushSDK/api", "PushSDK/core", "PushSDK/settings", "PushSDK/firebase", "PushSDK/models" - spec.exclude_files = "Classes/Exclude" - - # spec.public_header_files = "Classes/**/*.h" - - - # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # A list of resources included with the Pod. These are copied into the - # target bundle with a build phase script. Anything else will be cleaned. - # You can preserve files from being cleaned, please don't preserve - # non-essential files like tests, examples and documentation. - # - - # spec.resource = "icon.png" - # spec.resources = "Resources/*.png" - - # spec.preserve_paths = "FilesToSave", "MoreFilesToSave" - - - # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # Link your library with frameworks, or libraries. Libraries do not include - # the lib prefix of their name. - # - - # spec.framework = "SomeFramework" - # spec.frameworks = "SomeFramework", "AnotherFramework" - - spec.swift_version = ['3.0', '4.0', '4.2', '5.0', '5.1'] - - spec.static_framework = true - - - - spec.dependency "BoringSSL-GRPC" - #spec.dependency "BoringSSL-GRPC" - spec.dependency "CryptoSwift", "1.4.0" - spec.dependency "SwiftyJSON", "5.0.0" - spec.dependency "JSON", "5.0.0" - spec.dependency 'SwiftyBeaver', "1.9.2" - spec.dependency 'Firebase/Messaging' - #spec.dependency 'FirebaseCore' - spec.dependency 'Firebase/Installations' - #spec.dependency 'FirebaseInstanceID' - spec.dependency 'Alamofire' +Pod::Spec.new do |s| + s.name = "PushSDK" + s.version = "1.0.0.45" + s.summary = "SDK for sending push messages to iOS devices." + s.homepage = "https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS" - - # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - # - # If your library depends on compiler flags you can set them in the xcconfig hash - # where they will only apply to your library. If you depend on other Podspecs - # you can include multiple dependencies to ensure it works. - - # spec.requires_arc = true - spec.requires_arc = true - - spec.xcconfig = { 'LIBRARY_SEARCH_PATHS' => "$(SRCROOT)/Pods/**" } - - spec.pod_target_xcconfig = { - 'OTHER_LDFLAGS' => '$(inherited) -ObjC' - } - - - #spec.subspec 'Core' do |core| - # core.platform = :ios, '8.0' - # core.public_header_files = 'Core/FirebaseCore/*.h' - # core.source_files = 'Core/FirebaseCore/*.{h,m}' - # core.dependency 'Firebase/Core' - # core.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/PushSDK/FirebaseCore' } - #end + + #s.license = { :type => 'MIT', :file => 'LICENSE' } + + + s.author = { "o.korniienko" => "o.korniienko@gms-worldwide.com" } + s.source = { :git => "https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS.git", :tag => s.version.to_s} + + + s.platform = :ios, '13.0' + s.requires_arc = true + + s.swift_version = ['3.0', '4.0', '4.2', '5.0', '5.1'] + + #s.source_files = 'PushSDKIOS/**/*.{swift}' + s.source_files = "Classes", "Classes/**/*.{h,m}", "PushSDK/*.{h,m}", "PushSDK/*.swift", "PushSDK/api", "PushSDK/core", "PushSDK/settings", "PushSDK/firebase", "PushSDK/models" - # spec.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } - # spec.dependency "JSONKit", "~> 1.4" + +s.dependency "BoringSSL-GRPC" +#s.dependency "BoringSSL-GRPC" +s.dependency "CryptoSwift" +s.dependency "SwiftyJSON", "5.0.0" +s.dependency "JSON", "5.0.0" +s.dependency 'SwiftyBeaver', "1.9.2" +s.dependency 'Firebase/Messaging' +#.dependency 'FirebaseCore' +s.dependency 'Firebase/Installations' +#s.dependency 'FirebaseInstanceID' +s.dependency 'Alamofire' + + end diff --git a/PushSDK.xcodeproj/project.pbxproj b/PushSDK.xcodeproj/project.pbxproj index 483fba78..f85c0251 100644 --- a/PushSDK.xcodeproj/project.pbxproj +++ b/PushSDK.xcodeproj/project.pbxproj @@ -3,236 +3,213 @@ archiveVersion = 1; classes = { }; - objectVersion = 51; + objectVersion = 55; objects = { /* Begin PBXBuildFile section */ - 11F110D62AAAFBD642E927CF /* Pods_PushSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 140306593DA75B413DE05549 /* Pods_PushSDK.framework */; }; - A6B9A8A20B93925DA2CDFE5A /* Pods_PushSDKTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 63E76706A3F5E5229C1EE088 /* Pods_PushSDKTests.framework */; }; - BA48A2DC255FF77A00748CAA /* Podfile in Resources */ = {isa = PBXBuildFile; fileRef = BA48A2DB255FF77A00748CAA /* Podfile */; }; - BA48A2DE2560895500748CAA /* PushSDK.podspec in Resources */ = {isa = PBXBuildFile; fileRef = BA48A2DD2560895500748CAA /* PushSDK.podspec */; }; - BA5DBF76256DDFDE00590993 /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = BA5DBF75256DDFDE00590993 /* README.md */; }; - BA7283C8256D74BC00509E06 /* DataStructures.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7283C7256D74BC00509E06 /* DataStructures.swift */; }; - BA7283CD256D771200509E06 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7283CC256D771200509E06 /* Extensions.swift */; }; - BA7283D3256D7C8B00509E06 /* MemorySaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7283D2256D7C8B00509E06 /* MemorySaver.swift */; }; - BA7283DF256D820600509E06 /* PushAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7283DE256D820600509E06 /* PushAdapter.swift */; }; - BA7283E3256D825E00509E06 /* JsonParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA7283E2256D825E00509E06 /* JsonParser.swift */; }; - BA728675256DB83900509E06 /* PushSDKFirebase.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA728674256DB83900509E06 /* PushSDKFirebase.swift */; }; - BAA1F2512570425E00728318 /* FirebaseHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAA1F2502570425E00728318 /* FirebaseHelpers.swift */; }; - BAB6CB0A2558FA59007A4C56 /* PushSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BAB6CB002558FA59007A4C56 /* PushSDK.framework */; }; - BAB6CB0F2558FA59007A4C56 /* PushSDKTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB0E2558FA59007A4C56 /* PushSDKTests.swift */; }; - BAB6CB112558FA59007A4C56 /* PushSDK.h in Headers */ = {isa = PBXBuildFile; fileRef = BAB6CB032558FA59007A4C56 /* PushSDK.h */; settings = {ATTRIBUTES = (Public, ); }; }; - BAB6CB1B2558FAD5007A4C56 /* PushSDK.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB1A2558FAD5007A4C56 /* PushSDK.swift */; }; - BAB6CB1D2558FAE2007A4C56 /* BridgingHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = BAB6CB1C2558FAE2007A4C56 /* BridgingHeader.h */; }; - BAB6CB2B2558FBF0007A4C56 /* Params.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB272558FBF0007A4C56 /* Params.swift */; }; - BAB6CB2C2558FBF0007A4C56 /* PushAnswerFunc.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB282558FBF0007A4C56 /* PushAnswerFunc.swift */; }; - BAB6CB2D2558FBF0007A4C56 /* AddFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB292558FBF0007A4C56 /* AddFunctions.swift */; }; - BAB6CB302559036A007A4C56 /* Parser.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAB6CB2F2559036A007A4C56 /* Parser.swift */; }; - BAC30CCE25623AE300559536 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAC30CCD25623AE300559536 /* Notifications.swift */; }; + 01FCADDA28C0C15E00D77FA4 /* PushSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 01FCADD128C0C15E00D77FA4 /* PushSDK.framework */; }; + 01FCADDF28C0C15E00D77FA4 /* PushSDKTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADDE28C0C15E00D77FA4 /* PushSDKTests.swift */; }; + 01FCADE028C0C15E00D77FA4 /* PushSDK.h in Headers */ = {isa = PBXBuildFile; fileRef = 01FCADD428C0C15E00D77FA4 /* PushSDK.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 01FCADF928C0C27D00D77FA4 /* PushSDKFirebase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADE928C0C27C00D77FA4 /* PushSDKFirebase.swift */; }; + 01FCADFA28C0C27D00D77FA4 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADEB28C0C27C00D77FA4 /* Extensions.swift */; }; + 01FCADFB28C0C27D00D77FA4 /* PushConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADEC28C0C27C00D77FA4 /* PushConstants.swift */; }; + 01FCADFC28C0C27D00D77FA4 /* PushAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADEE28C0C27D00D77FA4 /* PushAdapter.swift */; }; + 01FCADFD28C0C27D00D77FA4 /* AnswerBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF028C0C27D00D77FA4 /* AnswerBuilder.swift */; }; + 01FCADFE28C0C27D00D77FA4 /* DataSaver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF128C0C27D00D77FA4 /* DataSaver.swift */; }; + 01FCADFF28C0C27D00D77FA4 /* Parser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF228C0C27D00D77FA4 /* Parser.swift */; }; + 01FCAE0028C0C27D00D77FA4 /* JsonParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF328C0C27D00D77FA4 /* JsonParser.swift */; }; + 01FCAE0128C0C27D00D77FA4 /* DataStructures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF528C0C27D00D77FA4 /* DataStructures.swift */; }; + 01FCAE0228C0C27D00D77FA4 /* PushSDK.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF628C0C27D00D77FA4 /* PushSDK.swift */; }; + 01FCAE0328C0C27D00D77FA4 /* FireBaseHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01FCADF828C0C27D00D77FA4 /* FireBaseHelpers.swift */; }; + 593D0818C1A7FD450EF82F47 /* Pods_PushSDK_PushSDKTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A2B845CD28A7D9D2EDDC584D /* Pods_PushSDK_PushSDKTests.framework */; }; + 6C52BA53CC2ADC475B3D1AF7 /* Pods_PushSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ED9E39E9B478D971E1E64ABD /* Pods_PushSDK.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - BAB6CB0B2558FA59007A4C56 /* PBXContainerItemProxy */ = { + 01FCADDB28C0C15E00D77FA4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = BAB6CAF72558FA59007A4C56 /* Project object */; + containerPortal = 01FCADC828C0C15E00D77FA4 /* Project object */; proxyType = 1; - remoteGlobalIDString = BAB6CAFF2558FA59007A4C56; + remoteGlobalIDString = 01FCADD028C0C15E00D77FA4; remoteInfo = PushSDK; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 140306593DA75B413DE05549 /* Pods_PushSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PushSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 27EBCAC057364D579C92EB06 /* Pods-PushSDKTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDKTests.debug.xcconfig"; path = "Target Support Files/Pods-PushSDKTests/Pods-PushSDKTests.debug.xcconfig"; sourceTree = ""; }; - 296C18064AF63D7FD04C7F5B /* Pods-PushSDKTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDKTests.release.xcconfig"; path = "Target Support Files/Pods-PushSDKTests/Pods-PushSDKTests.release.xcconfig"; sourceTree = ""; }; - 60C41E10609C942F177AC5D7 /* Pods-PushSDK.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK.release.xcconfig"; path = "Target Support Files/Pods-PushSDK/Pods-PushSDK.release.xcconfig"; sourceTree = ""; }; - 63E76706A3F5E5229C1EE088 /* Pods_PushSDKTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PushSDKTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 9D23197EF21667D931631324 /* Pods-PushSDK.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK.debug.xcconfig"; path = "Target Support Files/Pods-PushSDK/Pods-PushSDK.debug.xcconfig"; sourceTree = ""; }; - BA48A2DB255FF77A00748CAA /* Podfile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Podfile; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - BA48A2DD2560895500748CAA /* PushSDK.podspec */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = PushSDK.podspec; sourceTree = ""; }; - BA5DBF75256DDFDE00590993 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; - BA7283C7256D74BC00509E06 /* DataStructures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataStructures.swift; sourceTree = ""; }; - BA7283CC256D771200509E06 /* Extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; - BA7283D2256D7C8B00509E06 /* MemorySaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemorySaver.swift; sourceTree = ""; }; - BA7283DE256D820600509E06 /* PushAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushAdapter.swift; sourceTree = ""; }; - BA7283E2256D825E00509E06 /* JsonParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JsonParser.swift; sourceTree = ""; }; - BA728674256DB83900509E06 /* PushSDKFirebase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushSDKFirebase.swift; sourceTree = ""; }; - BAA1F2502570425E00728318 /* FirebaseHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirebaseHelpers.swift; sourceTree = ""; }; - BAB6CB002558FA59007A4C56 /* PushSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PushSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - BAB6CB032558FA59007A4C56 /* PushSDK.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PushSDK.h; sourceTree = ""; }; - BAB6CB042558FA59007A4C56 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BAB6CB092558FA59007A4C56 /* PushSDKTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PushSDKTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - BAB6CB0E2558FA59007A4C56 /* PushSDKTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushSDKTests.swift; sourceTree = ""; }; - BAB6CB102558FA59007A4C56 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - BAB6CB1A2558FAD5007A4C56 /* PushSDK.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushSDK.swift; sourceTree = ""; }; - BAB6CB1C2558FAE2007A4C56 /* BridgingHeader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BridgingHeader.h; sourceTree = ""; }; - BAB6CB272558FBF0007A4C56 /* Params.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Params.swift; sourceTree = ""; }; - BAB6CB282558FBF0007A4C56 /* PushAnswerFunc.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushAnswerFunc.swift; sourceTree = ""; }; - BAB6CB292558FBF0007A4C56 /* AddFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AddFunctions.swift; sourceTree = ""; }; - BAB6CB2F2559036A007A4C56 /* Parser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Parser.swift; sourceTree = ""; }; - BAC30CCD25623AE300559536 /* Notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifications.swift; sourceTree = ""; }; + 01FCADD128C0C15E00D77FA4 /* PushSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PushSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 01FCADD428C0C15E00D77FA4 /* PushSDK.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PushSDK.h; sourceTree = ""; }; + 01FCADD928C0C15E00D77FA4 /* PushSDKTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PushSDKTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 01FCADDE28C0C15E00D77FA4 /* PushSDKTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushSDKTests.swift; sourceTree = ""; }; + 01FCADE928C0C27C00D77FA4 /* PushSDKFirebase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushSDKFirebase.swift; sourceTree = ""; }; + 01FCADEB28C0C27C00D77FA4 /* Extensions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Extensions.swift; sourceTree = ""; }; + 01FCADEC28C0C27C00D77FA4 /* PushConstants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushConstants.swift; sourceTree = ""; }; + 01FCADEE28C0C27D00D77FA4 /* PushAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushAdapter.swift; sourceTree = ""; }; + 01FCADF028C0C27D00D77FA4 /* AnswerBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnswerBuilder.swift; sourceTree = ""; }; + 01FCADF128C0C27D00D77FA4 /* DataSaver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataSaver.swift; sourceTree = ""; }; + 01FCADF228C0C27D00D77FA4 /* Parser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Parser.swift; sourceTree = ""; }; + 01FCADF328C0C27D00D77FA4 /* JsonParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JsonParser.swift; sourceTree = ""; }; + 01FCADF528C0C27D00D77FA4 /* DataStructures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataStructures.swift; sourceTree = ""; }; + 01FCADF628C0C27D00D77FA4 /* PushSDK.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushSDK.swift; sourceTree = ""; }; + 01FCADF828C0C27D00D77FA4 /* FireBaseHelpers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FireBaseHelpers.swift; sourceTree = ""; }; + 9765B5F0A65CA6F0C55A43C9 /* Pods-PushSDK.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK.release.xcconfig"; path = "Target Support Files/Pods-PushSDK/Pods-PushSDK.release.xcconfig"; sourceTree = ""; }; + A2B845CD28A7D9D2EDDC584D /* Pods_PushSDK_PushSDKTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PushSDK_PushSDKTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C0C94F0280591F339FDAE7CE /* Pods-PushSDK.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK.debug.xcconfig"; path = "Target Support Files/Pods-PushSDK/Pods-PushSDK.debug.xcconfig"; sourceTree = ""; }; + D82D31A58B1C1FA747FC02EA /* Pods-PushSDK-PushSDKTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK-PushSDKTests.release.xcconfig"; path = "Target Support Files/Pods-PushSDK-PushSDKTests/Pods-PushSDK-PushSDKTests.release.xcconfig"; sourceTree = ""; }; + ED9E39E9B478D971E1E64ABD /* Pods_PushSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PushSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + EF12FE5BF376817136B02DB0 /* Pods-PushSDK-PushSDKTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PushSDK-PushSDKTests.debug.xcconfig"; path = "Target Support Files/Pods-PushSDK-PushSDKTests/Pods-PushSDK-PushSDKTests.debug.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - BAB6CAFD2558FA59007A4C56 /* Frameworks */ = { + 01FCADCE28C0C15E00D77FA4 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 11F110D62AAAFBD642E927CF /* Pods_PushSDK.framework in Frameworks */, + 6C52BA53CC2ADC475B3D1AF7 /* Pods_PushSDK.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - BAB6CB062558FA59007A4C56 /* Frameworks */ = { + 01FCADD628C0C15E00D77FA4 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - BAB6CB0A2558FA59007A4C56 /* PushSDK.framework in Frameworks */, - A6B9A8A20B93925DA2CDFE5A /* Pods_PushSDKTests.framework in Frameworks */, + 01FCADDA28C0C15E00D77FA4 /* PushSDK.framework in Frameworks */, + 593D0818C1A7FD450EF82F47 /* Pods_PushSDK_PushSDKTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 167F6E8451F83E52643B5759 /* Pods */ = { + 01FCADC728C0C15E00D77FA4 = { isa = PBXGroup; children = ( - 9D23197EF21667D931631324 /* Pods-PushSDK.debug.xcconfig */, - 60C41E10609C942F177AC5D7 /* Pods-PushSDK.release.xcconfig */, - 27EBCAC057364D579C92EB06 /* Pods-PushSDKTests.debug.xcconfig */, - 296C18064AF63D7FD04C7F5B /* Pods-PushSDKTests.release.xcconfig */, + 01FCADD328C0C15E00D77FA4 /* PushSDK */, + 01FCADDD28C0C15E00D77FA4 /* PushSDKTests */, + 01FCADD228C0C15E00D77FA4 /* Products */, + B561EDE5DFE8F38A29372126 /* Pods */, + 362A17525B851AE82AA1202E /* Frameworks */, ); - path = Pods; sourceTree = ""; }; - 5A27835A7DD2683BDCC31FA2 /* Frameworks */ = { + 01FCADD228C0C15E00D77FA4 /* Products */ = { isa = PBXGroup; children = ( - 140306593DA75B413DE05549 /* Pods_PushSDK.framework */, - 63E76706A3F5E5229C1EE088 /* Pods_PushSDKTests.framework */, + 01FCADD128C0C15E00D77FA4 /* PushSDK.framework */, + 01FCADD928C0C15E00D77FA4 /* PushSDKTests.xctest */, ); - name = Frameworks; + name = Products; sourceTree = ""; }; - BA7283C6256D748100509E06 /* models */ = { + 01FCADD328C0C15E00D77FA4 /* PushSDK */ = { isa = PBXGroup; children = ( - BA7283C7256D74BC00509E06 /* DataStructures.swift */, + 01FCADED28C0C27D00D77FA4 /* api */, + 01FCADEF28C0C27D00D77FA4 /* core */, + 01FCADF728C0C27D00D77FA4 /* firebase */, + 01FCADF428C0C27D00D77FA4 /* models */, + 01FCADF628C0C27D00D77FA4 /* PushSDK.swift */, + 01FCADE928C0C27C00D77FA4 /* PushSDKFirebase.swift */, + 01FCADEA28C0C27C00D77FA4 /* settings */, + 01FCADD428C0C15E00D77FA4 /* PushSDK.h */, ); - path = models; + path = PushSDK; sourceTree = ""; }; - BAA1F24F2570424D00728318 /* firebase */ = { + 01FCADDD28C0C15E00D77FA4 /* PushSDKTests */ = { isa = PBXGroup; children = ( - BAA1F2502570425E00728318 /* FirebaseHelpers.swift */, + 01FCADDE28C0C15E00D77FA4 /* PushSDKTests.swift */, ); - path = firebase; + path = PushSDKTests; sourceTree = ""; }; - BAB6CAF62558FA59007A4C56 = { + 01FCADEA28C0C27C00D77FA4 /* settings */ = { isa = PBXGroup; children = ( - BA5DBF75256DDFDE00590993 /* README.md */, - BA48A2DD2560895500748CAA /* PushSDK.podspec */, - BA48A2DB255FF77A00748CAA /* Podfile */, - BAB6CB022558FA59007A4C56 /* PushSDK */, - BAB6CB0D2558FA59007A4C56 /* PushSDKTests */, - BAB6CB012558FA59007A4C56 /* Products */, - 167F6E8451F83E52643B5759 /* Pods */, - 5A27835A7DD2683BDCC31FA2 /* Frameworks */, + 01FCADEB28C0C27C00D77FA4 /* Extensions.swift */, + 01FCADEC28C0C27C00D77FA4 /* PushConstants.swift */, ); + path = settings; sourceTree = ""; }; - BAB6CB012558FA59007A4C56 /* Products */ = { + 01FCADED28C0C27D00D77FA4 /* api */ = { isa = PBXGroup; children = ( - BAB6CB002558FA59007A4C56 /* PushSDK.framework */, - BAB6CB092558FA59007A4C56 /* PushSDKTests.xctest */, + 01FCADEE28C0C27D00D77FA4 /* PushAdapter.swift */, ); - name = Products; + path = api; sourceTree = ""; }; - BAB6CB022558FA59007A4C56 /* PushSDK */ = { + 01FCADEF28C0C27D00D77FA4 /* core */ = { isa = PBXGroup; children = ( - BAA1F24F2570424D00728318 /* firebase */, - BA7283C6256D748100509E06 /* models */, - BAB6CB2E25590354007A4C56 /* core */, - BAB6CB232558FB3D007A4C56 /* settings */, - BAB6CB222558FB35007A4C56 /* api */, - BAB6CB1C2558FAE2007A4C56 /* BridgingHeader.h */, - BAB6CB1A2558FAD5007A4C56 /* PushSDK.swift */, - BAB6CB032558FA59007A4C56 /* PushSDK.h */, - BAB6CB042558FA59007A4C56 /* Info.plist */, - BA7283CC256D771200509E06 /* Extensions.swift */, - BA728674256DB83900509E06 /* PushSDKFirebase.swift */, + 01FCADF028C0C27D00D77FA4 /* AnswerBuilder.swift */, + 01FCADF128C0C27D00D77FA4 /* DataSaver.swift */, + 01FCADF228C0C27D00D77FA4 /* Parser.swift */, + 01FCADF328C0C27D00D77FA4 /* JsonParser.swift */, ); - path = PushSDK; + path = core; sourceTree = ""; }; - BAB6CB0D2558FA59007A4C56 /* PushSDKTests */ = { + 01FCADF428C0C27D00D77FA4 /* models */ = { isa = PBXGroup; children = ( - BAB6CB0E2558FA59007A4C56 /* PushSDKTests.swift */, - BAB6CB102558FA59007A4C56 /* Info.plist */, + 01FCADF528C0C27D00D77FA4 /* DataStructures.swift */, ); - path = PushSDKTests; + path = models; sourceTree = ""; }; - BAB6CB222558FB35007A4C56 /* api */ = { + 01FCADF728C0C27D00D77FA4 /* firebase */ = { isa = PBXGroup; children = ( - BA7283DE256D820600509E06 /* PushAdapter.swift */, + 01FCADF828C0C27D00D77FA4 /* FireBaseHelpers.swift */, ); - path = api; + path = firebase; sourceTree = ""; }; - BAB6CB232558FB3D007A4C56 /* settings */ = { + 362A17525B851AE82AA1202E /* Frameworks */ = { isa = PBXGroup; children = ( - BAB6CB292558FBF0007A4C56 /* AddFunctions.swift */, - BAB6CB272558FBF0007A4C56 /* Params.swift */, - BAB6CB282558FBF0007A4C56 /* PushAnswerFunc.swift */, - BA7283E2256D825E00509E06 /* JsonParser.swift */, + ED9E39E9B478D971E1E64ABD /* Pods_PushSDK.framework */, + A2B845CD28A7D9D2EDDC584D /* Pods_PushSDK_PushSDKTests.framework */, ); - path = settings; + name = Frameworks; sourceTree = ""; }; - BAB6CB2E25590354007A4C56 /* core */ = { + B561EDE5DFE8F38A29372126 /* Pods */ = { isa = PBXGroup; children = ( - BAB6CB2F2559036A007A4C56 /* Parser.swift */, - BAC30CCD25623AE300559536 /* Notifications.swift */, - BA7283D2256D7C8B00509E06 /* MemorySaver.swift */, + C0C94F0280591F339FDAE7CE /* Pods-PushSDK.debug.xcconfig */, + 9765B5F0A65CA6F0C55A43C9 /* Pods-PushSDK.release.xcconfig */, + EF12FE5BF376817136B02DB0 /* Pods-PushSDK-PushSDKTests.debug.xcconfig */, + D82D31A58B1C1FA747FC02EA /* Pods-PushSDK-PushSDKTests.release.xcconfig */, ); - path = core; + path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ - BAB6CAFB2558FA59007A4C56 /* Headers */ = { + 01FCADCC28C0C15E00D77FA4 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - BAB6CB112558FA59007A4C56 /* PushSDK.h in Headers */, - BAB6CB1D2558FAE2007A4C56 /* BridgingHeader.h in Headers */, + 01FCADE028C0C15E00D77FA4 /* PushSDK.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ - BAB6CAFF2558FA59007A4C56 /* PushSDK */ = { + 01FCADD028C0C15E00D77FA4 /* PushSDK */ = { isa = PBXNativeTarget; - buildConfigurationList = BAB6CB142558FA59007A4C56 /* Build configuration list for PBXNativeTarget "PushSDK" */; + buildConfigurationList = 01FCADE328C0C15E00D77FA4 /* Build configuration list for PBXNativeTarget "PushSDK" */; buildPhases = ( - BF2B6D2F0759940431DDB682 /* [CP] Check Pods Manifest.lock */, - BAB6CAFB2558FA59007A4C56 /* Headers */, - BAB6CAFC2558FA59007A4C56 /* Sources */, - BAB6CAFD2558FA59007A4C56 /* Frameworks */, - BAB6CAFE2558FA59007A4C56 /* Resources */, + 94996B150B98415AFF28F360 /* [CP] Check Pods Manifest.lock */, + 01FCADCC28C0C15E00D77FA4 /* Headers */, + 01FCADCD28C0C15E00D77FA4 /* Sources */, + 01FCADCE28C0C15E00D77FA4 /* Frameworks */, + 01FCADCF28C0C15E00D77FA4 /* Resources */, ); buildRules = ( ); @@ -240,79 +217,76 @@ ); name = PushSDK; productName = PushSDK; - productReference = BAB6CB002558FA59007A4C56 /* PushSDK.framework */; + productReference = 01FCADD128C0C15E00D77FA4 /* PushSDK.framework */; productType = "com.apple.product-type.framework"; }; - BAB6CB082558FA59007A4C56 /* PushSDKTests */ = { + 01FCADD828C0C15E00D77FA4 /* PushSDKTests */ = { isa = PBXNativeTarget; - buildConfigurationList = BAB6CB172558FA59007A4C56 /* Build configuration list for PBXNativeTarget "PushSDKTests" */; + buildConfigurationList = 01FCADE628C0C15E00D77FA4 /* Build configuration list for PBXNativeTarget "PushSDKTests" */; buildPhases = ( - BEFDB269068DAC32CD407791 /* [CP] Check Pods Manifest.lock */, - BAB6CB052558FA59007A4C56 /* Sources */, - BAB6CB062558FA59007A4C56 /* Frameworks */, - BAB6CB072558FA59007A4C56 /* Resources */, - 15C22FABF9B4C8320D9C1055 /* [CP] Embed Pods Frameworks */, + 4ED250DE43D39191F162AC13 /* [CP] Check Pods Manifest.lock */, + 01FCADD528C0C15E00D77FA4 /* Sources */, + 01FCADD628C0C15E00D77FA4 /* Frameworks */, + 01FCADD728C0C15E00D77FA4 /* Resources */, + DDDAEC34363CACA514258EC8 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( - BAB6CB0C2558FA59007A4C56 /* PBXTargetDependency */, + 01FCADDC28C0C15E00D77FA4 /* PBXTargetDependency */, ); name = PushSDKTests; productName = PushSDKTests; - productReference = BAB6CB092558FA59007A4C56 /* PushSDKTests.xctest */; + productReference = 01FCADD928C0C15E00D77FA4 /* PushSDKTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ - BAB6CAF72558FA59007A4C56 /* Project object */ = { + 01FCADC828C0C15E00D77FA4 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 1020; - LastUpgradeCheck = 1220; - ORGANIZATIONNAME = PUSHER; + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1340; + LastUpgradeCheck = 1340; TargetAttributes = { - BAB6CAFF2558FA59007A4C56 = { - CreatedOnToolsVersion = 10.2.1; - LastSwiftMigration = 1020; + 01FCADD028C0C15E00D77FA4 = { + CreatedOnToolsVersion = 13.4.1; + LastSwiftMigration = 1340; }; - BAB6CB082558FA59007A4C56 = { - CreatedOnToolsVersion = 10.2.1; + 01FCADD828C0C15E00D77FA4 = { + CreatedOnToolsVersion = 13.4.1; }; }; }; - buildConfigurationList = BAB6CAFA2558FA59007A4C56 /* Build configuration list for PBXProject "PushSDK" */; - compatibilityVersion = "Xcode 9.3"; + buildConfigurationList = 01FCADCB28C0C15E00D77FA4 /* Build configuration list for PBXProject "PushSDK" */; + compatibilityVersion = "Xcode 13.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); - mainGroup = BAB6CAF62558FA59007A4C56; - productRefGroup = BAB6CB012558FA59007A4C56 /* Products */; + mainGroup = 01FCADC728C0C15E00D77FA4; + productRefGroup = 01FCADD228C0C15E00D77FA4 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( - BAB6CAFF2558FA59007A4C56 /* PushSDK */, - BAB6CB082558FA59007A4C56 /* PushSDKTests */, + 01FCADD028C0C15E00D77FA4 /* PushSDK */, + 01FCADD828C0C15E00D77FA4 /* PushSDKTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - BAB6CAFE2558FA59007A4C56 /* Resources */ = { + 01FCADCF28C0C15E00D77FA4 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - BA5DBF76256DDFDE00590993 /* README.md in Resources */, - BA48A2DC255FF77A00748CAA /* Podfile in Resources */, - BA48A2DE2560895500748CAA /* PushSDK.podspec in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; - BAB6CB072558FA59007A4C56 /* Resources */ = { + 01FCADD728C0C15E00D77FA4 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -322,24 +296,29 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 15C22FABF9B4C8320D9C1055 /* [CP] Embed Pods Frameworks */ = { + 4ED250DE43D39191F162AC13 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-PushSDKTests/Pods-PushSDKTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - name = "[CP] Embed Pods Frameworks"; + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-PushSDKTests/Pods-PushSDKTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-PushSDK-PushSDKTests-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-PushSDKTests/Pods-PushSDKTests-frameworks.sh\"\n"; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - BEFDB269068DAC32CD407791 /* [CP] Check Pods Manifest.lock */ = { + 94996B150B98415AFF28F360 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -354,85 +333,77 @@ outputFileListPaths = ( ); outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-PushSDKTests-checkManifestLockResult.txt", + "$(DERIVED_FILE_DIR)/Pods-PushSDK-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; - BF2B6D2F0759940431DDB682 /* [CP] Check Pods Manifest.lock */ = { + DDDAEC34363CACA514258EC8 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-PushSDK-PushSDKTests/Pods-PushSDK-PushSDKTests-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; + name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-PushSDK-checkManifestLockResult.txt", + "${PODS_ROOT}/Target Support Files/Pods-PushSDK-PushSDKTests/Pods-PushSDK-PushSDKTests-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-PushSDK-PushSDKTests/Pods-PushSDK-PushSDKTests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - BAB6CAFC2558FA59007A4C56 /* Sources */ = { + 01FCADCD28C0C15E00D77FA4 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - BAC30CCE25623AE300559536 /* Notifications.swift in Sources */, - BAA1F2512570425E00728318 /* FirebaseHelpers.swift in Sources */, - BA7283D3256D7C8B00509E06 /* MemorySaver.swift in Sources */, - BAB6CB302559036A007A4C56 /* Parser.swift in Sources */, - BAB6CB2C2558FBF0007A4C56 /* PushAnswerFunc.swift in Sources */, - BA728675256DB83900509E06 /* PushSDKFirebase.swift in Sources */, - BAB6CB1B2558FAD5007A4C56 /* PushSDK.swift in Sources */, - BA7283C8256D74BC00509E06 /* DataStructures.swift in Sources */, - BA7283CD256D771200509E06 /* Extensions.swift in Sources */, - BA7283DF256D820600509E06 /* PushAdapter.swift in Sources */, - BAB6CB2B2558FBF0007A4C56 /* Params.swift in Sources */, - BAB6CB2D2558FBF0007A4C56 /* AddFunctions.swift in Sources */, - BA7283E3256D825E00509E06 /* JsonParser.swift in Sources */, + 01FCAE0128C0C27D00D77FA4 /* DataStructures.swift in Sources */, + 01FCADFB28C0C27D00D77FA4 /* PushConstants.swift in Sources */, + 01FCADFD28C0C27D00D77FA4 /* AnswerBuilder.swift in Sources */, + 01FCAE0028C0C27D00D77FA4 /* JsonParser.swift in Sources */, + 01FCADFC28C0C27D00D77FA4 /* PushAdapter.swift in Sources */, + 01FCADFE28C0C27D00D77FA4 /* DataSaver.swift in Sources */, + 01FCAE0328C0C27D00D77FA4 /* FireBaseHelpers.swift in Sources */, + 01FCAE0228C0C27D00D77FA4 /* PushSDK.swift in Sources */, + 01FCADF928C0C27D00D77FA4 /* PushSDKFirebase.swift in Sources */, + 01FCADFA28C0C27D00D77FA4 /* Extensions.swift in Sources */, + 01FCADFF28C0C27D00D77FA4 /* Parser.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - BAB6CB052558FA59007A4C56 /* Sources */ = { + 01FCADD528C0C15E00D77FA4 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - BAB6CB0F2558FA59007A4C56 /* PushSDKTests.swift in Sources */, + 01FCADDF28C0C15E00D77FA4 /* PushSDKTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - BAB6CB0C2558FA59007A4C56 /* PBXTargetDependency */ = { + 01FCADDC28C0C15E00D77FA4 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - target = BAB6CAFF2558FA59007A4C56 /* PushSDK */; - targetProxy = BAB6CB0B2558FA59007A4C56 /* PBXContainerItemProxy */; + target = 01FCADD028C0C15E00D77FA4 /* PushSDK */; + targetProxy = 01FCADDB28C0C15E00D77FA4 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ - BAB6CB122558FA59007A4C56 /* Debug */ = { + 01FCADE128C0C15E00D77FA4 /* 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_CXX_LANGUAGE_STANDARD = "gnu++17"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; @@ -458,7 +429,6 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer"; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; @@ -478,7 +448,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.2; + IPHONEOS_DEPLOYMENT_TARGET = 15.5; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -490,14 +460,13 @@ }; name = Debug; }; - BAB6CB132558FA59007A4C56 /* Release */ = { + 01FCADE228C0C15E00D77FA4 /* 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_CXX_LANGUAGE_STANDARD = "gnu++17"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_WEAK = YES; @@ -523,7 +492,6 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer"; COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -537,7 +505,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.2; + IPHONEOS_DEPLOYMENT_TARGET = 15.5; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; @@ -549,96 +517,100 @@ }; name = Release; }; - BAB6CB152558FA59007A4C56 /* Debug */ = { + 01FCADE428C0C15E00D77FA4 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9D23197EF21667D931631324 /* Pods-PushSDK.debug.xcconfig */; + baseConfigurationReference = C0C94F0280591F339FDAE7CE /* Pods-PushSDK.debug.xcconfig */; buildSettings = { CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; DEFINES_MODULE = YES; - DEVELOPMENT_TEAM = 74UT6QD789; + DEVELOPMENT_TEAM = HRUACU4W6Z; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = PushSDK/Info.plist; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.push.ios.pushsdkios.PushSDK; + MARKETING_VERSION = 1.0.0.45; + PRODUCT_BUNDLE_IDENTIFIER = "com.gms-worldwide.PushSDK"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; - BAB6CB162558FA59007A4C56 /* Release */ = { + 01FCADE528C0C15E00D77FA4 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 60C41E10609C942F177AC5D7 /* Pods-PushSDK.release.xcconfig */; + baseConfigurationReference = 9765B5F0A65CA6F0C55A43C9 /* Pods-PushSDK.release.xcconfig */; buildSettings = { CLANG_ENABLE_MODULES = YES; - CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; DEFINES_MODULE = YES; - DEVELOPMENT_TEAM = 74UT6QD789; + DEVELOPMENT_TEAM = HRUACU4W6Z; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = PushSDK/Info.plist; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@loader_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = com.push.ios.pushsdkios.PushSDK; + MARKETING_VERSION = 1.0.0.45; + PRODUCT_BUNDLE_IDENTIFIER = "com.gms-worldwide.PushSDK"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; }; - BAB6CB182558FA59007A4C56 /* Debug */ = { + 01FCADE728C0C15E00D77FA4 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 27EBCAC057364D579C92EB06 /* Pods-PushSDKTests.debug.xcconfig */; + baseConfigurationReference = EF12FE5BF376817136B02DB0 /* Pods-PushSDK-PushSDKTests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = 74UT6QD789; - INFOPLIST_FILE = PushSDKTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.push.ios.pushsdkios.PushSDKTests; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = HRUACU4W6Z; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = "com.gms-worldwide.PushSDKTests"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; - BAB6CB192558FA59007A4C56 /* Release */ = { + 01FCADE828C0C15E00D77FA4 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 296C18064AF63D7FD04C7F5B /* Pods-PushSDKTests.release.xcconfig */; + baseConfigurationReference = D82D31A58B1C1FA747FC02EA /* Pods-PushSDK-PushSDKTests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = 74UT6QD789; - INFOPLIST_FILE = PushSDKTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.push.ios.pushsdkios.PushSDKTests; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = HRUACU4W6Z; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = "com.gms-worldwide.PushSDKTests"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -647,34 +619,34 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - BAB6CAFA2558FA59007A4C56 /* Build configuration list for PBXProject "PushSDK" */ = { + 01FCADCB28C0C15E00D77FA4 /* Build configuration list for PBXProject "PushSDK" */ = { isa = XCConfigurationList; buildConfigurations = ( - BAB6CB122558FA59007A4C56 /* Debug */, - BAB6CB132558FA59007A4C56 /* Release */, + 01FCADE128C0C15E00D77FA4 /* Debug */, + 01FCADE228C0C15E00D77FA4 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - BAB6CB142558FA59007A4C56 /* Build configuration list for PBXNativeTarget "PushSDK" */ = { + 01FCADE328C0C15E00D77FA4 /* Build configuration list for PBXNativeTarget "PushSDK" */ = { isa = XCConfigurationList; buildConfigurations = ( - BAB6CB152558FA59007A4C56 /* Debug */, - BAB6CB162558FA59007A4C56 /* Release */, + 01FCADE428C0C15E00D77FA4 /* Debug */, + 01FCADE528C0C15E00D77FA4 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - BAB6CB172558FA59007A4C56 /* Build configuration list for PBXNativeTarget "PushSDKTests" */ = { + 01FCADE628C0C15E00D77FA4 /* Build configuration list for PBXNativeTarget "PushSDKTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - BAB6CB182558FA59007A4C56 /* Debug */, - BAB6CB192558FA59007A4C56 /* Release */, + 01FCADE728C0C15E00D77FA4 /* Debug */, + 01FCADE828C0C15E00D77FA4 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; - rootObject = BAB6CAF72558FA59007A4C56 /* Project object */; + rootObject = 01FCADC828C0C15E00D77FA4 /* Project object */; } diff --git a/PushSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/PushSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 87a39615..919434a6 100644 --- a/PushSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/PushSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/PushSDK.xcodeproj/project.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate b/PushSDK.xcodeproj/project.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..d597fe69 Binary files /dev/null and b/PushSDK.xcodeproj/project.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDK.xcscheme b/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDK.xcscheme new file mode 100644 index 00000000..d3ee550d --- /dev/null +++ b/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDK.xcscheme @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDKTests.xcscheme b/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDKTests.xcscheme new file mode 100644 index 00000000..327f03c6 --- /dev/null +++ b/PushSDK.xcodeproj/xcshareddata/xcschemes/PushSDKTests.xcscheme @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/PushSDK.xcodeproj/xcuserdata/o.korniienko.xcuserdatad/xcschemes/xcschememanagement.plist b/PushSDK.xcodeproj/xcuserdata/o.korniienko.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000..21091594 --- /dev/null +++ b/PushSDK.xcodeproj/xcuserdata/o.korniienko.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,34 @@ + + + + + SchemeUserState + + PushSDK.xcscheme_^#shared#^_ + + orderHint + 17 + + PushSDKTests.xcscheme_^#shared#^_ + + isShown + + orderHint + 18 + + + SuppressBuildableAutocreation + + 01FCADD028C0C15E00D77FA4 + + primary + + + 01FCADD828C0C15E00D77FA4 + + primary + + + + + diff --git a/PushSDK.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/PushSDK.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings deleted file mode 100644 index 0c67376e..00000000 --- a/PushSDK.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate b/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 00000000..a7c9b995 Binary files /dev/null and b/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 00000000..271a6dc1 --- /dev/null +++ b/PushSDK.xcworkspace/xcuserdata/o.korniienko.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,6 @@ + + + diff --git a/PushSDK/BridgingHeader.h b/PushSDK/BridgingHeader.h deleted file mode 100644 index acf4eb95..00000000 --- a/PushSDK/BridgingHeader.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// header_pushsdk.h -// PushDemo -// -// Created by ard on 28/09/2019. -// Copyright © 2019 ard. All rights reserved. -// - -#ifndef header_PushSDK_h -#define header_PushSDK_h - - -#endif /* header_PushSDK_h */ -#import diff --git a/PushSDK/Info.plist b/PushSDK/Info.plist deleted file mode 100644 index e1fe4cfb..00000000 --- a/PushSDK/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleVersion - $(CURRENT_PROJECT_VERSION) - - diff --git a/PushSDK/PushSDK.h b/PushSDK/PushSDK.h index 0944deb8..340c3e30 100644 --- a/PushSDK/PushSDK.h +++ b/PushSDK/PushSDK.h @@ -2,14 +2,13 @@ // PushSDK.h // PushSDK // -// Created by Kirill Kotov on 01/10/2020. -// Copyright © 2020 HYBER. All rights reserved. +// Created by o.korniienko on 01.09.22. // +#import #import #import - //! Project version number for PushSDK. FOUNDATION_EXPORT double PushSDKVersionNumber; diff --git a/PushSDK/PushSDK.swift b/PushSDK/PushSDK.swift index e4cddd4b..8a31c64c 100644 --- a/PushSDK/PushSDK.swift +++ b/PushSDK/PushSDK.swift @@ -1,30 +1,18 @@ // -// pushsdk.swift -// pushsdk +// PushSDK.swift +// GMSPushSDKIOS // -// Created by Kirill Kotov on 08/05/2019. -// Copyright © 2019 ard. All rights reserved. +// Created by o.korniienko on 22.08.22. // -//import UIKit import Foundation -import UIKit import CryptoSwift import SwiftyBeaver -// -//import CoreData -//import FirebaseCore -//import FirebaseMessaging -//import FirebaseInstanceID - -//coredata -//https://medium.com/@ankurvekariya/core-data-crud-with-swift-4-2-for-beginners-40efe4e7d1cc public extension Notification.Name { static let receivePushKData = Notification.Name("pushKSdkReceiveData") - //static let didCompleteTask = Notification.Name("didCompleteTask") - //static let completedLengthyDownload = Notification.Name("completedLengthyDownload") + } @@ -33,14 +21,14 @@ public class PushSDKVar { public static let LOGLEVEL_ERROR = SwiftyBeaver.Level.error public static var branchMasterValue: BranchStructObj = BranchStructObj( - url_Http_Update: "device/update", - url_Http_Registration: "device/registration", - url_Http_Revoke: "device/revoke", - url_Http_Device_getall: "device/all", - url_Http_Mess_callback: "message/callback", - url_Http_Mess_dr: "message/dr", - push_url_mess_queue: "message/queue", - url_Http_Mess_history: "message/history?startDate=" + urlHttpUpdate: "device/update", + urlHttpRegistration: "device/registration", + urlHttpRevoke: "device/revoke", + urlHttpDeviceGetAll: "device/all", + urlHttpMesscallback: "message/callback", + urlHttpMessDr: "message/dr", + pusUrlMessQueue: "message/queue", + urlHttpMessHistory: "message/history?startDate=" ) } @@ -48,14 +36,15 @@ public class PushSDK { private let log = SwiftyBeaver.self private let parserClassAdapter = PusherKParser.init() - private let parserJson = PushKAnswParser.init() - //private let fb_init_adapter = PushKFirebaseSdk.init() - + private let pushRestServer = PushAPI.init() + //private let funNotificator = PushNotification.init() + let answerBuilder = AnswerBuilder.init() + public init( - platform_branch: BranchStructObj = PushSDKVar.branchMasterValue, - log_level: SwiftyBeaver.Level = PushSDKVar.LOGLEVEL_ERROR, - push_style: Int = 0, + platformBranch: BranchStructObj = PushSDKVar.branchMasterValue, + logLevel: SwiftyBeaver.Level = PushSDKVar.LOGLEVEL_ERROR, + pushStyle: Int = 0, basePushURL: String, //display notification auto @@ -65,38 +54,33 @@ public class PushSDK { enableDeliveryReportAuto: Bool = true, // Working if enableNotification is true and enableDeliveryReportAuto is true - // 0 - no special logic // 1 - if notification permitted in application settings then send delivery report. Else not send report // 2 - always send delivery report if receive deliveryReportLogic: Int = 1 ) { PushKConstants.registrationstatus = UserDefaults.standard.bool(forKey: "registrationstatus") - PushKConstants.push_registration_token = UserDefaults.standard.string(forKey: "push_registration_token") + PushKConstants.pushRegistratioToken = UserDefaults.standard.string(forKey: "push_registration_token") PushKConstants.deviceId = UserDefaults.standard.string(forKey: "deviceId") - PushKConstants.firebase_registration_token = UserDefaults.standard.string(forKey: "firebase_registration_token") - PushKConstants.push_user_msisdn = UserDefaults.standard.string(forKey: "push_user_msisdn") - PushKConstants.push_user_password = UserDefaults.standard.string(forKey: "push_user_password") - parserClassAdapter.urlsInitialization(branchUrl: basePushURL, method_paths: platform_branch) + PushKConstants.firebaseRegistrationToken = UserDefaults.standard.string(forKey: "firebase_registration_token") + PushKConstants.pushUserMsisdn = UserDefaults.standard.string(forKey: "push_user_msisdn") + PushKConstants.pushUserPassword = UserDefaults.standard.string(forKey: "push_user_password") + parserClassAdapter.urlsInitialization(branchUrl: basePushURL, methodPaths: platformBranch) PushKConstants.basePushURLactive = basePushURL - //Constants.log_level_active = log_level + let console = ConsoleDestination() console.format = "$Dyyyy-MM-dd HH:mm:ss.SSS$d PushSDK $T $N.$F:$l $L: $M" - console.minLevel = log_level + console.minLevel = logLevel let file = FileDestination() PushKConstants.logger.addDestination(console) PushKConstants.logger.addDestination(file) - //let push_sesion_id = PushSdkFirHelpers.firebaseUpdateToken() - //PushKConstants.logger.debug("Init PushSDK: push_sesion_id: \(push_sesion_id)") - PushKConstants.enableNotificationFlag = enableNotification PushKConstants.deliveryReportLogicFlag = deliveryReportLogic PushKConstants.enableDeliveryReportAutoFlag = enableDeliveryReportAuto } - private let processor = PushKProcessing.init() - private let funNotificator = PushKNotification.init() + //answer codes @@ -109,280 +93,192 @@ public class PushSDK { //sdk errors //700 - internal SDK error - //701 - already exists + //701 - incorrect input //704 - not registered - //705 - remote server error - //707 - incorrect input - //710 - unknown error - + //707 - already exists - //{ - // "result":"Ok", - // "description":"", - // "code":200, - // "body":{ - //} - //} - let answer_b = AnswerBuider.init() - //Procedure 1. new device registration - //x_push_sesion_id - firebase FCM token - //x_push_ios_bundle_id - ios application bundle id - //X_Push_Client_API_Key - provide by hub administrator - //user_phone - subscribers msisdn - //subscribers password (optional, for future use) - public func pushRegisterNew(user_phone: String, user_password: String, x_push_sesion_id: String, x_push_ios_bundle_id: String, X_Push_Client_API_Key: String) -> PushKFunAnswerRegister { + //device registration + //xPushSessionId - firebase FCM token + //xPushIOSBundleId - ios application bundle id + //xPushClientAPIKey - provide by hub administrator + //userPhone - subscribers msisdn + //userPassword - subscribers password (optional, for future use) + public func pushRegisterNew(userPhone: String, userPassword: String, xPushSessionId: String, xPushIOSBundleId: String, xPushClientAPIKey: String) -> PushKFunAnswerRegister { - PushKConstants.logger.debug("Start function registrar push_register_new") - PushKConstants.logger.debug("Input func push_register_new: user_phone: \(user_phone), user_password: \(user_password), x_push_sesion_id: \(x_push_sesion_id), x_push_ios_bundle_id: \(x_push_ios_bundle_id), X_Push_Client_API_Key: \(X_Push_Client_API_Key)") + PushKConstants.logger.debug("Start function registrar pushRegisterNew") + PushKConstants.logger.debug("Input func pushRegisterNew: userPhone: \(userPhone), userPassword: \(userPassword), xPushSessionId: \(xPushSessionId), xPushIOSBundleId: \(xPushIOSBundleId), xPushClientAPIKey: \(xPushClientAPIKey)") PushKConstants.logger.debug("Used constants: registrationstatus: \(PushKConstants.registrationstatus)") - if (PushKConstants.registrationstatus==false){ - if (user_phone != "" && x_push_sesion_id != "" && X_Push_Client_API_Key != "" ) { - UserDefaults.standard.set(x_push_sesion_id, forKey: "firebase_registration_token") - PushKConstants.firebase_registration_token = x_push_sesion_id - let push_rest_server = PushKAPI.init() - let push_register_new_answer = push_rest_server.push_device_register(X_Push_Client_API_Key: X_Push_Client_API_Key, X_Push_Session_Id: x_push_sesion_id, X_Push_IOS_Bundle_Id: x_push_ios_bundle_id, device_Name:UIDevice.modelName, device_Type: PushKConstants.localizedModel, os_Type: "ios", sdk_Version: PushKConstants.sdkVersion, user_Pass: user_password, user_Phone: user_phone) - return push_register_new_answer + if (!PushKConstants.registrationstatus){ + if (userPhone != "" && xPushSessionId != "" && xPushClientAPIKey != "" ) { + UserDefaults.standard.set(xPushSessionId, forKey: "firebase_registration_token") + PushKConstants.firebaseRegistrationToken = xPushSessionId + let pusRegisterNewAnswer = pushRestServer.registerPushDevice(xPushClientAPIKey: xPushClientAPIKey, xPushSessionId: xPushSessionId, xPushIOSBundleId: xPushIOSBundleId, userPass: userPassword, userPhone: userPhone) + return pusRegisterNewAnswer } else { - return PushKFunAnswerRegister.init(code: 701, result: "error", description: "Incorrect input parameters", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.push_registration_token ?? "firebase_empty", userId: "", userPhone: PushKConstants.push_user_msisdn ?? "", createdAt: "") + return PushKFunAnswerRegister.init(code: 701, result: "error", description: "Incorrect input parameters", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.pushRegistratioToken ?? "firebase_empty", userId: "", userPhone: PushKConstants.pushUserMsisdn ?? "", createdAt: "") } } else { - return PushKFunAnswerRegister.init(code: 707, result: "error", description: "Registration exists", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.push_registration_token ?? "token_empty", userId: "", userPhone: PushKConstants.push_user_msisdn ?? "", createdAt: "") + return PushKFunAnswerRegister.init(code: 707, result: "error", description: "Registration exists", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.pushRegistratioToken ?? "token_empty", userId: "", userPhone: PushKConstants.pushUserMsisdn ?? "", createdAt: "") } } - public func pushRegisterNew(user_phone: String, user_password: String, x_push_ios_bundle_id: String, X_Push_Client_API_Key: String)->PushKFunAnswerRegister { - - PushKConstants.logger.debug("Start function registrar push_register_new2") - PushKConstants.logger.debug("Input func push_register_new2: user_phone: \(user_phone), user_password: \(user_password), x_push_ios_bundle_id: \(x_push_ios_bundle_id), X_Push_Client_API_Key: \(X_Push_Client_API_Key)") + public func pushRegisterNew(userPhone: String, userPassword: String, xPushIOSBundleId: String, xPushClientAPIKey: String)->PushKFunAnswerRegister { + PushKConstants.logger.debug("Start function registrar pushRegisterNew2") + PushKConstants.logger.debug("Input func pushRegisterNew2: userPhone: \(userPhone), userPassword: \(userPassword), xPushIOSBundleId: \(xPushIOSBundleId), xPushClientAPIKey: \(xPushClientAPIKey)") PushKConstants.logger.debug("Used constants: registrationstatus: \(PushKConstants.registrationstatus)") - let x_push_sesion_id = PushSdkFirHelpers.firebaseUpdateToken() + let xPushSessionId = PushSdkFirHelpers.firebaseUpdateToken() - PushKConstants.logger.debug("Token updated for registration: x_push_sesion_id: \(x_push_sesion_id)") + PushKConstants.logger.debug("Token updated for registration: xPushSessionId: \(xPushSessionId)") - if (PushKConstants.registrationstatus==false){ - if (user_phone != "" && x_push_sesion_id != "" && X_Push_Client_API_Key != "" ) { - let push_rest_server = PushKAPI.init() - let push_register_new_answer = push_rest_server.push_device_register(X_Push_Client_API_Key: X_Push_Client_API_Key, X_Push_Session_Id: x_push_sesion_id, X_Push_IOS_Bundle_Id: x_push_ios_bundle_id, device_Name:UIDevice.modelName, device_Type: PushKConstants.localizedModel, os_Type: "ios", sdk_Version: PushKConstants.sdkVersion, user_Pass: user_password, user_Phone: user_phone) - return push_register_new_answer + if (!PushKConstants.registrationstatus){ + if (userPhone != "" && xPushSessionId != "" && xPushClientAPIKey != "" ) { + let pusRegisterNewAnswer = pushRestServer.registerPushDevice(xPushClientAPIKey: xPushClientAPIKey, xPushSessionId: xPushSessionId, xPushIOSBundleId: xPushIOSBundleId, userPass: userPassword, userPhone: userPhone) + return pusRegisterNewAnswer } else { - PushKConstants.logger.debug("Error pushRegisterNew. Incorrect input parameters: user_phone: \(user_phone), x_push_sesion_id: \(x_push_sesion_id), X_Push_Client_API_Key: \(X_Push_Client_API_Key)") + PushKConstants.logger.debug("Error pushRegisterNew2. Incorrect input parameters: userPhone: \(userPhone), xPushSessionId: \(xPushSessionId), xPushClientAPIKey: \(xPushClientAPIKey)") - return PushKFunAnswerRegister.init(code: 701, result: "error", description: "Incorrect input parameters", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.push_registration_token ?? "firebase_empty", userId: "", userPhone: PushKConstants.push_user_msisdn ?? "", createdAt: "") + return PushKFunAnswerRegister.init(code: 701, result: "error", description: "Incorrect input parameters", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.pushRegistratioToken ?? "firebase_empty", userId: "", userPhone: PushKConstants.pushUserMsisdn ?? "", createdAt: "") } } else { - return PushKFunAnswerRegister.init(code: 707, result: "error", description: "Registration exists", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.push_registration_token ?? "token_empty", userId: "", userPhone: PushKConstants.push_user_msisdn ?? "", createdAt: "") + return PushKFunAnswerRegister.init(code: 707, result: "error", description: "Registration exists", deviceId: PushKConstants.deviceId ?? "unknown", token: PushKConstants.pushRegistratioToken ?? "token_empty", userId: "", userPhone: PushKConstants.pushUserMsisdn ?? "", createdAt: "") } } - //Procedure 2. Delete registration + public func pushUpdateRegistration() -> PushKGeneralAnswerStruct { + if (PushKConstants.registrationstatus) { + + let xPushSessionId: String = PushSdkFirHelpers.firebaseUpdateToken() + + let answer = pushRestServer.pushUpdateRegistration(fcmToken: PushKConstants.firebaseRegistrationToken ?? "firebase_empty", xPushSessionId: xPushSessionId, xPushAuthToken:PushKConstants.pushRegistratioToken ?? "token_empty") + return answer } + else { + return answerBuilder.generalAnswerStruct(respCode: 704, bodyJson: "error", description: "Not registered") + } + } + + + //Delete registration public func pushClearCurrentDevice()->PushKGeneralAnswerStruct { - if (PushKConstants.registrationstatus==true){ - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - let answer = push_rest_server.push_device_revoke(dev_list: [PushKConstants.deviceId ?? "unknown"], X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "firebase_empty") + if (PushKConstants.registrationstatus){ + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + + let answer = pushRestServer.pushDeviceRevoke(devList: [PushKConstants.deviceId ?? "unknown"], xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "firebase_empty") return answer } else { - return answer_b.generalAnswerStruct(resp_code: "704", body_json: "error", description: "Not registered") + return answerBuilder.generalAnswerStruct(respCode: 704, bodyJson: "error", description: "Not registered") } } - + //Get all devices related to number public func pushGetDeviceAllFromServer() -> PushKFunAnswerGetDeviceList { - if (PushKConstants.registrationstatus==true){ - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - let ansss = push_rest_server.push_device_get_all(X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "token_empty") - PushKConstants.logger.debug(ansss) - return ansss} + if (PushKConstants.registrationstatus){ + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + let answer = pushRestServer.pushDevicesGetAll(xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "token_empty") + PushKConstants.logger.debug(answer) + return answer} else { return PushKFunAnswerGetDeviceList.init(code: 704, result: "error", description: "Not registered", body: nil) } } - public func pushSendMessageCallback(message_id: String, message_text: String) -> PushKGeneralAnswerStruct { - if (PushKConstants.registrationstatus==true){ - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - let anss = push_rest_server.push_message_callback(message_Id: message_id, answer: message_text, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "token_empty") - - return anss} - else { - return answer_b.generalAnswerStruct(resp_code: "704", body_json: "error", description: "Not registered") - } - } - public func pushMessageDeliveryReport(message_id: String) -> PushKGeneralAnswerStruct { - if (PushKConstants.registrationstatus==true) { - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - PushKConstants.logger.debug(X_Push_Session_Id) - PushKConstants.logger.debug(message_id) - PushKConstants.logger.debug(String(PushKConstants.push_registration_token ?? "firebase_empty")) - - let asaa = push_rest_server.push_message_dr(message_Id: message_id, received_At: "0", X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "token_empty") - - return asaa} + //Delete registration of all devices related to number + public func pushClearAllDevice()->PushKGeneralAnswerStruct { + + if (PushKConstants.registrationstatus) { + let getdevResponse = pushGetDeviceAllFromServer() + + var listDevId: [String] = [] + + let devListAll = getdevResponse.body + + for device in devListAll?.devices ?? [] + { + listDevId.append(String(device.id)) + } + + PushKConstants.logger.debug(listDevId) + + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + PushKConstants.logger.debug(String(PushKConstants.deviceId ?? "unknown")) + PushKConstants.logger.debug(xPushSessionId) + PushKConstants.logger.debug(String(PushKConstants.pushRegistratioToken ?? "token_empty")) + + let answer = pushRestServer.pushDeviceRevoke(devList: listDevId, xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "empty_token") + + return answer + + } else { - return answer_b.generalAnswerStruct(resp_code: "704", body_json: "error", description: "Not registered") + return answerBuilder.generalAnswerStruct(respCode: 704, bodyJson: "error", description: "Not registered") } } - public func pushUpdateRegistration() -> PushKGeneralAnswerStruct { - if (PushKConstants.registrationstatus==true) { + //Get message history related to current device + public func pushGetMessageHistory(periodInSeconds: Int) -> PushKFunAnswerGetMessageHistory { + if (PushKConstants.registrationstatus) { + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" - let X_Push_Session_Id: String = PushSdkFirHelpers.firebaseUpdateToken() - let push_rest_server = PushKAPI.init() + let answer = pushRestServer.pushGetMessageHistory(utcTime: periodInSeconds, xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "token_empty" ) + return answer - let ansss = push_rest_server.push_device_update(fcm_Token: PushKConstants.firebase_registration_token ?? "firebase_empty", os_Type: "ios", os_Version: PushKConstants.dev_os_Version, device_Type: PushKConstants.localizedModel, device_Name: UIDevice.modelName, sdk_Version: PushKConstants.sdkVersion, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token:PushKConstants.push_registration_token ?? "token_empty") - return ansss } + } else { - return answer_b.generalAnswerStruct(resp_code: "704", body_json: "error", description: "Not registered") + return PushKFunAnswerGetMessageHistory.init(code: 704, result: "error", description: "Not registered", body: nil) } } - enum MyError: Error { - case FoundNil(String) - } - public func pushGetMessageHistory(period_in_seconds: Int) -> PushKFunAnswerGetMessageHistory { - if (PushKConstants.registrationstatus==true) { - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - - let ansss = push_rest_server.push_message_get_history( utc_time: period_in_seconds, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "token_empty" ) - return ansss } + public func pushCheckQueue() -> PushKFunAnswerGeneral { + if (PushKConstants.registrationstatus) { + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + let answer = pushRestServer.checkQueue(xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "token_empty" ) + return answer + } else { - return PushKFunAnswerGetMessageHistory.init(code: 704, result: "error", description: "Not registered", body: nil) + return answerBuilder.generalAnswer(respCode: 704, bodyJson: "error", description: "Not registered") } } - public func pushClearAllDevice()->PushKGeneralAnswerStruct { - - if (PushKConstants.registrationstatus==true) { - let getdev = pushGetDeviceAllFromServer() - - var listdev: [String] = [] + //send message DR + public func pushMessageDeliveryReport(messageId: String) -> PushKGeneralAnswerStruct { + if (PushKConstants.registrationstatus) { + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + PushKConstants.logger.debug(xPushSessionId) + PushKConstants.logger.debug(messageId) + PushKConstants.logger.debug(String(PushKConstants.pushRegistratioToken ?? "firebase_empty")) - let dev_list_all = getdev.body + let answer = pushRestServer.sendMessageDR(messageId: messageId, xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "token_empty") - for jj in dev_list_all?.devices ?? [] - { - listdev.append(String(jj.id)) - } - - PushKConstants.logger.debug(listdev) - - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - PushKConstants.logger.debug(String(PushKConstants.deviceId ?? "unknown")) - PushKConstants.logger.debug(X_Push_Session_Id) - PushKConstants.logger.debug(String(PushKConstants.push_registration_token ?? "token_empty")) - - let push_rest_server = PushKAPI.init() - let ggg = push_rest_server.push_device_revoke(dev_list: listdev, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "empty_token") - - return ggg - - } + return answer} else { - return answer_b.generalAnswerStruct(resp_code: "704", body_json: "error", description: "Not registered") + return answerBuilder.generalAnswerStruct(respCode: 704, bodyJson: "error", description: "Not registered") } } - public func rewrite_msisdn(newmsisdn: String) -> PushKGeneralAnswerStruct { - UserDefaults.standard.set(newmsisdn, forKey: "push_user_msisdn") - PushKConstants.firebase_registration_token = newmsisdn - return PushKGeneralAnswerStruct.init(code: 200, result: "Ok", description: "Success", body: "newmsisdn: \(newmsisdn)") - } - - public func rewrite_password(newpassword: String) -> PushKGeneralAnswerStruct{ - UserDefaults.standard.set(newpassword, forKey: "push_user_password") - PushKConstants.firebase_registration_token = newpassword - return PushKGeneralAnswerStruct.init(code: 200, result: "Ok", description: "Success", body: "newpassword: \(newpassword)") - } - - - - //check if notification permitted (Sync procedure) - public func areNotificationsEnabled() -> Bool { - - let semaphore = DispatchSemaphore(value: 0) - funNotificator.areNotificationsEnabled { (notificationStatus) in - debugPrint(notificationStatus) - PushKConstants.notificationPermission = notificationStatus - semaphore.signal() - } - semaphore.wait() - return PushKConstants.notificationPermission - } - - //check if notification permitted (Async procedure) - public func areNotificationsEnabled(completion:@escaping (Bool)->Swift.Void) { - var notificationStatus: Bool = false - let current = UNUserNotificationCenter.current() - current.getNotificationSettings(completionHandler: { permission in - switch permission.authorizationStatus { - case .authorized: - PushKConstants.logger.debug("User granted permission for notification") - notificationStatus = true - completion(notificationStatus) - break - case .denied: - PushKConstants.logger.debug("User denied notification permission") - notificationStatus = false - completion(notificationStatus) - break - case .notDetermined: - PushKConstants.logger.debug("Notification permission haven't been asked yet") - notificationStatus = false - completion(notificationStatus) - break - case .provisional: - // @available(iOS 12.0, *) - PushKConstants.logger.debug("The application is authorized to post non-interruptive user notifications.") - notificationStatus = true - completion(notificationStatus) - break - case .ephemeral: - // @available(iOS 14.0, *) - PushKConstants.logger.debug("The application is temporarily authorized to post notifications. Only available to app clips.") - notificationStatus = false - completion(notificationStatus) - break - @unknown default: - PushKConstants.logger.debug("Unknow Status") - notificationStatus = false - completion(notificationStatus) - break - } - }) - } - - - - public func pushCheckQueue() -> PushKFunAnswerGeneral { - if (PushKConstants.registrationstatus==true) { - let X_Push_Session_Id: String = PushKConstants.firebase_registration_token ?? "firebase_empty" - let push_rest_server = PushKAPI.init() - let ansss = push_rest_server.push_check_queue(X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: PushKConstants.push_registration_token ?? "token_empty" ) - return ansss - } + public func pushSendMessageCallback(messageId: String, callbackText: String) -> PushKGeneralAnswerStruct { + if (PushKConstants.registrationstatus){ + let xPushSessionId: String = PushKConstants.firebaseRegistrationToken ?? "firebase_empty" + let answer = pushRestServer.sendMessageCallBack(messageId: messageId, answer: callbackText, xPushSessionId: xPushSessionId, xPushAuthToken: PushKConstants.pushRegistratioToken ?? "token_empty") + + return answer} else { - return answer_b.generalAnswer(resp_code: 704, body_json: "error", description: "Not registered") + return answerBuilder.generalAnswerStruct(respCode: 704, bodyJson: "error", description: "Not registered") } } @@ -392,8 +288,8 @@ public class PushSDK { guard let jsonData = try? JSONSerialization.data(withJSONObject: message.userInfo ?? "", options: []) else { return PushKMess(code: 500, result: "Error in process message", messageFir: FullFirebaseMessageStr(aps: MessApsDataStr(contentAvailable: 0), message: MessagesResponseStr(), googleCSenderId: "", gcmMessageId: ""))} let jsonString = String(data: jsonData, encoding: .utf8) let newString = String(jsonString ?? "").replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - let parsed_message = PushKAnswParser.messageIncomingJson(str_resp: newString) - return PushKMess(code: 200, result: "Success", messageFir: parsed_message) + let parsedMessage = PushServerAnswParser.messageIncomingJson(strResp: newString) + return PushKMess(code: 200, result: "Success", messageFir: parsedMessage) } //userInfo parse @@ -402,14 +298,9 @@ public class PushSDK { let jsonString = String(data: jsonData, encoding: .utf8) let newString = String(jsonString ?? "").replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - let parsed_message = PushKAnswParser.messageIncomingJson(str_resp: newString) - return PushKMess(code: 200, result: "Success", messageFir: parsed_message) + let parsedMessage = PushServerAnswParser.messageIncomingJson(strResp: newString) + return PushKMess(code: 200, result: "Success", messageFir: parsedMessage) } } - - - - - diff --git a/PushSDK/PushSDKFirebase.swift b/PushSDK/PushSDKFirebase.swift index 8255f9da..b88a4fa5 100644 --- a/PushSDK/PushSDKFirebase.swift +++ b/PushSDK/PushSDKFirebase.swift @@ -1,10 +1,8 @@ - // -// firebase_message_code.swift -// PushSDK +// PushSDKFirebase.swift +// ToTestSDK // -// Created by Kirill Kotov on 15/05/2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 23.08.22. // import Foundation @@ -12,16 +10,14 @@ import Foundation import UserNotifications import FirebaseMessaging import FirebaseCore -//import FirebaseInstanceID public class PushSDKFirebase: UIResponder, UIApplicationDelegate { - let processorPush = PushKProcessing.init() let pushParser = PusherKParser.init() - let manualNotificator = PushKNotification.init() - let answerAdapter = PushKAnswParser.init() - let push_adapter = PushSDK.init(basePushURL: PushKConstants.basePushURLactive) + //let manualNotificator = PushNotification.init() + let answerAdapter = PushServerAnswParser.init() + let pushAdapter = PushSDK.init(basePushURL: PushKConstants.basePushURLactive) let gcmMessageIDKey = "gcm.message_id" let mySpecialNotificationKey = "com.push.specialNotificationKey" @@ -84,7 +80,7 @@ public class PushSDKFirebase: UIResponder, UIApplicationDelegate { PushKConstants.logger.debug("Call fbInitApplication: fbInitApplication2") // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. - // TODO: Handle data of notification + // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. @@ -93,91 +89,10 @@ public class PushSDKFirebase: UIResponder, UIApplicationDelegate { } // Print full message. - PushKConstants.logger.debug("fb_fun2_application userInfo: \(userInfo)") + PushKConstants.logger.debug("fb_init_application_fun2 userInfo: \(userInfo)") } - public func fbInitApplication(didReceiveRemoteNotification userInfo: [AnyHashable: Any], - fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { - //fbInitApplication3 - PushKConstants.logger.debug("Call fbInitApplication: fbInitApplication3") - // If you are receiving a notification message while your app is in the background, - // this callback will not be fired till the user taps on the notification launching the application. - // TODO: Handle data of notification - - // With swizzling disabled you must let Messaging know about the message, for Analytics - // Messaging.messaging().appDidReceiveMessage(userInfo) - - // Print message ID. - if let messageID = userInfo[gcmMessageIDKey] { - PushKConstants.logger.debug("Message ID: \(messageID)") - } - - // Print full message. - PushKConstants.logger.debug("userInfo: \(userInfo)") - - - - //here is delivery report - guard let jsonData = try? JSONSerialization.data(withJSONObject: userInfo, options: []) else { return } - let jsonString = String(data: jsonData, encoding: .utf8) - let newString = String(jsonString ?? "").replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - let parsed_message = PushKAnswParser.messageIncomingJson(str_resp: newString) - PushKConstants.logger.debug(parsed_message) - PushKConstants.logger.debug("test step before notification") - - /* - let state = UIApplication.shared.applicationState - if state == .background || state == .inactive { - manualNotificator.pushNotificationManualWithImage( - image_url: String(parsed_message.message.image?.url ?? ""), - content_title: String(parsed_message.message.title ?? ""), - content_body: String(parsed_message.message.body ?? "")) - PushKConstants.logger.debug("App in Background") - } - */ - if (PushKConstants.enableNotificationFlag == true) { - manualNotificator.pushNotificationManualWithImage( - image_url: String(parsed_message.message.image?.url ?? ""), - content_title: String(parsed_message.message.title ?? ""), - content_body: String(parsed_message.message.body ?? ""), - userInfo: userInfo) - PushKConstants.logger.debug("App in Background") - } - - //textOutput.text = newString - PushKConstants.logger.debug("newString: \(newString)") - PushKConstants.logger.debug("findProcessor") - - let new3String = pushParser.messIdParser(message_from_push_server: jsonString ?? "") - - PushKConstants.logger.debug("new3String: \(new3String)") - - //if (PushKConstants.enableDeliveryReportAutoFlag == true) { - // let deliv_rep_answ = push_adapter.pushMessageDeliveryReport(message_id: new3String) - // PushKConstants.logger.debug("deliv_rep_answ: \(deliv_rep_answ)") - //} - - if (PushKConstants.enableDeliveryReportAutoFlag == true && PushKConstants.enableNotificationFlag == true) { - if (PushKConstants.deliveryReportLogicFlag == 1) { - manualNotificator.areNotificationsEnabled { (notificationStatus) in - debugPrint(notificationStatus) - if (notificationStatus == true) { - let deliv_rep_answ = self.push_adapter.pushMessageDeliveryReport(message_id: new3String) - PushKConstants.logger.debug("deliv_rep_answ: \(deliv_rep_answ)") - } - } - } else if (PushKConstants.deliveryReportLogicFlag == 2) - { - let deliv_rep_answ = self.push_adapter.pushMessageDeliveryReport(message_id: new3String) - PushKConstants.logger.debug("deliv_rep_answ: \(deliv_rep_answ)") - } - } - - NotificationCenter.default.post(name: .receivePushKData, object: nil, userInfo: userInfo) - - completionHandler(UIBackgroundFetchResult.newData) - } public func fbInitApplication(didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { @@ -221,78 +136,8 @@ extension PushSDKFirebase: UNUserNotificationCenterDelegate{ extension PushSDKFirebase { - public func fb_notify_messaging() { + public func fbNotifyMessaging() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: mySpecialNotificationKey), object: self) } - public func fb_remote_messaging(remoteMessage: NSDictionary) { - let fdf = remoteMessage as NSDictionary as? [String: AnyObject] - guard let jsonData = (try? JSONSerialization.data(withJSONObject: fdf ?? "", options: [])) else { return } - let jsonString = String(data: jsonData, encoding: .utf8) - let parsedMessage = PushKAnswParser.messageIncomingJson(str_resp: jsonString ?? "") - PushKConstants.logger.debug(parsedMessage) - let parsedMessageUserData = pushParser.messIdParser(message_from_push_server: jsonString ?? "") - - - /* - let state = UIApplication.shared.applicationState - if state == .background || state == .inactive { - manualNotificator.pushNotificationManualWithImage( - image_url: String(parsedMessage.message.image?.url ?? ""), - content_title: String(parsedMessage.message.title ?? ""), - content_body: String(parsedMessage.message.body ?? "")) - PushKConstants.logger.debug("App in Background") - } - */ - if (PushKConstants.enableNotificationFlag == true) { - manualNotificator.pushNotificationManualWithImage( - image_url: String(parsedMessage.message.image?.url ?? ""), - content_title: String(parsedMessage.message.title ?? ""), - content_body: String(parsedMessage.message.body ?? ""), - userInfo: fdf ?? [:]) - } - PushKConstants.logger.debug("App in Background") - - switch UIApplication.shared.applicationState { - case .active: - PushKConstants.logger.debug("active") - case .background: - PushKConstants.logger.debug("App is backgrounded. Next number = \(parsedMessageUserData)") - PushKConstants.logger.debug("Background time remaining = " + - "\(UIApplication.shared.backgroundTimeRemaining) seconds") - case .inactive: - break - @unknown default: - PushKConstants.logger.debug("Fatal application error for UIApplication.shared.applicationState") - } - - if (PushKConstants.enableDeliveryReportAutoFlag == true && PushKConstants.enableNotificationFlag == true) { - if (PushKConstants.deliveryReportLogicFlag == 1) { - manualNotificator.areNotificationsEnabled { (notificationStatus) in - debugPrint(notificationStatus) - if (notificationStatus == true) { - let deliv_rep_answ = self.push_adapter.pushMessageDeliveryReport(message_id: parsedMessageUserData) - PushKConstants.logger.debug("deliv_rep_answ: \(deliv_rep_answ)") - } - } - } else if (PushKConstants.deliveryReportLogicFlag == 2) - { - let deliv_rep_answ = self.push_adapter.pushMessageDeliveryReport(message_id: parsedMessageUserData) - PushKConstants.logger.debug("deliv_rep_answ: \(deliv_rep_answ)") - } - } - - NotificationCenter.default.post(name: .receivePushKData, object: nil, userInfo: fdf) - } - - public func fb_token_messaging(didReceiveRegistrationToken fcmToken: String) { - PushKConstants.logger.debug("Firebase registration token: \(fcmToken)") - let dataDict:[String: String] = ["token": fcmToken] - NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict) - PushKConstants.logger.debug("fb_token_messaging fcmToken: \(fcmToken)") - // TODO: If necessary send token to application server. - // Note: This callback is fired at each app startup and whenever a new token is generated. - } } - - diff --git a/PushSDK/api/PushAdapter.swift b/PushSDK/api/PushAdapter.swift index 73ba09d1..b973be4c 100644 --- a/PushSDK/api/PushAdapter.swift +++ b/PushSDK/api/PushAdapter.swift @@ -1,999 +1,653 @@ - // -// push_adapter.swift -// test222 +// PushAdapter.swift +// GMSPushSDKIOS // -// Created by Kirill Kotov on 16/04/2019. -// Copyright © 2019 ard. All rights reserved. +// Created by o.korniienko on 22.08.22. // import Foundation import CryptoSwift +import Alamofire -internal class PushKAPI { - - private let jsonparser = PushKAnswParser.init() - private let push_database_adapter = PushKDatabase.init() + + + +internal class PushAPI { - private let processor = PushKProcessing.init() - private let answer_buider = AnswerBuider.init() + private let jsonparser = PushServerAnswParser.init() + private let pushDatabaseAdapter = PushKDatabase.init() + private let answerBuider = AnswerBuilder.init() + private let serverDataResponses = DataResponses() - private let functionNotificator = PushKNotification.init() - let answer_b = AnswerBuider.init() - //rest function for device registration - //1 procedure - func push_device_register(X_Push_Client_API_Key: String, X_Push_Session_Id: String, X_Push_IOS_Bundle_Id: String, device_Name:String, device_Type:String, os_Type:String, sdk_Version:String, user_Pass:String, user_Phone:String)-> PushKFunAnswerRegister { + //function for device registration + func registerPushDevice(xPushClientAPIKey: String, xPushSessionId: String, xPushIOSBundleId: String, userPass:String, userPhone:String) -> PushKFunAnswerRegister { - PushKConstants.logger.debug("Start function push_device_register") + PushKConstants.logger.debug("Start function registerPushDevice") + let semaphore = DispatchSemaphore(value: 0) + + var genAnsw: PushKFunAnswerRegister = PushKFunAnswerRegister(code: 0, result: "", description: "", deviceId: "", token: "", userId: "", userPhone: "", createdAt: "") + + let osVersion = PushKConstants.devOSVersion + + let requestURL = PushKConstants.platformBrancActive.urlHttpRegistration + PushKConstants.logger.debug("registerPushDevice url string is \(requestURL)") + + let params: Parameters = [ + "deviceName": UIDevice.modelName, + "deviceType": PushKConstants.localizedModel, + "osType": "ios", + "osVersion": osVersion, + "sdkVersion": PushKConstants.sdkVersion, + "userPass": userPass, + "userPhone": userPhone + ] + + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Client-API-Key": xPushClientAPIKey, + "X-Hyber-IOS-Bundle-Id": xPushIOSBundleId + ] + + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + + + Task{ + serverDataResponses.registerResponse = await makePostRequest(headersRequest: headersRequest, params: params, url: requestURL) + semaphore.signal() + } + semaphore.wait() + + let response = serverDataResponses.registerResponse + PushKConstants.logger.debug("registerPushDevice response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("registerPushDevice response debugDescription is \(String(describing: response?.debugDescription))") - //var answ: String = String() - var genAnsw: PushKFunAnswerRegister = PushKFunAnswerRegister(code: 0, result: "", description: "", deviceId: "", token: "", userId: "", userPhone: "", createdAt: "") - - let semaphore7 = DispatchSemaphore(value: 0) - - let os_Version = PushKConstants.dev_os_Version - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - let params = [ - "deviceName": device_Name, - "deviceType": device_Type, - "osType": os_Type, - "osVersion": os_Version, - "sdkVersion": sdk_Version, - "userPass": user_Pass, - "userPhone": user_Phone - ] as Dictionary - - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Registration as NSString); - PushKConstants.logger.debug("push_device_register url string is \(urlString)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - //var result = "" as? [[String: Any]]; - - request.url = URL(string: NSString(format: "%@", urlString)as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - - //headers - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - //request.addValue("application/json", forHTTPHeaderField: "Accept") - request.addValue(X_Push_Client_API_Key, forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - request.addValue(X_Push_IOS_Bundle_Id, forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.debug("request.httpBody error") - } - - PushKConstants.logger.debug(request.httpBody ?? "") - PushKConstants.logger.debug(request.allHTTPHeaderFields ?? "") - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore7.signal() - return - } - print(httpResponse) - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_device_register body_json from push server: \(body_json)") - - - genAnsw = PushKFunAnswerRegister.init(code: httpResponse.statusCode, result: "unknown", description: "unknown", deviceId: "", token: "", userId: "", userPhone: "", createdAt: "") - - - PushKConstants.logger.debug("push_device_register response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("push_device_register response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("push_device_register response data is \(String(describing: data))") - - PushKConstants.logger.debug("push_device_register response debugDescription is \(httpResponse.debugDescription)") - - - - switch (httpResponse.statusCode) - { + + switch response?.response?.statusCode { case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - PushKConstants.logger.debug(String(response ?? "")) - - let str_resp = String(response ?? "") - - PushKConstants.logger.debug(str_resp) - - let resp_register_parsed = self.jsonparser.registerJParse(str_resp: str_resp) - - + PushKConstants.logger.debug("registerPushDevice response data is \(String(describing: response?.data))") + let responseNSString = NSString (data: (response?.data)! , encoding: String.Encoding.utf8.rawValue) + + PushKConstants.logger.debug(String(responseNSString ?? "")) + let respStr = String(responseNSString ?? "") + PushKConstants.logger.debug(respStr) + let parsedRegisterResp = self.jsonparser.registerJParse(strResp: respStr) + genAnsw.result = "Success" genAnsw.description = "Procedure completed" - genAnsw.createdAt = resp_register_parsed.createdAt ?? "empty" - genAnsw.deviceId = resp_register_parsed.deviceId ?? "unknown" - genAnsw.token = resp_register_parsed.token ?? "empty_token" - genAnsw.userId = String(resp_register_parsed.userId ?? 0) - - self.push_database_adapter.saveDataAfterRegisterOk( - user_Phone: user_Phone, - token: resp_register_parsed.token ?? "empty_token", - device_id: resp_register_parsed.deviceId ?? "unknown", - user_Password: user_Pass, - created_at: resp_register_parsed.createdAt ?? "empty", - user_id: String(resp_register_parsed.userId ?? 0) + genAnsw.createdAt = parsedRegisterResp.createdAt ?? "empty" + genAnsw.deviceId = parsedRegisterResp.deviceId ?? "unknown" + genAnsw.token = parsedRegisterResp.token ?? "empty_token" + genAnsw.userId = String(parsedRegisterResp.userId ?? 0) + + self.pushDatabaseAdapter.saveDataAfterRegisterOk( + userPhone: userPhone, + token: parsedRegisterResp.token ?? "empty_token", + deviceId: parsedRegisterResp.deviceId ?? "unknown", + userPassword: userPass, + createdAt: parsedRegisterResp.createdAt ?? "empty", + userId: String(parsedRegisterResp.userId ?? 0) ) - - PushKConstants.logger.debug(resp_register_parsed.token ?? "") - - if response == "SUCCESS" - { - PushKConstants.logger.debug("push_device_register success response body is \(String(describing: response))") - } - + + PushKConstants.logger.debug(parsedRegisterResp.token ?? "") + PushKConstants.logger.debug("registerPushDevice response code is \(String(describing: response?.response!.statusCode))") + default: - PushKConstants.logger.debug("push_device_register save profile POST request got response \(httpResponse.statusCode)") - } - //return jsonData - semaphore7.signal() + PushKConstants.logger.debug("registerPushDevice response code is \(String(describing: response?.response!.statusCode))") + + } - dataTask.resume() - semaphore7.wait() - return genAnsw + + } + + + return genAnsw + } - //2 procedure - //for revoke device from push server - func push_device_revoke(dev_list: [String], X_Push_Session_Id: String, X_Push_Auth_Token:String)->PushKGeneralAnswerStruct { - let procedure_name = "push_device_revoke" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - var answ: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") - let semaphore6 = DispatchSemaphore(value: 0) - - let params = ["devices": dev_list] as Dictionary - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Revoke as NSString); - - PushKConstants.logger.debug("params: \(dev_list)") - PushKConstants.logger.debug("push_device_revoke: \(procedure_name) url string is \(urlString)") - PushKConstants.logger.debug("\(procedure_name) params is \"devices\": \(dev_list)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString) as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - //request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - + //update device registration on push server + func pushUpdateRegistration(fcmToken: String, xPushSessionId: String, xPushAuthToken:String) -> PushKGeneralAnswerStruct { + PushKConstants.logger.debug("Start function pushUpdateRegistration") + let semaphore = DispatchSemaphore(value: 0) + var genAnsw: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") + let requestURL = PushKConstants.platformBrancActive.urlHttpUpdate + PushKConstants.logger.debug("pushUpdateRegistration url string is \(requestURL)") + + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("pushUpdateRegistration request X-Hyber-Timestamp is \(String(timet))") + + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) + + let params = [ + "fcmToken": fcmToken, + "osType": "ios", + "osVersion": PushKConstants.devOSVersion, + "deviceType": PushKConstants.localizedModel, + "deviceName": UIDevice.modelName, + "sdkVersion": PushKConstants.sdkVersion + ] as Dictionary + + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + + Task{ + serverDataResponses.updateResponse = await makePostRequest(headersRequest: headersRequest, params: params, url: requestURL) + semaphore.signal() + } + semaphore.wait() + + let response = serverDataResponses.updateResponse + PushKConstants.logger.debug("pushUpdateRegistration response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("pushUpdateRegistration response debugDescription is \(String(describing: response?.debugDescription))") + PushKConstants.logger.debug("pushUpdateRegistration response data is \(String(describing: response?.data))") + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("pushUpdateRegistration bodyJsonF from push server: \(bodyJson)") + + let devisParsed = self.jsonparser.updateregistrationJParse(strResp: bodyJson) + var description = "Success" - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - PushKConstants.logger.debug(sha256_auth_token) - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") + switch response?.response?.statusCode { + case 401: + description = "Failed" + UserDefaults.standard.set(false, forKey: "registrationstatus") + PushKConstants.registrationstatus = false + UserDefaults.standard.synchronize() + PushKConstants.logger.debug("pushUpdateRegistration response code is \(String(describing: response?.response!.statusCode))") + default: + description = "Failed" + PushKConstants.logger.debug("pushUpdateRegistration response code is \(String(describing: response?.response!.statusCode))") + } - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) - PushKConstants.logger.debug(params) + genAnsw = self.answerBuider.generalAnswerStruct(respCode: response?.response!.statusCode ?? 0, bodyJson: "deviceId: \(devisParsed.deviceId)", description: description) - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.error("request.httpBody error") } - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore6.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - let body_json: String = String(decoding: receivedData, as: UTF8.self) - - PushKConstants.logger.debug("push_device_revoke body_json from push server: \(body_json)") - - answ = self.answer_buider.generalAnswerStruct(resp_code: String(httpResponse.statusCode), body_json: body_json, description: "Success") - - PushKConstants.logger.debug(jsonData as Any) - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - PushKConstants.logger.debug(httpResponse.statusCode) - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - PushKConstants.logger.debug(httpResponse.debugDescription) - - switch (httpResponse.statusCode) - { - case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - + + return genAnsw + } + + //remove devices from push server + func pushDeviceRevoke(devList: [String], xPushSessionId: String, xPushAuthToken:String)->PushKGeneralAnswerStruct { + PushKConstants.logger.debug("Start function pushDeviceRevoke") + let semaphore = DispatchSemaphore(value: 0) + + + + var genAnsw: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") + + let requestURL = PushKConstants.platformBrancActive.urlHttpRevoke + PushKConstants.logger.debug("pushDeviceRevoke url string is \(requestURL)") + + + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("pushDeviceRevoke request X-Hyber-Timestamp is \(String(timet))") + + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) + + let params = ["devices": devList] as Dictionary + + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + + Task{ + serverDataResponses.revokeDeviceResponse = await makePostRequest(headersRequest: headersRequest, params: params, url: requestURL) + semaphore.signal() + } + semaphore.wait() + + let response = serverDataResponses.revokeDeviceResponse + PushKConstants.logger.debug("pushDeviceRevoke response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("pushDeviceRevoke response data is \(String(describing:response?.data))") + + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + + PushKConstants.logger.debug("pushDeviceRevoke bodyJson from push server: \(bodyJson)") + + var description = "Success" + + PushKConstants.logger.debug("pushDeviceRevoke response debugDescription is \(response.debugDescription)") + + switch response?.response?.statusCode { + case 200, 401: + UserDefaults.standard.set(false, forKey: "registrationstatus") PushKConstants.registrationstatus = false - - UserDefaults.standard.synchronize() - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") - } - case 401: - PushKConstants.registrationstatus = false - UserDefaults.standard.set(false, forKey: "registrationstatus") UserDefaults.standard.synchronize() - + PushKConstants.logger.debug("pushDeviceRevoke response code is \(String(describing: response?.response!.statusCode))") default: - PushKConstants.logger.error("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore6.signal() + description = "Failed" + PushKConstants.logger.debug("pushDeviceRevoke response code is \(String(describing: response?.response!.statusCode))") + + } - dataTask.resume() - // semaphore6.wait(timeout: DispatchTime.now() + 2) - semaphore6.wait() + genAnsw = self.answerBuider.generalAnswerStruct(respCode: response?.response!.statusCode ?? 0, bodyJson: bodyJson, description: description) - return answ + } + + return genAnsw } - //3 procedure - //for update device from push server - func push_device_update(fcm_Token: String, os_Type: String, os_Version: String, device_Type: String, device_Name: String, sdk_Version: String, X_Push_Session_Id: String, X_Push_Auth_Token:String) -> PushKGeneralAnswerStruct { - PushKConstants.logger.debug("Start function push_device_update") - let procedure_name = "push_device_update" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - var answ: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") - let semaphore5 = DispatchSemaphore(value: 0) - - let params = [ - "fcmToken": fcm_Token, - "osType": os_Type, - "osVersion": os_Version, - "deviceType": device_Type, - "deviceName": device_Name, - "sdkVersion": sdk_Version - ] as Dictionary - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Update as NSString); - PushKConstants.logger.debug("push_device_update: \(procedure_name) url string is \(urlString)") - PushKConstants.logger.debug("\(procedure_name) params is \(params.description)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString)as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - - - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") - - - - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.debug("request.httpBody error") + //get devices info from push server + func pushDevicesGetAll(xPushSessionId: String, xPushAuthToken:String) -> PushKFunAnswerGetDeviceList{ + PushKConstants.logger.debug("Start function pushDevicesGetAll") + let semaphore = DispatchSemaphore(value: 0) + + + var genAnsw: PushKFunAnswerGetDeviceList = PushKFunAnswerGetDeviceList(code: 0, result: "", description: "", body: nil) + + let requestURL = PushKConstants.platformBrancActive.urlHttpDeviceGetAll + PushKConstants.logger.debug("pushDevicesGetAll url string is \(requestURL)") + + + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("pushDevicesGetAll request X-Hyber-Timestamp is \(String(timet))") + + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) + + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(headersRequest) + + + Task{ + serverDataResponses.getAllDevicesResponse = await makeGetRequest(headersRequest: headersRequest, url: requestURL) + semaphore.signal() } - - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(params) - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore5.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_device_update body_json from push server: \(body_json)") - - let devid_parsed = self.jsonparser.updateregistrationJParse(str_resp: body_json) - - answ = self.answer_buider.generalAnswerStruct(resp_code: String(httpResponse.statusCode), body_json: "deviceId: \(devid_parsed.deviceId)", description: "Success") - - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - PushKConstants.logger.debug(jsonData as Any) - PushKConstants.logger.debug(httpResponse.statusCode) - - switch (httpResponse.statusCode) - { + semaphore.wait() + + let response = serverDataResponses.getAllDevicesResponse + PushKConstants.logger.debug("pushDevicesGetAll response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("pushDevicesGetAll response jsonData is \(String(describing: response?.debugDescription))") + PushKConstants.logger.debug("pusGetMessageHistory response data is \(String(describing: response?.data))") + + switch response?.response?.statusCode { case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") } + + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("pushDevicesGetAll bodyJson from push server: \(bodyJson)") + + + genAnsw.description = "Success" + genAnsw.result = "Ok" + genAnsw.body = self.jsonparser.getDeviceListJson(strResp: bodyJson) + PushKConstants.logger.debug("pushDevicesGetAll response code is \(String(describing: response?.response!.statusCode))") + case 401: PushKConstants.registrationstatus = false UserDefaults.standard.set(false, forKey: "registrationstatus") UserDefaults.standard.synchronize() - + PushKConstants.logger.debug("pushDevicesGetAll response code is \(String(describing: response?.response!.statusCode))") + default: - PushKConstants.logger.error("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore5.signal() + PushKConstants.logger.debug("pushDevicesGetAll response code is \(String(describing: response?.response!.statusCode))") + + } - dataTask.resume() - semaphore5.wait() - return answ + } + + + return genAnsw + } - - //4 procedure - //for get message history device from push server - func push_message_get_history(utc_time: Int, X_Push_Session_Id: String, X_Push_Auth_Token:String)->PushKFunAnswerGetMessageHistory { - var answ: PushKFunAnswerGetMessageHistory = PushKFunAnswerGetMessageHistory.init(code: 0, result: "unknown", description: "unknown", body: nil) - let procedure_name = "push_message_get_history" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - let semaphore4 = DispatchSemaphore(value: 0) - - //let escaped_utc = String(utc_time).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) + //get message history for device from push server + func pushGetMessageHistory(utcTime: Int, xPushSessionId: String, xPushAuthToken:String)->PushKFunAnswerGetMessageHistory { - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("Start function pushGetMessageHistory") + let semaphore = DispatchSemaphore(value: 0) + + var genAnsw: PushKFunAnswerGetMessageHistory = PushKFunAnswerGetMessageHistory.init(code: 0, result: "unknown", description: "unknown", body: nil) - PushKConstants.logger.debug("Generated Timestamp: \(timet)") - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("pushGetMessageHistory request X-Hyber-Timestamp is \(String(timet))") - PushKConstants.logger.debug("Generated sha256_auth_token: \(sha256_auth_token)") + let timestampForServerUrl = timet - utcTime - let timestampForServerUrl = timet - utc_time + let requestURL = String(format: "\(PushKConstants.platformBrancActive.urlHttpMessHistory)\(String(timestampForServerUrl))") + PushKConstants.logger.debug("pushGetMessageHistory url string is \(requestURL)") + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) - let urlString = NSString(format: "\(PushKConstants.platform_branch_active.url_Http_Mess_history)\(String(timestampForServerUrl))" as NSString); + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(headersRequest) - PushKConstants.logger.debug("push_message_get_history: \(procedure_name) url string is \(urlString)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString) as String) - request.httpMethod = "GET" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - - - + Task{ + serverDataResponses.historyResponse = await makeGetRequest(headersRequest: headersRequest, url: requestURL) + semaphore.signal() + } + semaphore.wait() + + let response = serverDataResponses.historyResponse + PushKConstants.logger.debug("pushGetMessageHistory response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") + PushKConstants.logger.debug("pushGetMessageHistory response data is \(String(describing: response?.data))") - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) + PushKConstants.logger.debug("pushGetMessageHistory response debugDescription is \(String(describing: response?.debugDescription))") - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore4.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - //////self.logger.file_logger(message: "\(procedure_name) response jsonData is \(jsonData??["devices"])", loglevel: ".debug") - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_message_get_history body_json from push server: \(body_json)") - - answ.code = httpResponse.statusCode - answ.body = self.jsonparser.getMessageHistoryJson(str_resp: body_json) - - //answ = self.answer_buider.general_answer(resp_code: String(httpResponse.statusCode), body_json: body_json, description: "Success") - - - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - PushKConstants.logger.debug(jsonData as Any) - PushKConstants.logger.debug(httpResponse.statusCode) - - switch (httpResponse.statusCode) - { + switch response?.response?.statusCode { case 200: - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - answ.result = "Success" - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") - } - - UserDefaults.standard.set(true, forKey: "registrationstatus") + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("pusGetMessageHistory bodyJson from push server: \(bodyJson)") + genAnsw.description = "Success" + genAnsw.result = "Ok" + genAnsw.body = self.jsonparser.getMessageHistoryJson(strResp: bodyJson) + PushKConstants.logger.debug("pushGetMessageHistory response code is \(String(describing: response?.response!.statusCode))") + case 401: PushKConstants.registrationstatus = false UserDefaults.standard.set(false, forKey: "registrationstatus") UserDefaults.standard.synchronize() - + PushKConstants.logger.debug("pushGetMessageHistory response code is \(String(describing: response?.response!.statusCode))") default: - PushKConstants.logger.debug("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore4.signal() + PushKConstants.logger.debug("pushGetMessageHistory response code is \(String(describing: response?.response!.statusCode))") } - dataTask.resume() - semaphore4.wait() - - return answ + } + + + return genAnsw + } - //5 procedure - //for send delivery report to push server - func push_message_dr(message_Id: String, received_At: String, X_Push_Session_Id: String, X_Push_Auth_Token:String)->PushKGeneralAnswerStruct { - if (message_Id != "" && message_Id != "[]" ) { - let procedure_name = "push_message_dr" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - var answ: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") - let semaphore3 = DispatchSemaphore(value: 0) - - let params = [ - "messageId":message_Id - //"receivedAt":received_At - ] as Dictionary - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Mess_dr as NSString); - PushKConstants.logger.debug("push_message_dr: \(procedure_name) url string is \(urlString)") - PushKConstants.logger.debug("\(procedure_name) params is \(params.description)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString)as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - //request.addValue(X_Hyber_Auth_Token, forHTTPHeaderField: "X-Hyber-Auth-Token") - - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) - PushKConstants.logger.debug(X_Push_Auth_Token) - PushKConstants.logger.debug(timet) - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - - PushKConstants.logger.debug(sha256_auth_token) - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") - - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) - - - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.debug("request.httpBody error") - } - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore3.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - //////self.logger.file_logger(message: "\(procedure_name) response jsonData is \(jsonData??["devices"])", loglevel: ".debug") - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_message_dr body_json from push server: \(body_json)") - - answ = self.answer_buider.generalAnswerStruct(resp_code: String(httpResponse.statusCode), body_json: body_json, description: "Success") - - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - PushKConstants.logger.debug(httpResponse.statusCode) - PushKConstants.logger.debug(jsonData as Any) - - switch (httpResponse.statusCode) - { - case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") } - - case 401: - PushKConstants.registrationstatus = false - UserDefaults.standard.set(false, forKey: "registrationstatus") - UserDefaults.standard.synchronize() - - default: - PushKConstants.logger.debug("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore3.signal() - } - dataTask.resume() - semaphore3.wait() - return answ - } else { - return self.answer_buider.generalAnswerStruct(resp_code: "700", body_json: "{\"error\":\"Incorrect input\"}", description: "Failed") - } + //check queue + func checkQueue(xPushSessionId: String, xPushAuthToken:String)->PushKFunAnswerGeneral { - } - - //6 procedure - //for message callback to push server - func push_message_callback(message_Id: String, answer: String, X_Push_Session_Id: String, X_Push_Auth_Token:String)->PushKGeneralAnswerStruct { - let procedure_name = "push_message_callback" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - let semaphore2 = DispatchSemaphore(value: 0) - var answ: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") - let params = [ - "messageId": message_Id, - "answer": answer - ] as Dictionary - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Mess_callback as NSString); - PushKConstants.logger.debug("\(procedure_name) url string is \(urlString)") - PushKConstants.logger.debug("\(procedure_name) params is \(params.description)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString)as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - - - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - print(sha256_auth_token) - - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) - - - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.debug("request.httpBody error") + var genAnsw: PushKFunAnswerGeneral = PushKFunAnswerGeneral(code: 0, result: "unknown", description: "unknown", body: "{}") + + + let requestURL = PushKConstants.platformBrancActive.pusUrlMessQueue + PushKConstants.logger.debug("checkQueue url string is \(requestURL)") + + let semaphore = DispatchSemaphore(value: 0) + + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("checkQueue request X-Hyber-Timestamp is \(String(timet))") + + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) + + let params = [:] as Dictionary + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + + Task{ + serverDataResponses.queueResponse = await makePostRequest(headersRequest: headersRequest, params: params, url: requestURL) + semaphore.signal() } + semaphore.wait() + + let response = serverDataResponses.queueResponse + PushKConstants.logger.debug("checkQueue response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("checkQueue response data is \(String(describing: response?.data))") - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - print("error: not a valid http response") - semaphore2.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_message_callback body_json from push server: \(body_json)") - - answ = self.answer_buider.generalAnswerStruct(resp_code: String(httpResponse.statusCode), body_json: body_json, description: "Success") - - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - PushKConstants.logger.debug(httpResponse.statusCode) - - switch (httpResponse.statusCode) - { - case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - PushKConstants.logger.debug(jsonData as Any) - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") } - + PushKConstants.logger.debug("checkQueue response debugDescription is \(String(describing: response?.debugDescription))") + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("checkQueue bodyJson from push server: \(bodyJson)") + + var description = "Success" + + switch response?.response?.statusCode { case 401: + description = "Failed" PushKConstants.registrationstatus = false UserDefaults.standard.set(false, forKey: "registrationstatus") UserDefaults.standard.synchronize() + PushKConstants.logger.debug("checkQueue response code is \(String(describing: response?.response!.statusCode))") default: - PushKConstants.logger.debug("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore2.signal() + description = "Failed" + PushKConstants.logger.debug("checkQueue response code is \(String(describing: response?.response!.statusCode))") } - dataTask.resume() - semaphore2.wait() - return answ - } - - typealias CompletionHandler = (_ result:NSDictionary) -> Void - - func hardProcessingWithString(input: String, completion: (String) -> Void) { - completion("we finished!") + genAnsw = self.answerBuider.generalAnswer(respCode: response?.response!.statusCode ?? 0, bodyJson: bodyJson, description: description) + } + + return genAnsw } - //7 procedure - //for get device info from push server - func push_device_get_all(X_Push_Session_Id: String, X_Push_Auth_Token:String) -> PushKFunAnswerGetDeviceList { - var answ: PushKFunAnswerGetDeviceList = PushKFunAnswerGetDeviceList.init(code: 0, result: "unknown", description: "unknown", body: nil) + //send delivery report to push server + func sendMessageDR(messageId: String, xPushSessionId: String, xPushAuthToken:String)->PushKGeneralAnswerStruct { + if (messageId != "" && messageId != "[]" ) { + var genAnsw: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result:"unknown", description: "unknown", body: "unknown") - let procedure_name = "push_device_get_all" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) + let requestURL = PushKConstants.platformBrancActive.urlHttpMessDr + PushKConstants.logger.debug("sendMessageDR url string is \(requestURL)") let semaphore = DispatchSemaphore(value: 0) - let urlString = NSString(format: PushKConstants.platform_branch_active.url_Http_Device_getall as NSString); - PushKConstants.logger.debug("\(procedure_name) url string is \(urlString)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString) as String) - request.httpMethod = "GET" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - - let timeInterval = NSDate().timeIntervalSince1970 let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("sendMessageDR request X-Hyber-Timestamp is \(String(timet))") - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - PushKConstants.logger.debug(sha256_auth_token) + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") + let params = ["messageId":messageId] as Dictionary - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) - - - - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - print("error: not a valid http response") - semaphore.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_device_get_all body_json from push server: \(body_json)") - - answ.code = httpResponse.statusCode - answ.description = "Success" - answ.result = "Ok" - answ.body = self.jsonparser.getDeviceListJson(str_resp: body_json) - - - if let userInfo = jsonData as NSDictionary? { - let test = userInfo["devices"] - - if let userInfo2 = test as? NSDictionary { - let test2 = userInfo2 - print(test2) - } - } - - - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - switch (httpResponse.statusCode) - { - case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - - - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") - } - - case 401: - PushKConstants.registrationstatus = false - UserDefaults.standard.set(false, forKey: "registrationstatus") - UserDefaults.standard.synchronize() - - - - default: - PushKConstants.logger.debug("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - - } + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + Task{ + serverDataResponses.drResponse = await makePostRequest(headersRequest:headersRequest, params: params, url: requestURL) semaphore.signal() } - dataTask.resume() semaphore.wait() + let response = serverDataResponses.drResponse + PushKConstants.logger.debug("sendMessageDR response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 - print(answ) - - return answ - } - - - func deliveryReport(list: [String], X_Push_Session_Id: String, X_Push_Auth_Token: String,queue_answer: String) { - - if (list == [] ) - { - }else { - for i in list - { - //var messs = queue_answer as! [String: AnyObject] - - let messs2 = ["message": queue_answer as AnyObject] as [String: AnyObject] + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("sendMessageDR response data is \(String(describing:response?.data))") - NotificationCenter.default.post(name: .receivePushKData, object: nil, userInfo: messs2 ) + PushKConstants.logger.debug("sendMessageDR response debugDescription is\(String(describing: response?.debugDescription))") + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("sendMessageDR bodyJson from push server:\(bodyJson)") + + var description = "Success" - if (PushKConstants.enableDeliveryReportAutoFlag == true && PushKConstants.enableNotificationFlag == true) { - if (PushKConstants.deliveryReportLogicFlag == 1) { - functionNotificator.areNotificationsEnabled { (notificationStatus) in - debugPrint(notificationStatus) - if (notificationStatus == true) { - let res_dr = self.push_message_dr(message_Id: i, received_At: "123123122341", X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: X_Push_Auth_Token) - PushKConstants.logger.debug(res_dr) - } - } - } else if (PushKConstants.deliveryReportLogicFlag == 2) - { - let res_dr = push_message_dr(message_Id: i, received_At: "123123122341", X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: X_Push_Auth_Token) - PushKConstants.logger.debug(res_dr) - } + switch response?.response?.statusCode { + case 401: + description = "Failed" + PushKConstants.registrationstatus = false + UserDefaults.standard.set(false, forKey: "registrationstatus") + UserDefaults.standard.synchronize() + PushKConstants.logger.debug("sendMessageDR response code is \(String(describing:response?.response!.statusCode))") + default: + description = "Failed" + PushKConstants.logger.debug("sendMessageDR response code is \(String(describing:response?.response!.statusCode))") } - + genAnsw = self.answerBuider.generalAnswerStruct(respCode:response?.response!.statusCode ?? 0, bodyJson: bodyJson, description:description) } - PushKConstants.logger.debug(list) + + return genAnsw + }else{ + PushKConstants.logger.debug("sendMessageDR messageId is \(messageId)") + return self.answerBuider.generalAnswerStruct(respCode: 700, bodyJson:"{\"error\":\"Incorrect input\"}", description: "Failed") } } - func messidParse(queue_answer: String, X_Push_Session_Id: String, X_Push_Auth_Token: String)->[String] { - var listdev: [String] = [] - - let string1 = self.processor.matches(for: "\"messageId\": \"(\\S+-\\S+-\\S+-\\S+-\\S+)\"", in: queue_answer) - PushKConstants.logger.debug(string1) - - /* - let jsonData2 = try? JSONSerialization.data(withJSONObject: string1, options: []) - let jsonString2 = String(data: jsonData2!, encoding: .utf8)! - let string2 = String(jsonString2).replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - print(string2) - */ - - for jj in string1 - { - PushKConstants.logger.debug(jj) - let new2String = jj.replacingOccurrences(of: "\"messageId\": ", with: "", options: .literal, range: nil) - PushKConstants.logger.debug(new2String) - let new3String = new2String.replacingOccurrences(of: "\"", with: "", options: .literal, range: nil) - PushKConstants.logger.debug(new3String) - listdev.append(new3String) - } + //send message callback to push server + func sendMessageCallBack(messageId: String, answer: String, xPushSessionId: String,xPushAuthToken:String)->PushKGeneralAnswerStruct { - PushKConstants.logger.debug(listdev) + let semaphore = DispatchSemaphore(value: 0) + var genAnsw: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result:"unknown", description: "unknown", body: "unknown") - deliveryReport(list: listdev, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: X_Push_Auth_Token, queue_answer: queue_answer) + let requestURL = PushKConstants.platformBrancActive.urlHttpMesscallback + PushKConstants.logger.debug("sendMessaeCallBack url string is \(requestURL)") - return listdev - } - - //8 queue procedure - func push_check_queue(X_Push_Session_Id: String, X_Push_Auth_Token:String)->PushKFunAnswerGeneral { - let procedure_name = "push_check_queue" - let configuration = URLSessionConfiguration .default - let session = URLSession(configuration: configuration) - let semaphore2 = DispatchSemaphore(value: 0) - var answ: PushKFunAnswerGeneral? - let params = [:] as Dictionary - let urlString = NSString(format: PushKConstants.platform_branch_active.push_url_mess_queue as NSString); - PushKConstants.logger.debug("\(procedure_name) url string is \(urlString)") - PushKConstants.logger.debug("\(procedure_name) params is \(params.description)") - - let request : NSMutableURLRequest = NSMutableURLRequest() - request.url = URL(string: NSString(format: "%@", urlString)as String) - request.httpMethod = "POST" - request.timeoutInterval = 30 - request.addValue("application/json", forHTTPHeaderField: "Content-Type") - request.addValue("application/json", forHTTPHeaderField: "Accept") - //request.addValue("test", forHTTPHeaderField: "X-Hyber-Client-API-Key") - request.addValue(X_Push_Session_Id, forHTTPHeaderField: "X-Hyber-Session-Id") - //request.addValue("1234567890", forHTTPHeaderField: "X-Hyber-IOS-Bundle-Id") - //request.addValue("1", forHTTPHeaderField: "X-Hyber-App-Fingerprint") - - - let timeInterval = NSDate().timeIntervalSince1970 - let timet = Int(round(timeInterval) as Double) - let auth_token = X_Push_Auth_Token + ":" + String(timet) - let sha256_auth_token = auth_token.sha256() - PushKConstants.logger.debug(sha256_auth_token) - PushKConstants.logger.debug("\(procedure_name) request X-Hyber-Timestamp is \(String(timet))") - - request.addValue(String(timet), forHTTPHeaderField: "X-Hyber-Timestamp") - request.addValue(sha256_auth_token, forHTTPHeaderField: "X-Hyber-Auth-Token") - PushKConstants.logger.debug(request.allHTTPHeaderFields as Any) - PushKConstants.logger.debug(request.httpBody as Any) - do { - request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) - } catch { - PushKConstants.logger.debug("request.httpBody error") + let timeInterval = NSDate().timeIntervalSince1970 + let timet = Int(round(timeInterval) as Double) + PushKConstants.logger.debug("sendMessaeCallBack request X-Hyber-Timestamp is \(String(timet))") + + let authToken = xPushAuthToken + ":" + String(timet) + let sha256AuthToken = authToken.sha256() + PushKConstants.logger.debug(sha256AuthToken) + + let params = [ + "messageId": messageId, + "answer": answer + ] as Dictionary + + let headersRequest: HTTPHeaders = [ + "Content-Type": "application/json", + "Accept": "application/json", + "X-Hyber-Session-Id": xPushSessionId, + "X-Hyber-Timestamp": String(timet), + "X-Hyber-Auth-Token": sha256AuthToken + ] + PushKConstants.logger.debug(params) + PushKConstants.logger.debug(headersRequest) + Task{ + serverDataResponses.callBackResponse = await makePostRequest(headersRequest:headersRequest, params: params, url: requestURL) + semaphore.signal() } + semaphore.wait() - let dataTask = session.dataTask(with: request as URLRequest) - { - ( data: Data?, response: URLResponse?, error: Error?) -> Void in - // 1: Check HTTP Response for successful GET request - guard let httpResponse = response as? HTTPURLResponse, let receivedData = data - else { - PushKConstants.logger.error("error: not a valid http response") - semaphore2.signal() - return - } - - let jsonData = try? JSONSerialization.jsonObject(with: receivedData, options: []) as? Dictionary - let body_json: String = String(decoding: receivedData, as: UTF8.self) - PushKConstants.logger.debug("push_device_get_all body_json from push server: \(body_json)") - - answ = self.answer_buider.generalAnswer(resp_code: httpResponse.statusCode, body_json: body_json, description: "Success") - - PushKConstants.logger.debug("\(procedure_name) response jsonData is \(String(describing: jsonData))") - PushKConstants.logger.debug("\(procedure_name) response code is \(httpResponse.statusCode)") - PushKConstants.logger.debug("\(procedure_name) response data is \(String(describing: data))") - PushKConstants.logger.debug("\(procedure_name) response debugDescription is \(httpResponse.debugDescription)") - - PushKConstants.logger.debug(httpResponse.statusCode) - - switch (httpResponse.statusCode) - { - case 200: - - let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue) - - - - PushKConstants.logger.debug(jsonData as Any) - - let dataa = String(response ?? "") - - - PushKConstants.logger.debug(self.messidParse(queue_answer: dataa, X_Push_Session_Id: X_Push_Session_Id, X_Push_Auth_Token: X_Push_Auth_Token)) - - - if response == "SUCCESS" - { - PushKConstants.logger.debug("\(procedure_name) success response body is \(String(describing: response))") - - } - + let response = serverDataResponses.callBackResponse + PushKConstants.logger.debug("sendMessaeCallBack response is \(String(describing: response))") + genAnsw.code = response?.response?.statusCode ?? 500 + + if response != nil && response?.error == nil{ + PushKConstants.logger.debug("sendMessaeCallBack response data is \(String(describing:response?.data))") + + PushKConstants.logger.debug("sendMessaeCallBack response debugDescription is\(String(describing: response?.debugDescription))") + let bodyJson: String = String(decoding: (response?.data)!, as: UTF8.self) + PushKConstants.logger.debug("sendMessaeCallBack bodyJson from push server:\(bodyJson)") + + var description = "Success" + + switch response?.response?.statusCode { case 401: + description = "Failed" PushKConstants.registrationstatus = false UserDefaults.standard.set(false, forKey: "registrationstatus") UserDefaults.standard.synchronize() + PushKConstants.logger.debug("sendMessaeCallBack response code is\(String(describing: response?.response!.statusCode))") default: - PushKConstants.logger.debug("\(procedure_name) save profile POST request got response \(httpResponse.statusCode)") - } - semaphore2.signal() + description = "Failed" + PushKConstants.logger.debug("sendMessaeCallBack response code is\(String(describing: response?.response!.statusCode))") } - dataTask.resume() - semaphore2.wait() - return answ ?? PushKFunAnswerGeneral(code: 710, result: "Unknown error", description: "Nullable statement", body: "{}") + genAnsw = self.answerBuider.generalAnswerStruct(respCode:response?.response!.statusCode ?? 0, bodyJson: bodyJson, description:description) + } + + + return genAnsw } + + + + func makePostRequest(headersRequest: HTTPHeaders, params: Parameters, url: String) async -> DataResponse{ + let task = AF.request(url, method: .post, parameters: params, encoding:JSONEncoding.default, headers: headersRequest){$0.timeoutInterval = 15}.serializingString() + let response = await task.response + //{$0.timeoutInterval = 30} + return response + + } + + func makeGetRequest(headersRequest: HTTPHeaders, url: String) async -> DataResponse{ + let task = AF.request(url, method: .get, encoding:JSONEncoding.default, headers: headersRequest){$0.timeoutInterval = 15}.serializingString() + let response = await task.response + + return response + } + + +} + + +internal class DataResponses{ + + var registerResponse : DataResponse! + var getAllDevicesResponse : DataResponse! + var revokeDeviceResponse : DataResponse! + var updateResponse : DataResponse! + var historyResponse: DataResponse! + var callBackResponse: DataResponse! + var drResponse: DataResponse! + var queueResponse: DataResponse! + } diff --git a/PushSDK/core/AnswerBuilder.swift b/PushSDK/core/AnswerBuilder.swift new file mode 100644 index 00000000..45711ac1 --- /dev/null +++ b/PushSDK/core/AnswerBuilder.swift @@ -0,0 +1,39 @@ +// +// AnswerBuider.swift +// GMSPushSDKIOS +// +// Created by o.korniienko on 22.08.22. +// + +import Foundation + + +internal class AnswerBuilder { + + func generalAnswerStruct(respCode: Int, bodyJson: String, description: String) -> PushKGeneralAnswerStruct{ + var resp: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") + if (respCode==200){ + resp = PushKGeneralAnswerStruct.init(code: 200, result: "Ok", description: "Success", body: bodyJson) + } else if (respCode==400){ + resp = PushKGeneralAnswerStruct.init(code: 400, result: "Failed", description: "Failed", body: "unknown") + } else { + + resp = PushKGeneralAnswerStruct.init(code: respCode, result: "Failed", description: description, body: bodyJson) + } + return resp + } + + func generalAnswer(respCode: Int, bodyJson: String, description: String) -> PushKFunAnswerGeneral{ + var resp: PushKFunAnswerGeneral = PushKFunAnswerGeneral(code: 710, result: "Unknown", description: description, body: bodyJson) + + if (respCode == 200){ + resp = PushKFunAnswerGeneral(code: respCode, result: "Ok", description: "Success", body: bodyJson) + } else if (respCode==400){ + resp = PushKFunAnswerGeneral(code: respCode, result: "Failed", description: "Failed", body: "unknown") + + } else { + resp = PushKFunAnswerGeneral(code: respCode, result: "Failed", description: description, body: bodyJson) + } + return resp + } +} diff --git a/PushSDK/core/DataSaver.swift b/PushSDK/core/DataSaver.swift new file mode 100644 index 00000000..52d784a0 --- /dev/null +++ b/PushSDK/core/DataSaver.swift @@ -0,0 +1,41 @@ +// +// DataSaver.swift +// GMSPushSDKIOS +// +// Created by o.korniienko on 22.08.22. +// + +import Foundation + +internal class PushKDatabase { + internal func saveDataAfterRegisterOk(userPhone: String, + token: String, + deviceId: String, + userPassword: String, + createdAt: String, + userId: String + ) { + UserDefaults.standard.set(userPhone, forKey: "push_user_msisdn") + PushKConstants.pushUserMsisdn = userPhone + + UserDefaults.standard.set(token, forKey: "push_registration_token") + PushKConstants.pushRegistratioToken = token + + UserDefaults.standard.set(true, forKey: "registrationstatus") + PushKConstants.registrationstatus = true + + UserDefaults.standard.set(deviceId, forKey: "deviceId") + PushKConstants.deviceId = deviceId + + UserDefaults.standard.set(userId, forKey: "userId") + PushKConstants.userId = userId + + UserDefaults.standard.set(createdAt, forKey: "created_at") + PushKConstants.createdAt = createdAt + + UserDefaults.standard.set(userPassword, forKey: "push_user_password") + PushKConstants.pushUserPassword = userPassword + + UserDefaults.standard.synchronize() + } +} diff --git a/PushSDK/settings/JsonParser.swift b/PushSDK/core/JsonParser.swift similarity index 86% rename from PushSDK/settings/JsonParser.swift rename to PushSDK/core/JsonParser.swift index 0c7165e8..a1c980ee 100644 --- a/PushSDK/settings/JsonParser.swift +++ b/PushSDK/core/JsonParser.swift @@ -1,17 +1,15 @@ // -// json_parser.swift -// PushSDK +// JsonParser.swift +// GMSPushSDKIOS // -// Created by Kirill Kotov on 29/03/2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 22.08.22. // import Foundation -import JSON -class PushKAnswParser { +class PushServerAnswParser { - func registerJParse(str_resp: String) -> RegisterJsonParse { + func registerJParse(strResp: String) -> RegisterJsonParse { struct RegisterSession: Decodable { enum Category: String, Decodable { case swift, combine, debugging, xcode @@ -45,7 +43,7 @@ class PushKAnswParser { } - guard let jsonData = str_resp.data(using: .utf8) else { return RegisterJsonParse(deviceId: "", token: "", userId: 0, userPhone: "", createdAt: "")} + guard let jsonData = strResp.data(using: .utf8) else { return RegisterJsonParse(deviceId: "", token: "", userId: 0, userPhone: "", createdAt: "")} //let jsonData = JSON.self(using: .utf8)! do { let parsedJson: FullRegister = try JSONDecoder().decode(FullRegister.self, from: jsonData) @@ -61,7 +59,7 @@ class PushKAnswParser { - func updateregistrationJParse(str_resp: String) -> UpdateRegJsonParse + func updateregistrationJParse(strResp: String) -> UpdateRegJsonParse { struct RegisterUpdate: Decodable { enum Category: String, Decodable { @@ -70,7 +68,7 @@ class PushKAnswParser { let deviceId: Int } - guard let jsonData = str_resp.data(using: .utf8) else { return UpdateRegJsonParse(deviceId: "")} + guard let jsonData = strResp.data(using: .utf8) else { return UpdateRegJsonParse(deviceId: "")} //let jsonData = JSON.self(using: .utf8)! do { @@ -84,7 +82,7 @@ class PushKAnswParser { } - func getDeviceListJson(str_resp: String) -> PushKGetDeviceList + func getDeviceListJson(strResp: String) -> PushKGetDeviceList { struct PushKGetDeviceListParse: Decodable { @@ -108,7 +106,7 @@ class PushKAnswParser { let devices: [PushKGetDeviceListParse] } - guard let jsonData = str_resp.data(using: .utf8) else { return PushKGetDeviceList(devices: [])} + guard let jsonData = strResp.data(using: .utf8) else { return PushKGetDeviceList(devices: [])} do { let parsedJson: DevListRespAll = try JSONDecoder().decode(DevListRespAll.self, from: jsonData) @@ -129,7 +127,7 @@ class PushKAnswParser { } - func getMessageHistoryJson(str_resp: String) -> MessagesListResponse + func getMessageHistoryJson(strResp: String) -> MessagesListResponse { struct ImageResponseParse: Decodable { @@ -173,7 +171,7 @@ class PushKAnswParser { - guard let jsonData = str_resp.data(using: .utf8) else { return MessagesListResponse(limitDays: 0, limitMessages: 0, lastTime: 0, messages: [])} + guard let jsonData = strResp.data(using: .utf8) else { return MessagesListResponse(limitDays: 0, limitMessages: 0, lastTime: 0, messages: [])} do { let parsedJson: MessagesListRespAll = try JSONDecoder().decode(MessagesListRespAll.self, from: jsonData) @@ -198,11 +196,11 @@ class PushKAnswParser { - static func messageIncomingJson(str_resp: String) -> FullFirebaseMessageStr + static func messageIncomingJson(strResp: String) -> FullFirebaseMessageStr { - PushKConstants.logger.debug("messageIncomingJson start: str_resp: \(str_resp)") + PushKConstants.logger.debug("messageIncomingJson start: strResp: \(strResp)") - let str_resp_transform = str_resp.replacingOccurrences(of: "\"{", with: "{", options: .literal, range: nil).replacingOccurrences(of: "}\"", with: "}", options: .literal, range: nil) + let strRespTransform = strResp.replacingOccurrences(of: "\"{", with: "{", options: .literal, range: nil).replacingOccurrences(of: "}\"", with: "}", options: .literal, range: nil) struct ButtonResponseParse: Decodable { @@ -263,10 +261,10 @@ class PushKAnswParser { } - PushKConstants.logger.debug("messageIncomingJson before decoding: str_resp_transform: \(str_resp_transform)") + PushKConstants.logger.debug("messageIncomingJson before decoding: strRespTransform: \(strRespTransform)") - guard let jsonData = str_resp_transform.data(using: .utf8) else { return FullFirebaseMessageStr(aps: MessApsDataStr(contentAvailable: 0), message: MessagesResponseStr(phone: "", messageId: "", title: "", body: "", image: ImageResponse(url: ""), button: ButtonResponse(text: "", url: ""), time: "", partner: ""),googleCSenderId: "", gcmMessageId: "")} + guard let jsonData = strRespTransform.data(using: .utf8) else { return FullFirebaseMessageStr(aps: MessApsDataStr(contentAvailable: 0), message: MessagesResponseStr(phone: "", messageId: "", title: "", body: "", image: ImageResponse(url: ""), button: ButtonResponse(text: "", url: ""), time: "", partner: ""),googleCSenderId: "", gcmMessageId: "")} PushKConstants.logger.debug("messageIncomingJson transformed to data") @@ -303,4 +301,3 @@ class PushKAnswParser { } - diff --git a/PushSDK/core/MemorySaver.swift b/PushSDK/core/MemorySaver.swift deleted file mode 100644 index 40af73ca..00000000 --- a/PushSDK/core/MemorySaver.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// memory_saver.swift -// PushSDK -// -// Created by Kirill Kotov on 11/11/2020. -// Copyright © 2020 PUSHER. All rights reserved. -// - -import Foundation - - -internal class PushKDatabase { - internal func saveDataAfterRegisterOk(user_Phone: String, - token: String, - device_id: String, - user_Password: String, - created_at: String, - user_id: String - ) { - UserDefaults.standard.set(user_Phone, forKey: "push_user_msisdn") - PushKConstants.push_user_msisdn = user_Phone - - UserDefaults.standard.set(token, forKey: "push_registration_token") - PushKConstants.push_registration_token = token - - UserDefaults.standard.set(true, forKey: "registrationstatus") - PushKConstants.registrationstatus = true - - UserDefaults.standard.set(device_id, forKey: "deviceId") - PushKConstants.deviceId = device_id - - UserDefaults.standard.set(user_id, forKey: "userId") - PushKConstants.userId = user_id - - UserDefaults.standard.set(created_at, forKey: "created_at") - PushKConstants.created_at = created_at - - UserDefaults.standard.set(user_Password, forKey: "push_user_password") - PushKConstants.push_user_password = user_Password - - UserDefaults.standard.synchronize() - } -} - diff --git a/PushSDK/core/Parser.swift b/PushSDK/core/Parser.swift index d07ee186..232221e5 100644 --- a/PushSDK/core/Parser.swift +++ b/PushSDK/core/Parser.swift @@ -1,9 +1,8 @@ // -// parser.swift -// PushSDK +// Parser.swift +// GMSPushSDKIOS // -// Created by Kirill Kotov on 09/01/2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 22.08.22. // import Foundation @@ -13,43 +12,43 @@ public class PusherKParser { public init() {} - let processor = PushKProcessing.init() + //let processor = PushProcessing.init() - public func urlsInitialization(branchUrl: String, method_paths: BranchStructObj) { + public func urlsInitialization(branchUrl: String, methodPaths: BranchStructObj) { if (branchUrl.last == "/") { - PushKConstants.platform_branch_active = BranchStructObj( - url_Http_Update: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Update, - url_Http_Registration: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Registration, - url_Http_Revoke: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Revoke, - url_Http_Device_getall: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Device_getall, - url_Http_Mess_callback: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_callback, - url_Http_Mess_dr: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_dr, - push_url_mess_queue: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.push_url_mess_queue, - url_Http_Mess_history: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_history) + PushKConstants.platformBrancActive = BranchStructObj( + urlHttpUpdate: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpUpdate, + urlHttpRegistration: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpRegistration, + urlHttpRevoke: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpRevoke, + urlHttpDeviceGetAll: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpDeviceGetAll, + urlHttpMesscallback: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMesscallback, + urlHttpMessDr: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMessDr, + pusUrlMessQueue: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.pusUrlMessQueue, + urlHttpMessHistory: branchUrl + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMessHistory) } else { - PushKConstants.platform_branch_active = BranchStructObj( - url_Http_Update: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Update, - url_Http_Registration: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Registration, - url_Http_Revoke: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Revoke, - url_Http_Device_getall: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Device_getall, - url_Http_Mess_callback: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_callback, - url_Http_Mess_dr: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_dr, - push_url_mess_queue: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.push_url_mess_queue, - url_Http_Mess_history: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_history) + PushKConstants.platformBrancActive = BranchStructObj( + urlHttpUpdate: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpUpdate, + urlHttpRegistration: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpRegistration, + urlHttpRevoke: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpRevoke, + urlHttpDeviceGetAll: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpDeviceGetAll, + urlHttpMesscallback: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMesscallback, + urlHttpMessDr: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMessDr, + pusUrlMessQueue: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.pusUrlMessQueue, + urlHttpMessHistory: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + methodPaths.urlHttpMessHistory) } } - public func messIdParser(message_from_push_server: String) -> String + public func messIdParser(messageFromPushServer: String) -> String { - let newStringFun = message_from_push_server.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) + let newStringFun = messageFromPushServer.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) //textOutput.text = newString PushKConstants.logger.debug(newStringFun) - let deviceIdFunc = self.processor.matches(for: "\"messageId\":\"(.{4,9}-.{3,9}-.{3,9}-.{3,9}-.{4,15})\"", in: newStringFun) + let deviceIdFunc = self.matches(for: "\"messageId\":\"(.{4,9}-.{3,9}-.{3,9}-.{3,9}-.{4,15})\"", in: newStringFun) PushKConstants.logger.debug(deviceIdFunc) guard let jsonDataTransf = try? JSONSerialization.data(withJSONObject: deviceIdFunc, options: []) else { return "" } @@ -62,4 +61,21 @@ public class PusherKParser { return finalString } + + public func matches(for regex: String, in text: String) -> [String] { + do { + let regex = try NSRegularExpression(pattern: regex) + let results = regex.matches(in: text, + range: NSRange(text.startIndex..., in: text)) + + let resp = results.map { + String(text[Range($0.range, in: text)!]) + } + return resp + } catch let error { + PushKConstants.logger.error("invalid regex: \(error.localizedDescription)") + return [] + } + } } + diff --git a/PushSDK/core/notifications.swift b/PushSDK/core/notifications.swift deleted file mode 100644 index 0f60f1f6..00000000 --- a/PushSDK/core/notifications.swift +++ /dev/null @@ -1,141 +0,0 @@ -// -// notifications.swift -// PushSDK -// -// Created by Kirill Kotov on 10/11/2020. -// Copyright © 2020 PUSHER. All rights reserved. -// - -import Foundation -import UserNotifications - - -class PushKNotification { - - func pushNotificationManualWithImage(image_url: String = "", - time_delay: TimeInterval = 0.1, - content_title: String = "", - content_subtitle: String = "", - content_body: String, - userInfo: [AnyHashable: Any] - ) { - PushKConstants.logger.debug("push_notification_manual_wImage input: image_url: \(image_url), time_delay: \(time_delay), content_title: \(content_title), content_subtitle: \(content_subtitle), content_body: \(content_body)") - - let content = UNMutableNotificationContent() - PushKConstants.pusher_counter += 1 - let ident = PushKConstants.pusher_counter - PushKConstants.logger.debug("content.badge ident: \(ident)") - content.badge = ident as NSNumber - content.userInfo = userInfo - - if content_title != "" {content.title = content_title} - if content_subtitle != "" {content.subtitle = content_subtitle} - if content_body != "" {content.body = content_body} - content.categoryIdentifier = "pushKActionCategory" - - content.sound = UNNotificationSound.default - - PushKConstants.logger.debug("push_notification_manual_wImage started") - if (image_url != "") { - - if let url = URL(string: image_url) { - - let pathExtension = url.pathExtension - - let task = URLSession.shared.downloadTask(with: url) { (result, response, error) in - if let result = result { - - let identifier = ProcessInfo.processInfo.globallyUniqueString - let target = FileManager.default.temporaryDirectory.appendingPathComponent(identifier).appendingPathExtension(pathExtension) - - do { - try FileManager.default.moveItem(at: result, to: target) - - let attachment = try UNNotificationAttachment(identifier: identifier, url: target, options: nil) - content.attachments.append(attachment) - - let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: time_delay, repeats: false) - - let notification = UNNotificationRequest(identifier: Date().description, content: content, trigger: trigger) - UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in - if let error = error { - PushKConstants.logger.error("UNUserNotificationCenter error: \(error.localizedDescription)") - } - }) - } - catch { - PushKConstants.logger.error("UNUserNotificationCenter error2: \(error.localizedDescription)") - } - } else { - let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: time_delay, repeats: false) - - let notification = UNNotificationRequest(identifier: Date().description, content: content, trigger: trigger) - UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in - if let error = error { - PushKConstants.logger.error("UNUserNotificationCenter error3: \(error.localizedDescription)") - } - }) - } - } - task.resume() - } - - } else { - let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: time_delay, repeats: false) - - let notification = UNNotificationRequest(identifier: Date().description, content: content, trigger: trigger) - UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in - if let error = error { - PushKConstants.logger.error("UNUserNotificationCenter error4: \(error.localizedDescription)") - } - }) - } - - PushKConstants.logger.debug("push_notification_manual_wImage finished") - - } - - - func areNotificationsEnabled(completion:@escaping (Bool)->Swift.Void) { - var notificationStatus: Bool = false - let current = UNUserNotificationCenter.current() - current.getNotificationSettings(completionHandler: { permission in - switch permission.authorizationStatus { - case .authorized: - PushKConstants.logger.debug("User granted permission for notification") - notificationStatus = true - completion(notificationStatus) - break - case .denied: - PushKConstants.logger.debug("User denied notification permission") - notificationStatus = false - completion(notificationStatus) - break - case .notDetermined: - PushKConstants.logger.debug("Notification permission haven't been asked yet") - notificationStatus = false - completion(notificationStatus) - break - case .provisional: - // @available(iOS 12.0, *) - PushKConstants.logger.debug("The application is authorized to post non-interruptive user notifications.") - notificationStatus = true - completion(notificationStatus) - break - case .ephemeral: - // @available(iOS 14.0, *) - PushKConstants.logger.debug("The application is temporarily authorized to post notifications. Only available to app clips.") - notificationStatus = false - completion(notificationStatus) - break - @unknown default: - PushKConstants.logger.debug("Unknow Status") - notificationStatus = false - completion(notificationStatus) - break - } - }) - } - - -} diff --git a/PushSDK/core/parser.swift b/PushSDK/core/parser.swift deleted file mode 100644 index d07ee186..00000000 --- a/PushSDK/core/parser.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// parser.swift -// PushSDK -// -// Created by Kirill Kotov on 09/01/2020. -// Copyright © 2020 PUSHER. All rights reserved. -// - -import Foundation - - -public class PusherKParser { - - public init() {} - - let processor = PushKProcessing.init() - - public func urlsInitialization(branchUrl: String, method_paths: BranchStructObj) { - if (branchUrl.last == "/") - { - PushKConstants.platform_branch_active = BranchStructObj( - url_Http_Update: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Update, - url_Http_Registration: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Registration, - url_Http_Revoke: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Revoke, - url_Http_Device_getall: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Device_getall, - url_Http_Mess_callback: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_callback, - url_Http_Mess_dr: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_dr, - push_url_mess_queue: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.push_url_mess_queue, - url_Http_Mess_history: branchUrl + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_history) - } - else - { - PushKConstants.platform_branch_active = BranchStructObj( - url_Http_Update: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Update, - url_Http_Registration: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Registration, - url_Http_Revoke: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Revoke, - url_Http_Device_getall: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Device_getall, - url_Http_Mess_callback: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_callback, - url_Http_Mess_dr: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_dr, - push_url_mess_queue: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.push_url_mess_queue, - url_Http_Mess_history: branchUrl + "/" + PushKConstants.serverSdkVersion + "/" + method_paths.url_Http_Mess_history) - } - } - - public func messIdParser(message_from_push_server: String) -> String - { - - let newStringFun = message_from_push_server.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - //textOutput.text = newString - PushKConstants.logger.debug(newStringFun) - - let deviceIdFunc = self.processor.matches(for: "\"messageId\":\"(.{4,9}-.{3,9}-.{3,9}-.{3,9}-.{4,15})\"", in: newStringFun) - PushKConstants.logger.debug(deviceIdFunc) - - guard let jsonDataTransf = try? JSONSerialization.data(withJSONObject: deviceIdFunc, options: []) else { return "" } - let jsonString = String(data: jsonDataTransf, encoding: .utf8) ?? "" - let newString = String(jsonString).replacingOccurrences(of: "\\", with: "", options: .literal, range: nil) - PushKConstants.logger.debug(newString) - - let iterationString = newString.replacingOccurrences(of: "[\"\"messageId\":\"", with: "", options: .literal, range: nil) - let finalString = iterationString.replacingOccurrences(of: "\",\"\"]", with: "", options: .literal, range: nil) - - return finalString - } -} diff --git a/PushSDK/firebase/FireBaseHelpers.swift b/PushSDK/firebase/FireBaseHelpers.swift new file mode 100644 index 00000000..741fcc2e --- /dev/null +++ b/PushSDK/firebase/FireBaseHelpers.swift @@ -0,0 +1,41 @@ +// +// FireBaseHelpers.swift +// GMSPushSDKIOS +// +// Created by o.korniienko on 22.08.22. +// + +import Foundation +import FirebaseMessaging +import FirebaseCore +//import FirebaseInstanceID +import FirebaseInstallations + +internal class PushSdkFirHelpers { + static func firebaseUpdateToken() -> String { + PushKConstants.logger.debug("Start firebaseUpdateToken") + + Installations.installations().authTokenForcingRefresh(true, completion: { (token, error) in + if let error = error { + PushKConstants.logger.debug("Error fetching remote instance ID: \(error)") + return + } + guard let token = token else { return } + + PushKConstants.logger.debug("Remote Instance ID token: \(token.authToken)") + + }) + + PushKConstants.logger.debug("answToken token: \(PushKConstants.firebaseRegistrationToken ?? "")") + + let tokenFcm = String(Messaging.messaging().fcmToken ?? "") + if (tokenFcm != "") { + UserDefaults.standard.set(tokenFcm, forKey: "firebase_registration_token") + PushKConstants.firebaseRegistrationToken = tokenFcm + UserDefaults.standard.synchronize() + PushKConstants.logger.debug("FCM token: \(tokenFcm)") + } + + return PushKConstants.firebaseRegistrationToken ?? "" + } +} diff --git a/PushSDK/firebase/FirebaseHelpers.swift b/PushSDK/firebase/FirebaseHelpers.swift deleted file mode 100644 index ea4989f9..00000000 --- a/PushSDK/firebase/FirebaseHelpers.swift +++ /dev/null @@ -1,63 +0,0 @@ -// -// FirebaseHelpers.swift -// PushSDK -// -// Created by KirillKotov on 20.11.2020. -// Copyright © 2020 PUSHER. All rights reserved. -// - -import Foundation -import FirebaseMessaging -import FirebaseCore -//import FirebaseInstanceID -import FirebaseInstallations - -internal class PushSdkFirHelpers { - static func firebaseUpdateToken() -> String { - PushKConstants.logger.debug("Start firebaseUpdateToken") - - /* - InstanceID.instanceID().instanceID { (result, error) in - PushKConstants.logger.debug("Processing firebaseUpdateToken result: \(result?.token ?? ""), error: \(error.debugDescription )") - if let error = error { - PushKConstants.logger.debug("Error fetching remote instance ID: \(error)") - } else if let result = result { - if (result.token != "") { - UserDefaults.standard.set(result.token, forKey: "firebase_registration_token") - PushKConstants.firebase_registration_token = result.token - UserDefaults.standard.synchronize() - PushKConstants.logger.debug("Remote instance ID token: \(result.token)") - } - } - } - - PushKConstants.logger.debug("answToken token: \(PushKConstants.firebase_registration_token ?? "")") - */ - - - Installations.installations().authTokenForcingRefresh(true, completion: { (token, error) in - if let error = error { - PushKConstants.logger.debug("Error fetching remote instance ID: \(error)") - return - } - guard let token = token else { return } - - PushKConstants.logger.debug("Remote Instance ID token: \(token.authToken)") - - }) - - PushKConstants.logger.debug("answToken token: \(PushKConstants.firebase_registration_token ?? "")") - - let tokenFcm = String(Messaging.messaging().fcmToken ?? "") - if (tokenFcm != "") { - UserDefaults.standard.set(tokenFcm, forKey: "firebase_registration_token") - PushKConstants.firebase_registration_token = tokenFcm - UserDefaults.standard.synchronize() - PushKConstants.logger.debug("FCM token: \(tokenFcm)") - } - - return PushKConstants.firebase_registration_token ?? "" - } -} - - diff --git a/PushSDK/logger/Benchmarker.swift b/PushSDK/logger/Benchmarker.swift deleted file mode 100755 index d09e52c5..00000000 --- a/PushSDK/logger/Benchmarker.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// - -import Foundation - -internal class Benchmarker { - typealias Result = ( - description: String?, - average: Double, - relativeStandardDeviation: Double - ) - - - func measure(_ description: String? = nil, iterations n: Int = 10, block: () -> Void) -> Result { - precondition(n >= 1, "Iteration must be greater or equal to 1.") - - let durations = (0.. Void) -> Double { - let date = Date() - - block() - - return abs(date.timeIntervalSinceNow) - } - - private func average(_ durations: [Double]) -> Double { - return durations.reduce(0, +) / Double(durations.count) - } - - private func standardDeviation(_ average: Double, durations: [Double]) -> Double { - return durations.reduce(0) { sum, duration in - return sum + pow(duration - average, 2) - } - } -} diff --git a/PushSDK/logger/Formatter.swift b/PushSDK/logger/Formatter.swift deleted file mode 100755 index c1361ebf..00000000 --- a/PushSDK/logger/Formatter.swift +++ /dev/null @@ -1,175 +0,0 @@ -// -// - -public enum Component { - case date(String) - case message - case level - case file(fullPath: Bool, fileExtension: Bool) - case line - case column - case function - case location - case block(() -> Any?) -} - -public class Formatters {} - -public class Formatter: Formatters { - /// The formatter format. - private var format: String - - /// The formatter components. - private var components: [Component] - - /// The date formatter. - fileprivate let dateFormatter = DateFormatter() - - /// The formatter logger. - internal weak var logger: Logger! - - /// The formatter textual representation. - internal var description: String { - return String(format: format, arguments: components.map { (component: Component) -> CVarArg in - return String(describing: component).uppercased() - }) - } - - public convenience init(_ format: String, _ components: Component...) { - self.init(format, components) - } - - public init(_ format: String, _ components: [Component]) { - self.format = format - self.components = components - } - - internal func format(level: Level, items: [Any], separator: String, terminator: String, file: String, line: Int, column: Int, function: String, date: Date) -> String { - let arguments = components.map { (component: Component) -> CVarArg in - switch component { - case .date(let dateFormat): - return format(date: date, dateFormat: dateFormat) - case .file(let fullPath, let fileExtension): - return format(file: file, fullPath: fullPath, fileExtension: fileExtension) - case .function: - return String(function) - case .line: - return String(line) - case .column: - return String(column) - case .level: - return format(level: level) - case .message: - return items.map({ String(describing: $0) }).joined(separator: separator) - case .location: - return format(file: file, line: line) - case .block(let block): - return block().flatMap({ String(describing: $0) }) ?? "" - } - } - - return String(format: format, arguments: arguments) + terminator - } - - func format(description: String?, average: Double, relativeStandardDeviation: Double, file: String, line: Int, column: Int, function: String, date: Date) -> String { - - let arguments = components.map { (component: Component) -> CVarArg in - switch component { - case .date(let dateFormat): - return format(date: date, dateFormat: dateFormat) - case .file(let fullPath, let fileExtension): - return format(file: file, fullPath: fullPath, fileExtension: fileExtension) - case .function: - return String(function) - case .line: - return String(line) - case .column: - return String(column) - case .level: - return format(description: description) - case .message: - return format(average: average, relativeStandardDeviation: relativeStandardDeviation) - case .location: - return format(file: file, line: line) - case .block(let block): - return block().flatMap({ String(describing: $0) }) ?? "" - } - } - - return String(format: format, arguments: arguments) - } -} - -private extension Formatter { - - func format(date: Date, dateFormat: String) -> String { - dateFormatter.dateFormat = dateFormat - return dateFormatter.string(from: date) - } - - func format(file: String, fullPath: Bool, fileExtension: Bool) -> String { - var file = file - - if !fullPath { file = file.lastPathComponent } - if !fileExtension { file = file.stringByDeletingPathExtension } - - return file - } - - func format(file: String, line: Int) -> String { - return [ - format(file: file, fullPath: false, fileExtension: true), - String(line) - ].joined(separator: ":") - } - - func format(level: Level) -> String { - let text = level.description - - if let color = logger.theme?.colors[level] { - return text.withColor(color) - } - - return text - } - - func format(description: String?) -> String { - var text = "MEASURE" - - if let color = logger.theme?.colors[.debug] { - text = text.withColor(color) - } - - if let description = description { - text = "\(text) \(description)" - } - - return text - } - - func format(average: Double, relativeStandardDeviation: Double) -> String { - let average = format(average: average) - let relativeStandardDeviation = format(relativeStandardDeviation: relativeStandardDeviation) - - return "Time: \(average) sec (\(relativeStandardDeviation) STDEV)" - } - - func format(average: Double) -> String { - return String(format: "%.3f", average) - } - - func format(durations: [Double]) -> String { - var format = Array(repeating: "%.6f", count: durations.count).joined(separator: ", ") - format = "[\(format)]" - - return String(format: format, arguments: durations.map{ $0 as CVarArg }) - } - - func format(standardDeviation: Double) -> String { - return String(format: "%.6f", standardDeviation) - } - - func format(relativeStandardDeviation: Double) -> String { - return String(format: "%.3f%%", relativeStandardDeviation) - } -} diff --git a/PushSDK/logger/Formatters.swift b/PushSDK/logger/Formatters.swift deleted file mode 100755 index b4ea28f3..00000000 --- a/PushSDK/logger/Formatters.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// Formatters.swift -// Hyber-SDK -// -// Created by Kirill Kotov on 10/27/16. -// Incuube -// -import Foundation - -extension Formatters { - public static let `default` = Formatter("[%@] %@ %@: %@", [ - .date("yyyy-MM-dd HH:mm:ss.SSS"), - .location, - .level, - .message - ]) - - public static let minimal = Formatter("%@: %@", [ - .level, - .message - ]) - - public static let detailed = Formatter("[%@] %@.%@:%@ %@: %@", [ - .date("yyyy-MM-dd HH:mm:ss.SSS"), - .file(fullPath: false, fileExtension: false), - .function, - .line, - .level, - .message - ]) -} diff --git a/PushSDK/logger/Log.h b/PushSDK/logger/Log.h deleted file mode 100755 index e44f2d78..00000000 --- a/PushSDK/logger/Log.h +++ /dev/null @@ -1,12 +0,0 @@ -// -// Log.h -// Hyber-SDK -// -// Created by Taras on 10/27/16. -// Incuube -// - -@import Foundation; - -FOUNDATION_EXPORT double LogVersionNumber; -FOUNDATION_EXPORT const unsigned char LogVersionString[]; diff --git a/PushSDK/logger/PushLogger.swift b/PushSDK/logger/PushLogger.swift deleted file mode 100755 index f7258845..00000000 --- a/PushSDK/logger/PushLogger.swift +++ /dev/null @@ -1,138 +0,0 @@ -// -// -import Foundation - -public let HyberLogger = HyberSDK.hyberLog - -public extension HyberSDK { - static let hyberLog : Logger = { - let log = Logger() - return log - }() -} - -private let benchmarker = Benchmarker() - -public enum Level { - - case trace, debug, info, warning, error - - var description: String { - - switch self { - case .trace: return "✅ SPTrace" - case .debug: return "🐞SPDEBUG" - case .info: return "❗️SPInfo" - case .warning: return "⚠️ SPWarinig" - case .error: return "❌ SPERROR" - } - - } -} - -extension Level: Comparable {} - -public func ==(x: Level, y: Level) -> Bool { - return x.hashValue == y.hashValue -} - -public func <(x: Level, y: Level) -> Bool { - return x.hashValue < y.hashValue -} - -open class Logger { - - public var enabled: Bool = true - - public var formatter: Formatter { - didSet { formatter.logger = self } - } - - public var theme: Theme? - - public var minLevel: Level - - public var format: String { - return formatter.description - } - - public var colors: String { - return theme?.description ?? "" - } - - private let queue = DispatchQueue(label: "SP.log") - - - public init(formatter: Formatter = .default, theme: Theme? = nil, minLevel: Level = .trace) { - self.formatter = formatter - self.theme = theme - self.minLevel = minLevel - - formatter.logger = self - } - - open func trace(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { - log(.trace, items, separator, terminator, file, line, column, function) - } - - open func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { - log(.debug, items, separator, terminator, file, line, column, function) - } - - open func info(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { - log(.info, items, separator, terminator, file, line, column, function) - } - - open func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { - log(.warning, items, separator, terminator, file, line, column, function) - } - - open func error(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { - log(.error, items, separator, terminator, file, line, column, function) - } - - private func log(_ level: Level, _ items: [Any], _ separator: String, _ terminator: String, _ file: String, _ line: Int, _ column: Int, _ function: String) { - guard enabled && level >= minLevel else { return } - - let date = Date() - - let result = formatter.format( - level: level, - items: items, - separator: separator, - terminator: terminator, - file: file, - line: line, - column: column, - function: function, - date: date - ) - - queue.async { - Swift.print(result, separator: "", terminator: "") - } - } - - public func measure(_ description: String? = nil, iterations n: Int = 10, file: String = #file, line: Int = #line, column: Int = #column, function: String = #function, block: () -> Void) { - guard enabled && .debug >= minLevel else { return } - - let measure = benchmarker.measure(description, iterations: n, block: block) - - let date = Date() - - let result = formatter.format( - description: measure.description, - average: measure.average, - relativeStandardDeviation: measure.relativeStandardDeviation, - file: file, - line: line, - column: column, - function: function, - date: date - ) - - queue.async { - Swift.print(result) - } - } -} diff --git a/PushSDK/logger/Theme.swift b/PushSDK/logger/Theme.swift deleted file mode 100755 index 2d707b98..00000000 --- a/PushSDK/logger/Theme.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// - -public class Themes {} - -public class Theme: Themes { - internal var colors: [Level: String] - - internal var description: String { - return colors.keys.sorted().map { - $0.description.withColor(colors[$0]!) - }.joined(separator: " ") - } - - - public init(trace: String, debug: String, info: String, warning: String, error: String) { - self.colors = [ - .trace: Theme.formatHex(trace), - .debug: Theme.formatHex(debug), - .info: Theme.formatHex(info), - .warning: Theme.formatHex(warning), - .error: Theme.formatHex(error) - ] - } - - private static func formatHex(_ hex: String) -> String { - let scanner = Scanner(string: hex) - var hex: UInt32 = 0 - - scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#") - scanner.scanHexInt32(&hex) - - let r = (hex & 0xFF0000) >> 16 - let g = (hex & 0xFF00) >> 8 - let b = (hex & 0xFF) - - return [r, g, b].map({ String($0) }).joined(separator: ",") - } -} - - diff --git a/PushSDK/logger/Themes.swift b/PushSDK/logger/Themes.swift deleted file mode 100755 index 393f31d9..00000000 --- a/PushSDK/logger/Themes.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// Themes.swift -// Hyber-SDK -// -// Created by Kirill Kotov on 10/27/16. -// Incuube -// - -extension Themes { - public static let `default` = Theme( - trace: "#C8C8C8", - debug: "#0000FF", - info: "#00FF00", - warning: "#FFFB00", - error: "#FF0000" - ) - - public static let dusk = Theme( - trace: "#FFFFFF", - debug: "#526EDA", - info: "#93C96A", - warning: "#D28F5A", - error: "#E44347" - ) - - public static let midnight = Theme( - trace: "#FFFFFF", - debug: "#527EFF", - info: "#08FA95", - warning: "#EB905A", - error: "#FF4647" - ) - - public static let tomorrow = Theme( - trace: "#4D4D4C", - debug: "#4271AE", - info: "#718C00", - warning: "#EAB700", - error: "#C82829" - ) - - public static let tomorrowNight = Theme( - trace: "#C5C8C6", - debug: "#81A2BE", - info: "#B5BD68", - warning: "#F0C674", - error: "#CC6666" - ) - - public static let tomorrowNightEighties = Theme( - trace: "#CCCCCC", - debug: "#6699CC", - info: "#99CC99", - warning: "#FFCC66", - error: "#F2777A" - ) - - public static let tomorrowNightBright = Theme( - trace: "#EAEAEA", - debug: "#7AA6DA", - info: "#B9CA4A", - warning: "#E7C547", - error: "#D54E53" - ) -} diff --git a/PushSDK/logger/Utilities.swift b/PushSDK/logger/Utilities.swift deleted file mode 100755 index a5fe7b79..00000000 --- a/PushSDK/logger/Utilities.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// Utilities.swift -// Hyber-SDK -// -// Created by Kirill Kotov on 10/27/16. -// Incuube -// - -internal extension String { - /// The last path component of the receiver. - var lastPathComponent: String { - return NSString(string: self).lastPathComponent - } - - /// A new string made by deleting the extension from the receiver. - var stringByDeletingPathExtension: String { - return NSString(string: self).deletingPathExtension - } - - /** - Returns a string colored with the specified color. - - - parameter color: The string representation of the color. - - - returns: A string colored with the specified color. - */ - func withColor(_ color: String) -> String { - return "\u{001b}[fg\(color);\(self)\u{001b}[;" - } -} diff --git a/PushSDK/models/DataStructures.swift b/PushSDK/models/DataStructures.swift index b71128f9..2b57c9c1 100644 --- a/PushSDK/models/DataStructures.swift +++ b/PushSDK/models/DataStructures.swift @@ -1,12 +1,10 @@ // // DataStructures.swift -// PushSDK +// GMSPushSDKIOS // -// Created by Kirill Kotov on 20.11.2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 22.08.22. // - import Foundation public struct PushKFunAnswerRegister { @@ -71,18 +69,18 @@ public struct PushKGetDeviceList { public var devices: [PushKGetDevice] public func toString() -> String { - var answ_result = "" + var answResult = "" for h in devices { - let current_str = h.toString() - if answ_result == "" { - answ_result = "[" + answ_result + current_str + let currentStr = h.toString() + if answResult == "" { + answResult = "[" + answResult + currentStr } else { - answ_result = answ_result + ", " + current_str + answResult = answResult + ", " + currentStr } } - answ_result = answ_result + "]" - return answ_result + answResult = answResult + "]" + return answResult } } @@ -156,27 +154,27 @@ public struct MessagesListResponse { public var messages: [MessagesResponseStr] public func toString() -> String { - var answ_result = "MessagesListResponse(limitDays: \(limitDays ?? 0), limitMessages: \(limitMessages ?? 0), lastTime: \(lastTime ?? 0), messages: " - var ans_mess = "" + var answResult = "MessagesListResponse(limitDays: \(limitDays ?? 0), limitMessages: \(limitMessages ?? 0), lastTime: \(lastTime ?? 0), messages: " + var ansMess = "" if (messages.count != 0) { for h in messages { - let current_str = h.toString() - if ans_mess == "" { - ans_mess = "[" + ans_mess + current_str + let currenStr = h.toString() + if ansMess == "" { + ansMess = "[" + ansMess + currenStr } else { - ans_mess = ans_mess + ", " + ans_mess + ansMess = ansMess + ", " + currenStr } } - ans_mess = ans_mess + "]" - answ_result = answ_result + ans_mess + ")" + ansMess = ansMess + "]" + answResult = answResult + ansMess + ")" } else { - answ_result = answ_result + "[])" + answResult = answResult + "[])" } - return answ_result + return answResult } } @@ -213,14 +211,12 @@ public struct PushKMess { } public struct BranchStructObj { - var url_Http_Update: String - var url_Http_Registration: String - var url_Http_Revoke: String - var url_Http_Device_getall: String - var url_Http_Mess_callback: String - var url_Http_Mess_dr: String - var push_url_mess_queue: String - var url_Http_Mess_history: String + var urlHttpUpdate: String + var urlHttpRegistration: String + var urlHttpRevoke: String + var urlHttpDeviceGetAll: String + var urlHttpMesscallback: String + var urlHttpMessDr: String + var pusUrlMessQueue: String + var urlHttpMessHistory: String } - - diff --git a/PushSDK/settings/AddFunctions.swift b/PushSDK/settings/AddFunctions.swift deleted file mode 100644 index cb9fb9bd..00000000 --- a/PushSDK/settings/AddFunctions.swift +++ /dev/null @@ -1,30 +0,0 @@ -// -// add_functions.swift -// test222 -// -// Created by Kirill Kotov on 28/04/2019. -// Copyright © 2019 ard. All rights reserved. -// - -import Foundation - -class PushKProcessing { - - - public func matches(for regex: String, in text: String) -> [String] { - do { - let regex = try NSRegularExpression(pattern: regex) - let results = regex.matches(in: text, - range: NSRange(text.startIndex..., in: text)) - - let resp = results.map { - String(text[Range($0.range, in: text)!]) - } - return resp - } catch let error { - PushKConstants.logger.error("invalid regex: \(error.localizedDescription)") - return [] - } - } - -} diff --git a/PushSDK/Extensions.swift b/PushSDK/settings/Extensions.swift similarity index 98% rename from PushSDK/Extensions.swift rename to PushSDK/settings/Extensions.swift index ce8e88e1..0af6f3ce 100644 --- a/PushSDK/Extensions.swift +++ b/PushSDK/settings/Extensions.swift @@ -1,9 +1,8 @@ // // Extensions.swift -// PushSDK +// GMSPushSDKIOS // -// Created by Kirill Kotov on 20.11.2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 22.08.22. // import Foundation @@ -125,4 +124,3 @@ public extension UIDevice { }() } - diff --git a/PushSDK/settings/PushAnswerFunc.swift b/PushSDK/settings/PushAnswerFunc.swift deleted file mode 100644 index 7d657932..00000000 --- a/PushSDK/settings/PushAnswerFunc.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// push_answer_func.swift -// PushDemo -// -// Created by Kirill Kotov on 28/09/2019. -// Copyright © 2019 ard. All rights reserved. -// - -import Foundation - -internal class AnswerBuider { - - func generalAnswerStruct(resp_code: String, body_json: String, description: String) -> PushKGeneralAnswerStruct{ - var resp: PushKGeneralAnswerStruct = PushKGeneralAnswerStruct.init(code: 0, result: "unknown", description: "unknown", body: "unknown") - if (resp_code=="200"){ - resp = PushKGeneralAnswerStruct.init(code: 200, result: "Ok", description: "Success", body: body_json) - } else if (resp_code=="400"){ - resp = PushKGeneralAnswerStruct.init(code: 400, result: "Failed", description: "Failed", body: "unknown") - } else { - - resp = PushKGeneralAnswerStruct.init(code: Int(resp_code) ?? 0, result: "Failed", description: "Failed", body: body_json) - } - return resp - } - - func generalAnswer(resp_code: Int, body_json: String, description: String) -> PushKFunAnswerGeneral{ - var resp: PushKFunAnswerGeneral = PushKFunAnswerGeneral(code: 710, result: "Unknown", description: description, body: body_json) - - if (resp_code == 200){ - resp = PushKFunAnswerGeneral(code: resp_code, result: "Ok", description: "Success", body: body_json) - } else if (resp_code==400){ - resp = PushKFunAnswerGeneral(code: resp_code, result: "Failed", description: "Failed", body: "unknown") - - } else { - resp = PushKFunAnswerGeneral(code: resp_code, result: "Failed", description: description, body: body_json) - } - return resp - } -} diff --git a/PushSDK/settings/params.swift b/PushSDK/settings/PushConstants.swift similarity index 51% rename from PushSDK/settings/params.swift rename to PushSDK/settings/PushConstants.swift index 73fecf02..6402f01d 100644 --- a/PushSDK/settings/params.swift +++ b/PushSDK/settings/PushConstants.swift @@ -1,12 +1,12 @@ // +// PushConstants.swift +// GMSPushSDKIOS // -// Created by Kirill Kotov on 28/04/2019. -// Copyright © 2019 ard. All rights reserved. +// Created by o.korniienko on 22.08.22. // import Foundation import CoreData -import UIKit import SwiftyBeaver @@ -14,41 +14,39 @@ import SwiftyBeaver public struct PushKConstants { public static var registrationstatus = UserDefaults.standard.bool(forKey: "registrationstatus") - public static var push_registration_token = UserDefaults.standard.string(forKey: "push_registration_token") + public static var pushRegistratioToken = UserDefaults.standard.string(forKey: "push_registration_token") public static var deviceId = UserDefaults.standard.string(forKey: "deviceId") public static var userId = UserDefaults.standard.string(forKey: "userId") - public static var created_at = UserDefaults.standard.string(forKey: "created_at") + public static var createdAt = UserDefaults.standard.string(forKey: "created_at") - public static var push_user_msisdn = UserDefaults.standard.string(forKey: "push_user_msisdn") - public static var push_user_password = UserDefaults.standard.string(forKey: "push_user_password") - public static var firebase_registration_token = UserDefaults.standard.string(forKey: "firebase_registration_token") - public static var platform_branch_active: BranchStructObj = PushSDKVar.branchMasterValue + public static var pushUserMsisdn = UserDefaults.standard.string(forKey: "push_user_msisdn") + public static var pushUserPassword = UserDefaults.standard.string(forKey: "push_user_password") + public static var firebaseRegistrationToken = UserDefaults.standard.string(forKey: "firebase_registration_token") + public static var platformBrancActive: BranchStructObj = PushSDKVar.branchMasterValue public static let logger = SwiftyBeaver.self let kOSType = "ios" static let serverSdkVersion = "2.3" - static let sdkVersion = "1.0.0.44" - static let dev_os_Version = UIDevice.current.systemVersion - static let kDeviceType = "\(UIDevice.current.model)" - static let kDeviceType2 = "\(UIDevice.current.batteryLevel)" + static let sdkVersion = "1.0.0.45" + static let devOSVersion = UIDevice.current.systemVersion + static let deviceType = "\(UIDevice.current.model)" + static let deviceType2 = "\(UIDevice.current.batteryLevel)" static let identifierForVendor = "\(String(describing: UIDevice.current.identifierForVendor))" static let localizedModel = "\(UIDevice.current.localizedModel)" static let kBundleID = Bundle.main.infoDictionary?[kCFBundleIdentifierKey as String] as? String static let kPushClientAPIKey = UserDefaults.standard.string(forKey:"clientApiKey") - static let kFCM = UserDefaults.standard.string(forKey: "fcmToken") + static let FCMToken = UserDefaults.standard.string(forKey: "fcmToken") static let branch = "master" - public static var message_buffer = "" as String + public static var messageBuffer = "" as String public static var basePushURLactive = "" as String - public static var pusher_counter = 1 + public static var pusherCounter = 1 public static var enableNotificationFlag = true as Bool public static var deliveryReportLogicFlag = 1 as Int public static var enableDeliveryReportAutoFlag = true as Bool public static var notificationPermission = false } - - diff --git a/PushSDKTests/Info.plist b/PushSDKTests/Info.plist deleted file mode 100644 index 6c40a6cd..00000000 --- a/PushSDKTests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - BNDL - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/PushSDKTests/PushSDKTests.swift b/PushSDKTests/PushSDKTests.swift index 8ab7fa71..4478995f 100644 --- a/PushSDKTests/PushSDKTests.swift +++ b/PushSDKTests/PushSDKTests.swift @@ -2,8 +2,7 @@ // PushSDKTests.swift // PushSDKTests // -// Created by Kirill Kotov on 09/01/2020. -// Copyright © 2020 PUSHER. All rights reserved. +// Created by o.korniienko on 01.09.22. // import XCTest @@ -11,72 +10,93 @@ import XCTest class PushSDKTests: XCTestCase { - var sdkInitPush = PushSDK.init(platform_branch: PushSDKVar.branchMasterValue, log_level: PushSDKVar.LOGLEVEL_DEBUG, basePushURL: "https://example.com") + var sdkInitPush: PushSDK! + let parserClass = PushServerAnswParser.init() + var userInfo : [AnyHashable:Any]! + + let regStr = "{\"session\": {\"token\": \"4fab048ae89f4b98890b3e5dc800000a\"}, \"profile\": {\"userId\": 1500051, \"userPhone\": \"1234567890\", \"createdAt\": \"2022-05-09T08:22:30.893636+00\"}, \"device\": {\"deviceId\": 13000522}}" + + let updStr = "{\"deviceId\": 13000522}" + + let allDeviceStr = "{\"devices\": [{\"id\": 10002522, \"osType\": \"ios\", \"osVersion\": \"15.5\", \"deviceType\": \"iPhone\", \"deviceName\": \"Simulator iPhone 11\", \"sdkVersion\": \"1.0.0.01\", \"createdAt\": \"2022-09-03T09:08:30.749255+00\", \"updatedAt\": \"2022-09-03T09:16:24.199570+00\"}, {\"id\": 10002524, \"osType\": \"ios\", \"osVersion\": \"15.6.1\", \"deviceType\": \"iPhone\", \"deviceName\": \"iPhone 11\", \"sdkVersion\": \"0.0.01\", \"createdAt\": \"2022-09-03T09:18:17.623499+00\", \"updatedAt\": \"2022-09-03T09:18:17.623499+00\"}]}" + + let historyStr = "{\"limitDays\": 92, \"limitMessages\": 1000, \"lastTime\": 1662197023, \"messages\": [{\"body\": \"Test Message IOS 2\", \"time\": \"2022-09-03T09:23:37.372843+00\", \"image\": {}, \"phone\": \"1234567890\", \"title\": \"Test title IOS\", \"button\": {}, \"partner\": \"push\", \"messageId\": \"16f68e44-0000-0000-0000-005056010cc1\"}, {\"body\": \"Test Message IOS 1\", \"time\": \"2022-09-03T09:23:24.414771+00\", \"image\": {}, \"phone\": \"1234567890\", \"title\": \"Test title IOS\", \"button\": {}, \"partner\": \"push\", \"messageId\": \"0f45dcae-0000-0000-0000-005056010cc1\"}]}" - let parser_class = PusherKParser.init() - - override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. + super.setUp() + sdkInitPush = PushSDK.init(platformBranch: PushSDKVar.branchMasterValue, logLevel: PushSDKVar.LOGLEVEL_DEBUG, basePushURL: "https://example.com") + userInfo = ["google.c.sender.id":"c-znu3aVxkB3redvr1HRgk", "aps": "{\"content-available\" = 1;}", "message": "{\"button\":{},\"image\":{},\"partner\":\"push\",\"phone\":\"1234567890\",\"messageId\":\"70f3cb2d-0000-0000-0000-005056010cc1\",\"time\":\"2022-09-02T12:04:49.204689+00\",\"body\":\"Test Message IOS 1\",\"title\":\"Test title IOS\"}","gcm.message_id": 8730000458611] } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() } - func testExample() { + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. + // Any test you write for XCTest can be annotated as throws and async. + // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. + // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } - func testPerformanceExample() { + func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } - func testRegistrar() { - let resp = sdkInitPush.pushRegisterNew(user_phone: "375291234567", user_password: "1", x_push_sesion_id: "123", x_push_ios_bundle_id: "123456789", X_Push_Client_API_Key: "test") - print(resp) - } - - func testGetDeviceAll() { +// func testRegistration() { +// +// } + + func testGetAllDevices() { let resp = sdkInitPush.pushGetDeviceAllFromServer().result print(resp) } - + func testGetMessHistory() { - let resp = sdkInitPush.pushGetMessageHistory(period_in_seconds: 12345) + let resp = sdkInitPush.pushGetMessageHistory(periodInSeconds: 12345) print(resp) } - + func testUpdateRegistration() { let resp = sdkInitPush.pushUpdateRegistration().description print(resp) } - + func testSendDeliveryReport() { - let resp = sdkInitPush.pushMessageDeliveryReport(message_id: "1251fqf4").description + let resp = sdkInitPush.pushMessageDeliveryReport(messageId: "1251fqf4").description print(resp) } - + func testSendMessageCallback() { - let resp = sdkInitPush.pushSendMessageCallback(message_id: "test", message_text: "privet").description + let resp = sdkInitPush.pushSendMessageCallback(messageId: "test-message-id", callbackText: "hello").description print(resp) } - + func testReqQueue() { let resp = sdkInitPush.pushCheckQueue() print(resp) } - + func testClearDeviceAll() { let resp = sdkInitPush.pushClearAllDevice() print(resp) } - - + + func testGetInfo() { let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String print(appVersion ?? "unknown_empty") @@ -85,5 +105,41 @@ class PushSDKTests: XCTestCase { print(module) } + func testNotificationParser(){ + var notif: Notification = Notification.init(name: Notification.Name("pushSDKReceiveData")) + notif.userInfo = userInfo + let result = PushSDK.parseIncomingPush(message: notif) + print(result) + + } + + func testUserInfoParser(){ + let result = PushSDK.parseIncomingPush(message: userInfo) + print(result) + } + + + func testRegParser(){ + let response = parserClass.registerJParse(strResp: regStr) + print(response) + } + func testUpdParser(){ + let response = parserClass.updateregistrationJParse(strResp: updStr) + print(response) + } + + func testAllDeviceParser(){ + let response = parserClass.getDeviceListJson(strResp: allDeviceStr) + print(response) + } + + func testHistoryParser(){ + let response = parserClass.getMessageHistoryJson(strResp: historyStr) + print(response) + } + + } + + diff --git a/README.md b/README.md index e2e3e669..7de999d0 100644 --- a/README.md +++ b/README.md @@ -1,158 +1,106 @@ +# IOS PushSDK -# Push-SDK-IOS +*** +Install and init Cocoapods.
+Open a terminal window and run $ sudo gem install cocoapods to instal Cocoapods.
+Then $ cd into your project directory and run $ pod init to create a Podfile. Important ! Before run $ pod init your project should be closed.
+To update dependencies in the Podfile run - $ pod update.
+To open your project run $ open ProjectName.xcworkspace
+More about Cocoapods and Podfile here - https://cocoapods.org, https://guides.cocoapods.org/using/the-podfile.html and https://guides.cocoapods.org/using/using-cocoapods.html. +last actual SDK version: 1.0.0.45
+To integrate PushSDK to your project with COCOAPODS (https://guides.cocoapods.org/using/the-podfile.html) add the next line in Podfile.
+pod 'PushSDK', :git => 'https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS', :branch => 'gmsapi' *** -### IMPORTANT information
-last actual SDK version: 1.0.0.44 -Integrate PushSDK to your project with COCOAPODS (https://guides.cocoapods.org/using/the-podfile.html)
-```pod 'PushSDK', :git => 'https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS', :branch => 'masterapi'``` +* Example of PushSDK initializing +```swift +let pushAdapterSdk = PushSDK.init(basePushURL: "https://push.example.com/api/", enableNotification: true, enableDeliveryReportAuto: true, deliveryReportLogic:1) +``` *** -## Using SDK - - - -Important ! Before start using SDK, configure firebase project first and upload your google-services.json file into your application directory - -* [Setting up your project to work with the SDK](https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS/wiki/Creating-App-Id-and-APNS-key) - -* [SDK functions list](https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS/wiki/SDK-functions-description) - -* [SDK answers](https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS/wiki/SDK-answers) +*** +Notification/delivery reports control +You can enable/disable displaying notification and sending delivery reports with the following optional parameters in PushSDK: +- enableNotification: Bool - enable/disable display notification. Default is true (enabled) +- enableDeliveryReportAuto: Bool - enable/disable sending delivery report. Default is true (enabled) +- deliveryReportLogic: Int - working if enableNotification is true and enableDeliveryReportAuto is true. Options of deliveryReportLogic:
+ 1 - if notification permitted in application settings, then send delivery report. Else not send report
+ 2 - always send delivery report if receive message +*** +#SDK functions description -Then initialize firebase helper functions into your AppDelegate.swift +All this functions are available from PushSDK class +For using it, create this class new instance first +*** +* New device registration. Register your device on push server ```swift +public func pushRegisterNew(userPhone: String, userPassword: String, xPushSessionId: String, xPushIOSBundleId: String, xPushClientAPIKey: String) -> PushKFunAnswerRegister - import UIKit - import PushSDK - import SwiftyBeaver - import UserNotifications - - @UIApplicationMain - public class AppDelegate: UIResponder, UIApplicationDelegate { - let fb_ad = PushSDKFirebase.init() - - public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - // Override point for customization after application launch. - FirebaseApp.configure() - fb_ad.fbInitApplication(didFinishLaunchingWithOptions: launchOptions) - UNUserNotificationCenter.current().delegate = self - return true - } - - func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { - - fb_ad.fbInitApplication(didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) - } - - public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { - fb_ad.fbInitApplication(didReceiveRemoteNotification: userInfo) - } - - - public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], - fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { - - fb_ad.fbInitApplication(didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) - } - - - public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { - fb_ad.fbInitApplication(didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) - } - } +public func pushRegisterNew(userPhone: String, userPassword: String, xPushIOSBundleId: String, xPushClientAPIKey: String)->PushKFunAnswerRegister ``` +*** -Configure processing incoming messages in ViewController.swift - +* Clear local device on server. This function clear on push server only locally saved device id ```swift - - override func viewDidLoad() { - super.viewDidLoad() - - //register in notification center - NotificationCenter.default.addObserver(self, selector: #selector(onReceiveFromPushServer(_:)), name: .receivePushKData, object: nil) - UNUserNotificationCenter.current().delegate = self - - } - - - //processing incoming data message function - @objc func onReceiveFromPushServer(_ notification: Notification) { - // Do something now - // You can process your message here - let incomMessage = PushSDK.parseIncomingPush(message: notification).messageFir - print(incomMessage.message.toString()) - textOutput.text = textOutput.text + "\n" + incomMessage.message.toString() - } +public func pushClearCurrentDevice()->PushKGeneralAnswerStruct ``` +*** -Then you can communicate with push platform by the following functions -[SDK functions list](https://github.com/GlobalMessageServices/BCS-GMS-SDK-IOS/wiki/SDK-functions-description) - -An example of using SDK functions: +* get message history ```swift - -let pushAdapterSdk = PushSDK.init(basePushURL: "https://push.example.com/api/") -let registrator: PushKFunAnswerRegister = pushAdapterSdk.pushRegisterNew(user_phone: "375291234567", user_password: "1", x_push_sesion_id: PushKConstants.firebase_registration_token ?? "", x_push_ios_bundle_id: "12345678", X_Push_Client_API_Key: "test") - -pushAdapterSdk.pushUpdateRegistration() - -pushAdapterSdk.pushGetDeviceAllFromServer() - -pushAdapterSdk.pushClearAllDevice() - +public func pushGetMessageHistory(periodInSeconds: Int) -> PushKFunAnswerGetMessageHistory ``` +*** -## Notification/delivery reports control - -You can enable/disable display notification and sending delivery reports with the following optional parameters: - -//enable/disable display notification. Default is true (enabled) -enableNotification: Bool - -//enable/disable sending delivery report. Default is true (enabled) -enableDeliveryReportAuto: Bool - -// Working if enableNotification is true and enableDeliveryReportAuto is true -// 1 - if notification permitted in application settings, then send delivery report. Else not send report -// 2 - always send delivery report if receive message -deliveryReportLogic: Int - -Then you can check notification permission with areNotificationsEnabled() public function -You can use it in synchronous and asynchronous mode - -Example: +* Check message queue ```swift -let pushAdapterSdk = PushSDK.init(basePushURL: "https://push.example.com/api/") - - -//synchronous mode -let permission = pushAdapterSdk.areNotificationsEnabled() - +public func pushCheckQueue() -> PushKFunAnswerGeneral +``` +*** -//asynchronous mode -pushAdapterSdk.areNotificationsEnabled { (notificationStatus) in - debugPrint(notificationStatus) -} +* Get all devices from server +```swift +public func pushGetDeviceAllFromServer() -> PushKFunAnswerGetDeviceList +``` +*** +* update firebase token on push server. Update your token on firebase platform first +```swift +public func pushUpdateRegistration() -> PushKGeneralAnswerStruct ``` +*** -Example class init: +* message callback +```swift +public func pushSendMessageCallback(messageId: String, callbackText: String) -> PushKGeneralAnswerStruct +``` +*** +* Send delivery report to server ```swift +public func pushMessageDeliveryReport(messageId: String) -> PushKGeneralAnswerStruct +``` +*** -let pushAdapterSdk = PushSDK.init( - basePushURL: "https://push.example.com/api/", - enableNotification: true, - enableDeliveryReportAuto: true, - deliveryReportLogic: 1 -) +* Clear all devices registered with current msisdn +```swift +public func pushClearAllDevice()->PushKGeneralAnswerStruct +``` +*** +* Parse incoming notification +```swift +public static func parseIncomingPush(message: Notification) -> PushKMess ``` +*** +* Parse incoming notification UserInfo +```swift +public static func parseIncomingPush(message: [AnyHashable : Any]) -> PushKMess +``` +*** diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 00000000..1858143e --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,8 @@ +sonar.projectKey=GlobalMessageServices_BCS-GMS-SDK-IOS +sonar.organization=globalmessageservices + + + +sonar.c.file.suffixes=- +sonar.cpp.file.suffixes=- +sonar.objc.file.suffixes=-