Repository: subhan-nadeem/EZShop Branch: master Commit: 4062df30f514 Files: 504 Total size: 102.9 MB Directory structure: gitextract_e8a7ey4n/ ├── .gitignore ├── Android/ │ ├── FaceTracker/ │ │ ├── .gitignore │ │ ├── FaceTracker.iml │ │ ├── app/ │ │ │ ├── .gitignore │ │ │ ├── app.iml │ │ │ ├── build.gradle │ │ │ ├── google-services.json │ │ │ ├── proguard-rules.pro │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── subhan_nadeem/ │ │ │ │ └── android/ │ │ │ │ └── gms/ │ │ │ │ └── samples/ │ │ │ │ └── vision/ │ │ │ │ └── face/ │ │ │ │ └── facetracker/ │ │ │ │ ├── App.java │ │ │ │ ├── FaceGraphic.java │ │ │ │ ├── FaceProximityListener.java │ │ │ │ ├── activities/ │ │ │ │ │ ├── FaceTrackingActivity.java │ │ │ │ │ └── SelectPurposeActivity.java │ │ │ │ ├── models/ │ │ │ │ │ ├── RecognitionCandidate.java │ │ │ │ │ └── User.java │ │ │ │ └── ui/ │ │ │ │ └── camera/ │ │ │ │ ├── CameraSourcePreview.java │ │ │ │ └── GraphicOverlay.java │ │ │ └── res/ │ │ │ ├── layout/ │ │ │ │ ├── activity_select_purpose.xml │ │ │ │ └── main.xml │ │ │ ├── layout-land/ │ │ │ │ └── main.xml │ │ │ └── values/ │ │ │ ├── attrs.xml │ │ │ ├── colors.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ ├── libs/ │ │ │ └── KairosSDK.jar │ │ └── settings.gradle │ └── README.md ├── Backend/ │ └── README.md ├── README.md ├── iOS/ │ ├── Manager/ │ │ └── EZShopManager/ │ │ ├── EZShopManager/ │ │ │ ├── ActivitiyIndicator.swift │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── CameraSquare.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── Contents.json │ │ │ │ ├── cat.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── logo.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── medical-notes-symbol-of-a-list-paper-on-a-clipboard.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── squarePNG.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── store.imageset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── user.imageset/ │ │ │ │ └── Contents.json │ │ │ ├── Base.lproj/ │ │ │ │ ├── LaunchScreen.storyboard │ │ │ │ └── Main.storyboard │ │ │ ├── CLFaceDetectionImagePicker.storyboard │ │ │ ├── CLFaceDetectionImagePickerViewController.h │ │ │ ├── CLFaceDetectionImagePickerViewController.m │ │ │ ├── EZShopManager-Bridging-Header.h │ │ │ ├── EnrollViewController.swift │ │ │ ├── GoogleService-Info.plist │ │ │ ├── Info.plist │ │ │ ├── InventoriesViewController.swift │ │ │ ├── Item.swift │ │ │ ├── JGUtils.swift │ │ │ ├── MySplitViewController.swift │ │ │ ├── UIImage+CL.h │ │ │ ├── UIImage+CL.m │ │ │ ├── User.swift │ │ │ ├── UserDetailsViewController.swift │ │ │ ├── UsersTableViewController.swift │ │ │ └── kairos.swift │ │ ├── EZShopManager.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcuserdata/ │ │ │ │ └── jchoi.xcuserdatad/ │ │ │ │ └── UserInterfaceState.xcuserstate │ │ │ └── xcuserdata/ │ │ │ └── jchoi.xcuserdatad/ │ │ │ └── xcschemes/ │ │ │ ├── EZShopManager.xcscheme │ │ │ └── xcschememanagement.plist │ │ ├── EZShopManager.xcworkspace/ │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcuserdata/ │ │ │ └── jchoi.xcuserdatad/ │ │ │ ├── UserInterfaceState.xcuserstate │ │ │ └── xcdebugger/ │ │ │ └── Breakpoints_v2.xcbkptlist │ │ ├── Podfile │ │ └── Pods/ │ │ ├── Alamofire/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ ├── AFError.swift │ │ │ ├── Alamofire.swift │ │ │ ├── DispatchQueue+Alamofire.swift │ │ │ ├── MultipartFormData.swift │ │ │ ├── NetworkReachabilityManager.swift │ │ │ ├── Notifications.swift │ │ │ ├── ParameterEncoding.swift │ │ │ ├── Request.swift │ │ │ ├── Response.swift │ │ │ ├── ResponseSerialization.swift │ │ │ ├── Result.swift │ │ │ ├── ServerTrustPolicy.swift │ │ │ ├── SessionDelegate.swift │ │ │ ├── SessionManager.swift │ │ │ ├── TaskDelegate.swift │ │ │ ├── Timeline.swift │ │ │ └── Validation.swift │ │ ├── AlamofireSwiftyJSON/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ └── AlamofireSwiftyJSON.swift │ │ ├── Firebase/ │ │ │ ├── Core/ │ │ │ │ └── Sources/ │ │ │ │ ├── Firebase.h │ │ │ │ └── module.modulemap │ │ │ └── README.md │ │ ├── FirebaseAnalytics/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseAnalytics.framework/ │ │ │ ├── FirebaseAnalytics │ │ │ ├── Headers/ │ │ │ │ ├── FIRAnalytics+AppDelegate.h │ │ │ │ ├── FIRAnalytics.h │ │ │ │ ├── FIRAnalyticsConfiguration.h │ │ │ │ ├── FIRApp.h │ │ │ │ ├── FIRConfiguration.h │ │ │ │ ├── FIREventNames.h │ │ │ │ ├── FIROptions.h │ │ │ │ ├── FIRParameterNames.h │ │ │ │ ├── FIRUserPropertyNames.h │ │ │ │ └── FirebaseAnalytics.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── FirebaseCore/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseCore.framework/ │ │ │ ├── FirebaseCore │ │ │ ├── Headers/ │ │ │ │ ├── FIRAnalyticsConfiguration.h │ │ │ │ ├── FIRApp.h │ │ │ │ ├── FIRConfiguration.h │ │ │ │ ├── FIRLoggerLevel.h │ │ │ │ ├── FIROptions.h │ │ │ │ └── FirebaseCore.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── FirebaseDatabase/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseDatabase.framework/ │ │ │ ├── FirebaseDatabase │ │ │ ├── Headers/ │ │ │ │ ├── FIRDataEventType.h │ │ │ │ ├── FIRDataSnapshot.h │ │ │ │ ├── FIRDatabase.h │ │ │ │ ├── FIRDatabaseQuery.h │ │ │ │ ├── FIRDatabaseReference.h │ │ │ │ ├── FIRMutableData.h │ │ │ │ ├── FIRServerValue.h │ │ │ │ ├── FIRTransactionResult.h │ │ │ │ └── FirebaseDatabase.h │ │ │ ├── Info.plist │ │ │ ├── Modules/ │ │ │ │ └── module.modulemap │ │ │ └── NOTICE │ │ ├── FirebaseInstanceID/ │ │ │ ├── CHANGELOG.md │ │ │ ├── Frameworks/ │ │ │ │ └── FirebaseInstanceID.framework/ │ │ │ │ ├── FirebaseInstanceID │ │ │ │ ├── Headers/ │ │ │ │ │ ├── FIRInstanceID.h │ │ │ │ │ └── FirebaseInstanceID.h │ │ │ │ └── Modules/ │ │ │ │ └── module.modulemap │ │ │ └── README.md │ │ ├── FirebaseStorage/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseStorage.framework/ │ │ │ ├── FirebaseStorage │ │ │ ├── Headers/ │ │ │ │ ├── FIRStorage.h │ │ │ │ ├── FIRStorageConstants.h │ │ │ │ ├── FIRStorageDownloadTask.h │ │ │ │ ├── FIRStorageMetadata.h │ │ │ │ ├── FIRStorageObservableTask.h │ │ │ │ ├── FIRStorageReference.h │ │ │ │ ├── FIRStorageTask.h │ │ │ │ ├── FIRStorageTaskSnapshot.h │ │ │ │ ├── FIRStorageUploadTask.h │ │ │ │ └── FirebaseStorage.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── GTMSessionFetcher/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ ├── GTMSessionFetcher.h │ │ │ ├── GTMSessionFetcher.m │ │ │ ├── GTMSessionFetcherLogging.h │ │ │ ├── GTMSessionFetcherLogging.m │ │ │ ├── GTMSessionFetcherService.h │ │ │ ├── GTMSessionFetcherService.m │ │ │ ├── GTMSessionUploadFetcher.h │ │ │ └── GTMSessionUploadFetcher.m │ │ ├── GoogleToolboxForMac/ │ │ │ ├── Foundation/ │ │ │ │ ├── GTMNSData+zlib.h │ │ │ │ └── GTMNSData+zlib.m │ │ │ ├── GTMDefines.h │ │ │ ├── LICENSE │ │ │ └── README.md │ │ ├── Kingfisher/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Sources/ │ │ │ ├── AnimatedImageView.swift │ │ │ ├── Box.swift │ │ │ ├── CacheSerializer.swift │ │ │ ├── Filter.swift │ │ │ ├── Image.swift │ │ │ ├── ImageCache.swift │ │ │ ├── ImageDownloader.swift │ │ │ ├── ImagePrefetcher.swift │ │ │ ├── ImageProcessor.swift │ │ │ ├── ImageTransition.swift │ │ │ ├── ImageView+Kingfisher.swift │ │ │ ├── Indicator.swift │ │ │ ├── Kingfisher.h │ │ │ ├── Kingfisher.swift │ │ │ ├── KingfisherManager.swift │ │ │ ├── KingfisherOptionsInfo.swift │ │ │ ├── RequestModifier.swift │ │ │ ├── Resource.swift │ │ │ ├── String+MD5.swift │ │ │ ├── ThreadHelper.swift │ │ │ └── UIButton+Kingfisher.swift │ │ ├── Pods.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ └── xcuserdata/ │ │ │ └── jchoi.xcuserdatad/ │ │ │ └── xcschemes/ │ │ │ ├── Alamofire.xcscheme │ │ │ ├── AlamofireSwiftyJSON.xcscheme │ │ │ ├── GTMSessionFetcher.xcscheme │ │ │ ├── GoogleToolboxForMac.xcscheme │ │ │ ├── Kingfisher.xcscheme │ │ │ ├── Pods-EZShopManager.xcscheme │ │ │ ├── SwiftyJSON.xcscheme │ │ │ └── xcschememanagement.plist │ │ ├── SwiftyJSON/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ └── SwiftyJSON.swift │ │ └── Target Support Files/ │ │ ├── Alamofire/ │ │ │ ├── Alamofire-dummy.m │ │ │ ├── Alamofire-prefix.pch │ │ │ ├── Alamofire-umbrella.h │ │ │ ├── Alamofire.modulemap │ │ │ ├── Alamofire.xcconfig │ │ │ └── Info.plist │ │ ├── AlamofireSwiftyJSON/ │ │ │ ├── AlamofireSwiftyJSON-dummy.m │ │ │ ├── AlamofireSwiftyJSON-prefix.pch │ │ │ ├── AlamofireSwiftyJSON-umbrella.h │ │ │ ├── AlamofireSwiftyJSON.modulemap │ │ │ ├── AlamofireSwiftyJSON.xcconfig │ │ │ └── Info.plist │ │ ├── GTMSessionFetcher/ │ │ │ ├── GTMSessionFetcher-dummy.m │ │ │ ├── GTMSessionFetcher-prefix.pch │ │ │ ├── GTMSessionFetcher-umbrella.h │ │ │ ├── GTMSessionFetcher.modulemap │ │ │ ├── GTMSessionFetcher.xcconfig │ │ │ └── Info.plist │ │ ├── GoogleToolboxForMac/ │ │ │ ├── GoogleToolboxForMac-dummy.m │ │ │ ├── GoogleToolboxForMac-prefix.pch │ │ │ ├── GoogleToolboxForMac-umbrella.h │ │ │ ├── GoogleToolboxForMac.modulemap │ │ │ ├── GoogleToolboxForMac.xcconfig │ │ │ └── Info.plist │ │ ├── Kingfisher/ │ │ │ ├── Info.plist │ │ │ ├── Kingfisher-dummy.m │ │ │ ├── Kingfisher-prefix.pch │ │ │ ├── Kingfisher-umbrella.h │ │ │ ├── Kingfisher.modulemap │ │ │ └── Kingfisher.xcconfig │ │ ├── Pods-EZShopManager/ │ │ │ ├── Info.plist │ │ │ ├── Pods-EZShopManager-acknowledgements.markdown │ │ │ ├── Pods-EZShopManager-acknowledgements.plist │ │ │ ├── Pods-EZShopManager-dummy.m │ │ │ ├── Pods-EZShopManager-frameworks.sh │ │ │ ├── Pods-EZShopManager-resources.sh │ │ │ ├── Pods-EZShopManager-umbrella.h │ │ │ ├── Pods-EZShopManager.debug.xcconfig │ │ │ ├── Pods-EZShopManager.modulemap │ │ │ └── Pods-EZShopManager.release.xcconfig │ │ └── SwiftyJSON/ │ │ ├── Info.plist │ │ ├── SwiftyJSON-dummy.m │ │ ├── SwiftyJSON-prefix.pch │ │ ├── SwiftyJSON-umbrella.h │ │ ├── SwiftyJSON.modulemap │ │ └── SwiftyJSON.xcconfig │ ├── README.md │ └── User/ │ └── ezshopUser/ │ ├── Podfile │ ├── Pods/ │ │ ├── Alamofire/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ ├── AFError.swift │ │ │ ├── Alamofire.swift │ │ │ ├── DispatchQueue+Alamofire.swift │ │ │ ├── MultipartFormData.swift │ │ │ ├── NetworkReachabilityManager.swift │ │ │ ├── Notifications.swift │ │ │ ├── ParameterEncoding.swift │ │ │ ├── Request.swift │ │ │ ├── Response.swift │ │ │ ├── ResponseSerialization.swift │ │ │ ├── Result.swift │ │ │ ├── ServerTrustPolicy.swift │ │ │ ├── SessionDelegate.swift │ │ │ ├── SessionManager.swift │ │ │ ├── TaskDelegate.swift │ │ │ ├── Timeline.swift │ │ │ └── Validation.swift │ │ ├── AlamofireSwiftyJSON/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ └── AlamofireSwiftyJSON.swift │ │ ├── Firebase/ │ │ │ ├── Core/ │ │ │ │ └── Sources/ │ │ │ │ ├── Firebase.h │ │ │ │ └── module.modulemap │ │ │ └── README.md │ │ ├── FirebaseAnalytics/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseAnalytics.framework/ │ │ │ ├── FirebaseAnalytics │ │ │ ├── Headers/ │ │ │ │ ├── FIRAnalytics+AppDelegate.h │ │ │ │ ├── FIRAnalytics.h │ │ │ │ ├── FIRAnalyticsConfiguration.h │ │ │ │ ├── FIRApp.h │ │ │ │ ├── FIRConfiguration.h │ │ │ │ ├── FIREventNames.h │ │ │ │ ├── FIROptions.h │ │ │ │ ├── FIRParameterNames.h │ │ │ │ ├── FIRUserPropertyNames.h │ │ │ │ └── FirebaseAnalytics.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── FirebaseCore/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseCore.framework/ │ │ │ ├── FirebaseCore │ │ │ ├── Headers/ │ │ │ │ ├── FIRAnalyticsConfiguration.h │ │ │ │ ├── FIRApp.h │ │ │ │ ├── FIRConfiguration.h │ │ │ │ ├── FIRLoggerLevel.h │ │ │ │ ├── FIROptions.h │ │ │ │ └── FirebaseCore.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── FirebaseDatabase/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseDatabase.framework/ │ │ │ ├── FirebaseDatabase │ │ │ ├── Headers/ │ │ │ │ ├── FIRDataEventType.h │ │ │ │ ├── FIRDataSnapshot.h │ │ │ │ ├── FIRDatabase.h │ │ │ │ ├── FIRDatabaseQuery.h │ │ │ │ ├── FIRDatabaseReference.h │ │ │ │ ├── FIRMutableData.h │ │ │ │ ├── FIRServerValue.h │ │ │ │ ├── FIRTransactionResult.h │ │ │ │ └── FirebaseDatabase.h │ │ │ ├── Info.plist │ │ │ ├── Modules/ │ │ │ │ └── module.modulemap │ │ │ └── NOTICE │ │ ├── FirebaseInstanceID/ │ │ │ ├── CHANGELOG.md │ │ │ ├── Frameworks/ │ │ │ │ └── FirebaseInstanceID.framework/ │ │ │ │ ├── FirebaseInstanceID │ │ │ │ ├── Headers/ │ │ │ │ │ ├── FIRInstanceID.h │ │ │ │ │ └── FirebaseInstanceID.h │ │ │ │ └── Modules/ │ │ │ │ └── module.modulemap │ │ │ └── README.md │ │ ├── FirebaseMessaging/ │ │ │ └── Frameworks/ │ │ │ └── FirebaseMessaging.framework/ │ │ │ ├── FirebaseMessaging │ │ │ ├── Headers/ │ │ │ │ ├── FIRMessaging.h │ │ │ │ └── FirebaseMessaging.h │ │ │ └── Modules/ │ │ │ └── module.modulemap │ │ ├── GoogleToolboxForMac/ │ │ │ ├── Foundation/ │ │ │ │ ├── GTMLogger.h │ │ │ │ ├── GTMLogger.m │ │ │ │ ├── GTMNSData+zlib.h │ │ │ │ └── GTMNSData+zlib.m │ │ │ ├── GTMDefines.h │ │ │ ├── LICENSE │ │ │ └── README.md │ │ ├── Kingfisher/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Sources/ │ │ │ ├── AnimatedImageView.swift │ │ │ ├── Box.swift │ │ │ ├── CacheSerializer.swift │ │ │ ├── Filter.swift │ │ │ ├── Image.swift │ │ │ ├── ImageCache.swift │ │ │ ├── ImageDownloader.swift │ │ │ ├── ImagePrefetcher.swift │ │ │ ├── ImageProcessor.swift │ │ │ ├── ImageTransition.swift │ │ │ ├── ImageView+Kingfisher.swift │ │ │ ├── Indicator.swift │ │ │ ├── Kingfisher.h │ │ │ ├── Kingfisher.swift │ │ │ ├── KingfisherManager.swift │ │ │ ├── KingfisherOptionsInfo.swift │ │ │ ├── RequestModifier.swift │ │ │ ├── Resource.swift │ │ │ ├── String+MD5.swift │ │ │ ├── ThreadHelper.swift │ │ │ └── UIButton+Kingfisher.swift │ │ ├── Pods.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ └── xcuserdata/ │ │ │ └── jchoi.xcuserdatad/ │ │ │ └── xcschemes/ │ │ │ ├── Alamofire.xcscheme │ │ │ ├── AlamofireSwiftyJSON.xcscheme │ │ │ ├── GoogleToolboxForMac.xcscheme │ │ │ ├── Kingfisher.xcscheme │ │ │ ├── Pods-ezshopUser.xcscheme │ │ │ ├── Protobuf.xcscheme │ │ │ ├── SwiftyJSON.xcscheme │ │ │ └── xcschememanagement.plist │ │ ├── Protobuf/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── objectivec/ │ │ │ ├── GPBArray.h │ │ │ ├── GPBArray.m │ │ │ ├── GPBArray_PackagePrivate.h │ │ │ ├── GPBBootstrap.h │ │ │ ├── GPBCodedInputStream.h │ │ │ ├── GPBCodedInputStream.m │ │ │ ├── GPBCodedInputStream_PackagePrivate.h │ │ │ ├── GPBCodedOutputStream.h │ │ │ ├── GPBCodedOutputStream.m │ │ │ ├── GPBCodedOutputStream_PackagePrivate.h │ │ │ ├── GPBDescriptor.h │ │ │ ├── GPBDescriptor.m │ │ │ ├── GPBDescriptor_PackagePrivate.h │ │ │ ├── GPBDictionary.h │ │ │ ├── GPBDictionary.m │ │ │ ├── GPBDictionary_PackagePrivate.h │ │ │ ├── GPBExtensionInternals.h │ │ │ ├── GPBExtensionInternals.m │ │ │ ├── GPBExtensionRegistry.h │ │ │ ├── GPBExtensionRegistry.m │ │ │ ├── GPBMessage.h │ │ │ ├── GPBMessage.m │ │ │ ├── GPBMessage_PackagePrivate.h │ │ │ ├── GPBProtocolBuffers.h │ │ │ ├── GPBProtocolBuffers_RuntimeSupport.h │ │ │ ├── GPBRootObject.h │ │ │ ├── GPBRootObject.m │ │ │ ├── GPBRootObject_PackagePrivate.h │ │ │ ├── GPBRuntimeTypes.h │ │ │ ├── GPBUnknownField.h │ │ │ ├── GPBUnknownField.m │ │ │ ├── GPBUnknownFieldSet.h │ │ │ ├── GPBUnknownFieldSet.m │ │ │ ├── GPBUnknownFieldSet_PackagePrivate.h │ │ │ ├── GPBUnknownField_PackagePrivate.h │ │ │ ├── GPBUtilities.h │ │ │ ├── GPBUtilities.m │ │ │ ├── GPBUtilities_PackagePrivate.h │ │ │ ├── GPBWellKnownTypes.h │ │ │ ├── GPBWellKnownTypes.m │ │ │ ├── GPBWireFormat.h │ │ │ ├── GPBWireFormat.m │ │ │ └── google/ │ │ │ └── protobuf/ │ │ │ ├── Any.pbobjc.h │ │ │ ├── Any.pbobjc.m │ │ │ ├── Api.pbobjc.h │ │ │ ├── Api.pbobjc.m │ │ │ ├── Duration.pbobjc.h │ │ │ ├── Duration.pbobjc.m │ │ │ ├── Empty.pbobjc.h │ │ │ ├── Empty.pbobjc.m │ │ │ ├── FieldMask.pbobjc.h │ │ │ ├── FieldMask.pbobjc.m │ │ │ ├── SourceContext.pbobjc.h │ │ │ ├── SourceContext.pbobjc.m │ │ │ ├── Struct.pbobjc.h │ │ │ ├── Struct.pbobjc.m │ │ │ ├── Timestamp.pbobjc.h │ │ │ ├── Timestamp.pbobjc.m │ │ │ ├── Type.pbobjc.h │ │ │ ├── Type.pbobjc.m │ │ │ ├── Wrappers.pbobjc.h │ │ │ └── Wrappers.pbobjc.m │ │ ├── SwiftyJSON/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── Source/ │ │ │ └── SwiftyJSON.swift │ │ └── Target Support Files/ │ │ ├── Alamofire/ │ │ │ ├── Alamofire-dummy.m │ │ │ ├── Alamofire-prefix.pch │ │ │ ├── Alamofire-umbrella.h │ │ │ ├── Alamofire.modulemap │ │ │ ├── Alamofire.xcconfig │ │ │ └── Info.plist │ │ ├── AlamofireSwiftyJSON/ │ │ │ ├── AlamofireSwiftyJSON-dummy.m │ │ │ ├── AlamofireSwiftyJSON-prefix.pch │ │ │ ├── AlamofireSwiftyJSON-umbrella.h │ │ │ ├── AlamofireSwiftyJSON.modulemap │ │ │ ├── AlamofireSwiftyJSON.xcconfig │ │ │ └── Info.plist │ │ ├── GoogleToolboxForMac/ │ │ │ ├── GoogleToolboxForMac-dummy.m │ │ │ ├── GoogleToolboxForMac-prefix.pch │ │ │ ├── GoogleToolboxForMac-umbrella.h │ │ │ ├── GoogleToolboxForMac.modulemap │ │ │ ├── GoogleToolboxForMac.xcconfig │ │ │ └── Info.plist │ │ ├── Kingfisher/ │ │ │ ├── Info.plist │ │ │ ├── Kingfisher-dummy.m │ │ │ ├── Kingfisher-prefix.pch │ │ │ ├── Kingfisher-umbrella.h │ │ │ ├── Kingfisher.modulemap │ │ │ └── Kingfisher.xcconfig │ │ ├── Pods-ezshopUser/ │ │ │ ├── Info.plist │ │ │ ├── Pods-ezshopUser-acknowledgements.markdown │ │ │ ├── Pods-ezshopUser-acknowledgements.plist │ │ │ ├── Pods-ezshopUser-dummy.m │ │ │ ├── Pods-ezshopUser-frameworks.sh │ │ │ ├── Pods-ezshopUser-resources.sh │ │ │ ├── Pods-ezshopUser-umbrella.h │ │ │ ├── Pods-ezshopUser.debug.xcconfig │ │ │ ├── Pods-ezshopUser.modulemap │ │ │ └── Pods-ezshopUser.release.xcconfig │ │ ├── Protobuf/ │ │ │ ├── Info.plist │ │ │ ├── Protobuf-dummy.m │ │ │ ├── Protobuf-prefix.pch │ │ │ ├── Protobuf-umbrella.h │ │ │ ├── Protobuf.modulemap │ │ │ └── Protobuf.xcconfig │ │ └── SwiftyJSON/ │ │ ├── Info.plist │ │ ├── SwiftyJSON-dummy.m │ │ ├── SwiftyJSON-prefix.pch │ │ ├── SwiftyJSON-umbrella.h │ │ ├── SwiftyJSON.modulemap │ │ └── SwiftyJSON.xcconfig │ ├── ezshopUser/ │ │ ├── ActivitiyIndicator.swift │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets/ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ ├── Contents.json │ │ │ └── logo.imageset/ │ │ │ └── Contents.json │ │ ├── Base.lproj/ │ │ │ └── Main.storyboard │ │ ├── CLFaceDetectionImagePicker.storyboard │ │ ├── CLFaceDetectionImagePickerViewController.h │ │ ├── CLFaceDetectionImagePickerViewController.m │ │ ├── GoogleService-Info.plist │ │ ├── HudView.swift │ │ ├── Info.plist │ │ ├── Item.swift │ │ ├── JGUtils.swift │ │ ├── UIImage+CL.h │ │ ├── UIImage+CL.m │ │ ├── User.swift │ │ ├── UserViewController.swift │ │ ├── ViewController.swift │ │ ├── ezshopUser-Bridging-Header.h │ │ ├── ezshopUser.entitlements │ │ └── kairos.swift │ ├── ezshopUser.xcodeproj/ │ │ ├── project.pbxproj │ │ ├── project.xcworkspace/ │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcuserdata/ │ │ │ └── jchoi.xcuserdatad/ │ │ │ └── UserInterfaceState.xcuserstate │ │ └── xcuserdata/ │ │ └── jchoi.xcuserdatad/ │ │ └── xcschemes/ │ │ ├── ezshopUser.xcscheme │ │ └── xcschememanagement.plist │ └── ezshopUser.xcworkspace/ │ ├── contents.xcworkspacedata │ └── xcuserdata/ │ └── jchoi.xcuserdatad/ │ ├── UserInterfaceState.xcuserstate │ └── xcdebugger/ │ └── Breakpoints_v2.xcbkptlist └── raspberry/ ├── InventoryClient.py ├── logs ├── script.py ├── script2.py └── ultrasonic.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .idea ================================================ FILE: Android/FaceTracker/.gitignore ================================================ .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures ================================================ FILE: Android/FaceTracker/FaceTracker.iml ================================================ ================================================ FILE: Android/FaceTracker/app/.gitignore ================================================ /build ================================================ FILE: Android/FaceTracker/app/app.iml ================================================ ================================================ FILE: Android/FaceTracker/app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "24.0.2" defaultConfig { applicationId "com.subhan_nadeem.android.gms.samples.vision.face.facetracker" minSdkVersion 19 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:support-v4:25.1.1' compile 'com.android.support:design:25.1.1' compile 'com.google.android.gms:play-services-vision:10.0.1' compile 'com.koushikdutta.ion:ion:2.1.9' compile 'com.google.firebase:firebase-database:10.0.1' } apply plugin: 'com.google.gms.google-services' ================================================ FILE: Android/FaceTracker/app/google-services.json ================================================ { "project_info": { "project_number": "89251823040", "firebase_url": "https://hackvalley-5be01.firebaseio.com", "project_id": "hackvalley-5be01", "storage_bucket": "hackvalley-5be01.appspot.com" }, "client": [ { "client_info": { "mobilesdk_app_id": "1:89251823040:android:5156d1cfeaf73706", "android_client_info": { "package_name": "com.subhan_nadeem.android.gms.samples.vision.face.facetracker" } }, "oauth_client": [ { "client_id": "89251823040-3c5mq2t39eh08lvj2itd5abi6p10eflm.apps.googleusercontent.com", "client_type": 1, "android_info": { "package_name": "com.subhan_nadeem.android.gms.samples.vision.face.facetracker", "certificate_hash": "9aea61c71b38a17b5872ec6aa1a4c2f3c25144a3" } }, { "client_id": "89251823040-fd3cfommlqogp5todrh25leo6hgh1bvm.apps.googleusercontent.com", "client_type": 3 } ], "api_key": [ { "current_key": "AIzaSyDxreksLNkzDpmaH9yZ3KiHTvQcNHVu_nw" } ], "services": { "analytics_service": { "status": 1 }, "appinvite_service": { "status": 2, "other_platform_oauth_client": [ { "client_id": "89251823040-okn0k3k9n4j5a0a5lacef55e7qh804gv.apps.googleusercontent.com", "client_type": 2, "ios_info": { "bundle_id": "ca.jgchoi.ezshopUser" } }, { "client_id": "89251823040-fd3cfommlqogp5todrh25leo6hgh1bvm.apps.googleusercontent.com", "client_type": 3 } ] }, "ads_service": { "status": 2 } } } ], "configuration_version": "1" } ================================================ FILE: Android/FaceTracker/app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/google/home/wilkinsonclay/android/adt-bundle-linux-x86_64-20140702/sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ================================================ FILE: Android/FaceTracker/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/App.java ================================================ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker; import android.app.Application; import android.speech.tts.TextToSpeech; import java.util.Locale; /** * Created by Subhan Nadeem on 2017-03-18. */ public class App extends Application { public static TextToSpeech ttsObj; @Override public void onCreate() { super.onCreate(); initializeTTS(); } private void initializeTTS() { ttsObj = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.ERROR) { ttsObj.setLanguage(Locale.UK); } } }); } } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/FaceGraphic.java ================================================ /* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import com.google.android.gms.vision.face.Face; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.ui.camera.GraphicOverlay; /** * Graphic instance for rendering face position, orientation, and landmarks within an associated * graphic overlay view. */ public class FaceGraphic extends GraphicOverlay.Graphic { private static final float FACE_POSITION_RADIUS = 10.0f; private static final float ID_TEXT_SIZE = 40.0f; private static final float ID_Y_OFFSET = 50.0f; private static final float ID_X_OFFSET = -50.0f; private static final float BOX_STROKE_WIDTH = 5.0f; private static final int COLOR_CHOICES[] = { Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.RED, Color.WHITE, Color.YELLOW }; private static int mCurrentColorIndex = 0; private Paint mFacePositionPaint; private Paint mIdPaint; private Paint mBoxPaint; public Face getFace() { return mFace; } private volatile Face mFace; private int mFaceId; private FaceProximityListener mFaceProximityListener; public FaceGraphic(GraphicOverlay overlay, FaceProximityListener proximityListener) { super(overlay); mFaceProximityListener = proximityListener; mCurrentColorIndex = (mCurrentColorIndex + 1) % COLOR_CHOICES.length; final int selectedColor = COLOR_CHOICES[mCurrentColorIndex]; mFacePositionPaint = new Paint(); mFacePositionPaint.setColor(selectedColor); mIdPaint = new Paint(); mIdPaint.setColor(selectedColor); mIdPaint.setTextSize(ID_TEXT_SIZE); mBoxPaint = new Paint(); mBoxPaint.setColor(selectedColor); mBoxPaint.setStyle(Paint.Style.STROKE); mBoxPaint.setStrokeWidth(BOX_STROKE_WIDTH); } public void setId(int id) { mFaceId = id; } /** * Updates the face instance from the detection of the most recent frame. Invalidates the * relevant portions of the overlay to trigger a redraw. */ public void updateFace(Face face) { mFace = face; postInvalidate(); } /** * Draws the face annotations for position on the supplied canvas. */ @Override public void draw(Canvas canvas) { Face face = mFace; if (face == null) { return; } // Draws a circle at the position of the detected face, with the face's track id below. float x = translateX(face.getPosition().x + face.getWidth() / 2); float y = translateY(face.getPosition().y + face.getHeight() / 2); canvas.drawCircle(x, y, FACE_POSITION_RADIUS, mFacePositionPaint); canvas.drawText("id: " + mFaceId, x + ID_X_OFFSET, y + ID_Y_OFFSET, mIdPaint); //canvas.drawText("happiness: " + String.format("%.2f", face.getIsSmilingProbability()), x - ID_X_OFFSET, y - ID_Y_OFFSET, mIdPaint); canvas.drawText(/*"right eye: " + String.format("%.2f", face.getIsRightEyeOpenProbability())*/ "Face width: " + mFace.getWidth(), x + ID_X_OFFSET * 2, y + ID_Y_OFFSET * 2, mIdPaint); // canvas.drawText("left eye: " + String.format("%.2f", face.getIsLeftEyeOpenProbability()), x - ID_X_OFFSET * 2, y - ID_Y_OFFSET * 2, mIdPaint); // Draws a bounding box around the face. float xOffset = scaleX(face.getWidth() / 2.0f); float yOffset = scaleY(face.getHeight() / 2.0f); float left = x - xOffset; float top = y - yOffset; float right = x + xOffset; float bottom = y + yOffset; canvas.drawRect(left, top, right, bottom, mBoxPaint); } } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/FaceProximityListener.java ================================================ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker; import com.google.android.gms.vision.face.Face; /** * Created by Subhan Nadeem on 2017-03-18. */ public interface FaceProximityListener { void onFaceProximityTrigger(Face face); } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/activities/FaceTrackingActivity.java ================================================ /* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.activities; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.speech.tts.TextToSpeech; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.Tracker; import com.google.android.gms.vision.face.Face; import com.google.android.gms.vision.face.FaceDetector; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.gson.JsonObject; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.App; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.FaceGraphic; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.FaceProximityListener; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.R; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.models.RecognitionCandidate; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.models.User; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.ui.camera.CameraSourcePreview; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.ui.camera.GraphicOverlay; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import static com.subhan_nadeem.android.gms.samples.vision.face.facetracker.App.ttsObj; /** * Activity for the face tracker app. This app detects faces with the rear facing camera, and draws * overlay graphics to indicate the position, size, and ID of each face. */ public final class FaceTrackingActivity extends AppCompatActivity implements FaceProximityListener { public static final String app_id = "4724eb0e"; public static final String api_key = "f5795e224117ac3393343c6bc14c841b"; public static final String GALLERY_ID = "ezshop"; public static final String URL_RECOGNIZE = "https://api.kairos.com/recognize"; public static final String KEY_APP_ID = "app_id"; public static final String KEY_APP_KEY = "app_key"; public static final String KEY_GALLERY_NAME = "gallery_name"; public static final String KEY_IMAGE = "image"; public static float FACE_WIDTH_PROXIMITY_TRIGGER = 200f; public static final int PURPOSE_ENTRANCE = 1; public static final int PURPOSE_EXIT = 2; public static final int PURPOSE_ITEM = 3; public static final int NO_ITEM_PICKED_UP = -1; private static final String TAG = "FaceTracker"; private static final int RC_HANDLE_GMS = 9001; // permission request codes need to be < 256 private static final int RC_HANDLE_CAMERA_PERM = 2; private static final String FIREBASE_PUSH_TOKEN = "AAAAFMfSvcA:APA91bGkiVlrAimQLWJKkdvTgF_" + "ow4KF17vq7VEkPjglNUmbvPIU3XrSe8f8pkRHr8YuVMN_4_4-HTx" + "fvngfmCCNSEo9rP3e0HG8zruRi17WPLmuKLfncAZNAN3Ch4LVLcY2XyzT-Eqm"; private static final long NUM_SECONDS_WAIT_BETWEEN_RECOGNIZE = 2; public static String EXTRA_CAMERA_PURPOSE = "cameraPurpose"; public static String URL_PUSH_NOTIFICATION = "https://fcm.googleapis.com/fcm/send"; private static int MAX_RECOGNITION_ATTEMPTS = 3; private CameraSource mCameraSource = null; private CameraSourcePreview mPreview; private GraphicOverlay mGraphicOverlay; private ProgressBar mProgressBar; private int mPurpose; private long mLastTriggerTime; private ArrayList alreadyRecognizedFacesList = new ArrayList<>(); private DatabaseReference mDatabase; private DatabaseReference mUserDatabase; private int mRecognitionAttempts; private TextView mPersonText; private DatabaseReference mEventDatabase; private int mItemPickedUp; private DatabaseReference mInventoryDatabase; private String mUserFCMToken; public static Intent newIntent(Context appContext, int cameraPurpose) { Intent i = new Intent(appContext, FaceTrackingActivity.class); i.putExtra(EXTRA_CAMERA_PURPOSE, cameraPurpose); return i; } public static void fadeIn(final View view) { view.setVisibility(View.VISIBLE); view.setAlpha(0); final int DURATION = 1000; view.animate().setDuration(DURATION).alpha(1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.setVisibility(View.VISIBLE); } }); } public static void fadeOut(final View view) { final int DURATION = 800; view.animate().setDuration(DURATION).alpha(0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.setVisibility(View.INVISIBLE); } }); } /** * Initializes the UI and initiates the creation of a face detector. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mPreview = (CameraSourcePreview) findViewById(R.id.preview); mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay); initializePermissions(); initializeProgressBar(); mLastTriggerTime = System.currentTimeMillis(); mPurpose = getIntent().getExtras().getInt(EXTRA_CAMERA_PURPOSE); mItemPickedUp = NO_ITEM_PICKED_UP; initializeSwitchCameraButton(); mDatabase = FirebaseDatabase.getInstance().getReference(); mUserDatabase = mDatabase.child("users"); mInventoryDatabase = mDatabase.child("inventories"); mEventDatabase = mDatabase.child("events"); mPersonText = (TextView) findViewById(R.id.personText); mPersonText.setVisibility(View.INVISIBLE); if (mPurpose == PURPOSE_ITEM) { listenForEvents(); } } private void listenForEvents() { mEventDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot event : dataSnapshot.getChildren()) { mItemPickedUp = Integer.parseInt(event.child("item_id").getValue().toString()); } if (mItemPickedUp != NO_ITEM_PICKED_UP) recognize(false, true); Log.d(TAG, "Event listener triggered!"); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void initializePermissions() { // Check for the camera permission before accessing the camera. If the // permission is not granted yet, request permission. int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (rc == PackageManager.PERMISSION_GRANTED) { createCameraSource(false); } else { requestCameraPermission(); } } private void initializeSwitchCameraButton() { findViewById(R.id.cameraButton).setOnClickListener(new View.OnClickListener() { boolean rearFacing = false; @Override public void onClick(View v) { rearFacing = !rearFacing; mCameraSource.stop(); mPreview.stop(); mPreview.release(); mCameraSource = null; createCameraSource(rearFacing); startCameraSource(); } }); } private void initializeProgressBar() { mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mProgressBar.setIndeterminate(true); mProgressBar.setVisibility(View.GONE); } //============================================================================================== // Camera Source Preview //============================================================================================== /** * Handles the requesting of the camera permission. This includes * showing a "Snackbar" message of why the permission is needed then * sending the request. */ private void requestCameraPermission() { Log.w(TAG, "Camera permission is not granted. Requesting permission"); final String[] permissions = new String[]{Manifest.permission.CAMERA}; if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM); return; } final Activity thisActivity = this; View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat.requestPermissions(thisActivity, permissions, RC_HANDLE_CAMERA_PERM); } }; Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.ok, listener) .show(); } /** * Creates and starts the camera. Note that this uses a higher resolution in comparison * to other detection examples to enable the barcode detector to detect small barcodes * at long distances. */ private void createCameraSource(boolean rearFacing) { int typeCamera; if (rearFacing) typeCamera = CameraSource.CAMERA_FACING_BACK; else typeCamera = CameraSource.CAMERA_FACING_FRONT; Context context = getApplicationContext(); FaceDetector detector = new FaceDetector.Builder(context) .setClassificationType(FaceDetector.ALL_CLASSIFICATIONS) .build(); detector.setProcessor( new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory()) .build()); if (!detector.isOperational()) { // Note: The first time that an app using face API is installed on a device, GMS will // download a native library to the device in order to do detection. Usually this // completes before the app is run for the first time. But if that download has not yet // completed, then the above call will not detect any faces. // // isOperational() can be used to check if the required native library is currently // available. The detector will automatically become operational once the library // download completes on device. Log.w(TAG, "Face detector dependencies are not yet available."); } mCameraSource = new CameraSource.Builder(context, detector) .setRequestedPreviewSize(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels) .setFacing(typeCamera) .setRequestedFps(30.0f) .build(); } /** * Restarts the camera. */ @Override protected void onResume() { super.onResume(); startCameraSource(); } /** * Stops the camera. */ @Override protected void onPause() { super.onPause(); mPreview.stop(); } /** * Releases the resources associated with the camera source, the associated detector, and the * rest of the processing pipeline. */ @Override protected void onDestroy() { super.onDestroy(); if (mCameraSource != null) { mCameraSource.release(); } } /** * Callback for the result from requesting permissions. This method * is invoked for every call on {@link #requestPermissions(String[], int)}. *

* Note: It is possible that the permissions request interaction * with the user is interrupted. In this case you will receive empty permissions * and results arrays which should be treated as a cancellation. *

* * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}. * @param permissions The requested permissions. Never null. * @param grantResults The grant results for the corresponding permissions * which is either {@link PackageManager#PERMISSION_GRANTED} * or {@link PackageManager#PERMISSION_DENIED}. Never null. * @see #requestPermissions(String[], int) */ @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode != RC_HANDLE_CAMERA_PERM) { Log.d(TAG, "Got unexpected permission result: " + requestCode); super.onRequestPermissionsResult(requestCode, permissions, grantResults); return; } if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "Camera permission granted - initialize the camera source"); // we have permission, so create the camerasource createCameraSource(true); return; } Log.e(TAG, "Permission not granted: results len = " + grantResults.length + " Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)")); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Face Tracker sample") .setMessage(R.string.no_camera_permission) .setPositiveButton(R.string.ok, listener) .show(); } /** * Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet * (e.g., because onResume was called before the camera source was created), this will be called * again when the camera source is created. */ private void startCameraSource() { // check that the device has play services available. int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( getApplicationContext()); if (code != ConnectionResult.SUCCESS) { Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS); dlg.show(); } if (mCameraSource != null) { try { mPreview.start(mCameraSource, mGraphicOverlay); } catch (IOException e) { Log.e(TAG, "Unable to start camera source.", e); mCameraSource.release(); mCameraSource = null; } } } @Override public void onFaceProximityTrigger(final Face face) { long timeSinceLastTrigger = System.currentTimeMillis() - mLastTriggerTime; if (timeSinceLastTrigger < TimeUnit.SECONDS.toMillis(NUM_SECONDS_WAIT_BETWEEN_RECOGNIZE)) return; alreadyRecognizedFacesList.add(face.getId()); mLastTriggerTime = System.currentTimeMillis(); mRecognitionAttempts = 1; recognize(true, false); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } private void recognize(final boolean sayRecognizingMessage, final boolean repeat) { runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "Attempting to recognize"); mProgressBar.setVisibility(View.VISIBLE); if (sayRecognizingMessage) App.ttsObj.speak("Recognizing", TextToSpeech.QUEUE_ADD, null); try { mCameraSource.takePicture(new CameraSource.ShutterCallback() { @Override public void onShutter() { } }, new CameraSource.PictureCallback() { @Override public void onPictureTaken(final byte[] bytes) { new AsyncTask() { @Override protected String doInBackground(Void... params) { return Base64.encodeToString(bytes, 0); } @Override protected void onPostExecute(String bitmap) { JsonObject json = new JsonObject(); json.addProperty(KEY_IMAGE, bitmap); json.addProperty(KEY_GALLERY_NAME, GALLERY_ID); Ion.with(getApplicationContext()) .load(URL_RECOGNIZE) .addHeader(KEY_APP_ID, app_id) .addHeader(KEY_APP_KEY, api_key) .setJsonObjectBody(json) .asString() .setCallback(new FutureCallback() { @Override public void onCompleted(Exception e, String result) { Log.d(TAG, result); mProgressBar.setVisibility(View.GONE); try { JSONObject jsonObject = new JSONObject(result); JSONArray imagesArray = jsonObject.getJSONArray("images"); JSONObject firstImageObject = imagesArray.getJSONObject(0); JSONObject transactionObject = firstImageObject.getJSONObject("transaction"); if (transactionObject.getString("status").equals("failure")) { sayErrorMessage(); return; } JSONObject candidateObject = firstImageObject.getJSONArray("candidates").getJSONObject(0); RecognitionCandidate candidate = new RecognitionCandidate(); candidate.setUUID(candidateObject.getString("subject_id")); candidate.setConfidence(candidateObject.getDouble("confidence")); candidate.setTimestamp(candidateObject.getLong("enrollment_timestamp")); if (mPurpose == PURPOSE_ENTRANCE) enterUserIntoShop(candidate); else if (mPurpose == PURPOSE_EXIT) exitUserFromShop(candidate); else if (mPurpose == PURPOSE_ITEM) onDetectItemEvent(candidate); } catch (JSONException e1) { Log.e(TAG, e1.toString()); ttsObj.speak("I couldn't recognize you!", TextToSpeech.QUEUE_ADD, null); ++mRecognitionAttempts; if (repeat) { ttsObj.speak("Trying again! Please look at the camera", TextToSpeech.QUEUE_ADD, null); (new Handler()).postDelayed(new Runnable() { @Override public void run() { recognize(false, true); } }, 5000); } } } }); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } }); } catch (RuntimeException e) { Log.e(TAG, e.toString()); Toast.makeText(FaceTrackingActivity.this, "Couldn't take photo! Try again.", Toast.LENGTH_LONG).show(); } } }); } private String mItemPersonName; private String mItemItemName; private void onDetectItemEvent(final RecognitionCandidate candidate) { final DatabaseReference userCartDatabase = mDatabase.child("store") .child(candidate.getUUID()) .child("cart"); getPersonNameForItemTTS(candidate); getItemNameForItemTTS(); userCartDatabase.addListenerForSingleValueEvent(new ValueEventListener() { boolean itemAdded = false; @Override public void onDataChange(DataSnapshot dataSnapshot) { ttsObj.speak(mItemPersonName + " picked up a "+mItemItemName, TextToSpeech.QUEUE_ADD, null); if (!itemAdded) userCartDatabase.child(String.valueOf(dataSnapshot.getChildrenCount())) .setValue(mItemPickedUp); itemAdded = true; removeEvents(); mItemPickedUp = NO_ITEM_PICKED_UP; } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void getItemNameForItemTTS() { mInventoryDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot item : dataSnapshot.getChildren()) { if (item.child("item_id").getValue().toString().equals(String.valueOf(mItemPickedUp))) { mItemItemName = item.child("item_name").getValue().toString(); return; } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void getPersonNameForItemTTS(RecognitionCandidate candidate) { mUserDatabase.child(candidate.getUUID()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); mItemPersonName = user.name; } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void removeEvents() { mEventDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot event : dataSnapshot.getChildren()) { event.getRef().setValue(null); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void exitUserFromShop(final RecognitionCandidate candidate) { getUserFirebaseToken(candidate); mUserDatabase.child(candidate.getUUID()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); String text = "Goodbye, " + user.name; showUserText(text); if (!user.is_in_store) return; mUserDatabase.child(candidate.getUUID()).child("is_in_store").setValue(false); ttsObj.speak("Goodbye, " + user.name + "! Thank you for shopping at easyshop", TextToSpeech.QUEUE_ADD, null); final DatabaseReference userCartDatabase = mDatabase.child("store") .child(candidate.getUUID()) .child("cart"); userCartDatabase.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList cartItems = new ArrayList<>(); for (DataSnapshot cartItem : dataSnapshot.getChildren()) { cartItems.add(Integer.valueOf(cartItem.getValue().toString())); } calculateCartTotal(cartItems); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void getUserFirebaseToken(RecognitionCandidate candidate) { mUserDatabase.child(candidate.getUUID()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { mUserFCMToken = dataSnapshot.child("fcm_token").getValue().toString(); } catch (Exception e) { Log.e(TAG, e.toString()); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void calculateCartTotal(final ArrayList cartItems) { mInventoryDatabase.addListenerForSingleValueEvent(new ValueEventListener() { double totalSpent = 0; @Override public void onDataChange(DataSnapshot dataSnapshot) { for (int item : cartItems) { totalSpent += Double.parseDouble( dataSnapshot .child(String.valueOf(item)) .child("item_price") .getValue().toString()); } sendPushNotification(totalSpent); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void sendPushNotification(double totalSpent) { DecimalFormat df = new DecimalFormat("0.00"); if (mUserFCMToken == null || mUserFCMToken.equals("invalid")) return; JsonObject dataObj = new JsonObject(); dataObj.addProperty("alert", "Your total is $" + df.format(totalSpent)); JsonObject notificationObj = new JsonObject(); notificationObj.addProperty("body", "Your total is $" + df.format(totalSpent)); notificationObj.addProperty("title", "Thank you for shopping at easyshop!"); JsonObject pushObj = new JsonObject(); pushObj.addProperty("to", mUserFCMToken); pushObj.addProperty("priority", "high"); pushObj.add("data", dataObj); pushObj.add("notification", notificationObj); Ion.with(getApplicationContext()) .load(URL_PUSH_NOTIFICATION) .addHeader("Authorization", "key=" + FIREBASE_PUSH_TOKEN) .setJsonObjectBody(pushObj) .asString() .setCallback(new FutureCallback() { @Override public void onCompleted(Exception e, String result) { Log.d(TAG, "PUSH RESULT: " + result); } }); mUserFCMToken = null; } private void enterUserIntoShop(final RecognitionCandidate candidate) throws JSONException { clearUserCart(candidate); mUserDatabase.child(candidate.getUUID()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); String text = "Hello, " + user.name; showUserText(text); if (user.is_in_store) return; mUserDatabase.child(candidate.getUUID()).child("is_in_store").setValue(true); ttsObj.speak("Welcome to easyshop, " + user.name, TextToSpeech.QUEUE_ADD, null); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void clearUserCart(RecognitionCandidate candidate) { mDatabase.child("store") .child(candidate.getUUID()).setValue(null); } private void showUserText(String text) { if (mPersonText.getVisibility() != View.VISIBLE) fadeIn(mPersonText); mPersonText.setText(text); mPersonText.getHandler().postDelayed(new Runnable() { @Override public void run() { fadeOut(mPersonText); } }, 5000); } private void sayErrorMessage() { ttsObj.speak("You are not enrolled in our database!", TextToSpeech.QUEUE_ADD, null); } //============================================================================================== // Graphic Face Tracker //============================================================================================== /** * Factory for creating a face tracker to be associated with a new face. The multiprocessor * uses this factory to create face trackers as needed -- one for each individual. */ private class GraphicFaceTrackerFactory implements MultiProcessor.Factory { @Override public Tracker create(Face face) { return new GraphicFaceTracker(mGraphicOverlay); } } /** * Face tracker for each detected individual. This maintains a face graphic within the app's * associated face overlay. */ private class GraphicFaceTracker extends Tracker { // Bigger is closer private GraphicOverlay mOverlay; private FaceGraphic mFaceGraphic; GraphicFaceTracker(GraphicOverlay overlay) { mOverlay = overlay; mFaceGraphic = new FaceGraphic(overlay, FaceTrackingActivity.this); } /** * Start tracking the detected face instance within the face overlay. */ @Override public void onNewItem(int faceId, Face item) { mFaceGraphic.setId(faceId); } /** * Update the position/characteristics of the face within the overlay. */ @Override public void onUpdate(FaceDetector.Detections detectionResults, Face face) { mOverlay.add(mFaceGraphic); mFaceGraphic.updateFace(face); if (face.getWidth() >= FACE_WIDTH_PROXIMITY_TRIGGER && !alreadyRecognizedFacesList.contains(face.getId()) && mPurpose != PURPOSE_ITEM) { onFaceProximityTrigger(face); } } /** * Hide the graphic when the corresponding face was not detected. This can happen for * intermediate frames temporarily (e.g., if the face was momentarily blocked from * view). */ @Override public void onMissing(FaceDetector.Detections detectionResults) { mOverlay.remove(mFaceGraphic); } /** * Called when the face is assumed to be gone for good. Remove the graphic annotation from * the overlay. */ @Override public void onDone() { alreadyRecognizedFacesList.remove((Object) mFaceGraphic.getFace().getId()); runOnUiThread(new Runnable() { @Override public void run() { } }); mOverlay.remove(mFaceGraphic); } } } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/activities/SelectPurposeActivity.java ================================================ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import com.subhan_nadeem.android.gms.samples.vision.face.facetracker.R; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class SelectPurposeActivity extends Activity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); private View mContentView; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; private View mControlsView; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.show(); } mControlsView.setVisibility(View.VISIBLE); } }; private boolean mVisible; private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(); } }; /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_purpose); mContentView = findViewById(R.id.contentView); mVisible = true; Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/coolvetica.ttf"); TextView title = (TextView)findViewById(R.id.ezshopTitle); title.setTypeface(myTypeface); findViewById(R.id.entranceCameraButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = FaceTrackingActivity .newIntent(SelectPurposeActivity.this, FaceTrackingActivity.PURPOSE_ENTRANCE); startActivity(i); } }); findViewById(R.id.exitCameraButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = FaceTrackingActivity .newIntent(SelectPurposeActivity.this, FaceTrackingActivity.PURPOSE_EXIT); startActivity(i); } }); findViewById(R.id.itemCameraButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = FaceTrackingActivity .newIntent(SelectPurposeActivity.this, FaceTrackingActivity.PURPOSE_ITEM); startActivity(i); } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } private void toggle() { if (mVisible) { hide(); } else { show(); } } private void hide() { // Hide UI first ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.hide(); } mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } @SuppressLint("InlinedApi") private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/models/RecognitionCandidate.java ================================================ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.models; /** * Created by Subhan Nadeem on 2017-03-18. */ public class RecognitionCandidate { public String getUUID() { return UUID; } public void setUUID(String UUID) { this.UUID = UUID; } public double getConfidence() { return confidence; } public void setConfidence(double confidence) { this.confidence = confidence; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } private String UUID; private double confidence; private long timestamp; } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/models/User.java ================================================ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.models; import com.google.firebase.database.IgnoreExtraProperties; /** * Created by Subhan Nadeem on 2017-03-18. */ @IgnoreExtraProperties public class User { public boolean is_in_store; public String name; public String photo; public String user_id; } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/ui/camera/CameraSourcePreview.java ================================================ /* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.ui.camera; import android.content.Context; import android.content.res.Configuration; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.ViewGroup; import com.google.android.gms.common.images.Size; import com.google.android.gms.vision.CameraSource; import java.io.IOException; public class CameraSourcePreview extends ViewGroup { private static final String TAG = "CameraSourcePreview"; private Context mContext; private SurfaceView mSurfaceView; private boolean mStartRequested; private boolean mSurfaceAvailable; private CameraSource mCameraSource; private GraphicOverlay mOverlay; public CameraSourcePreview(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mStartRequested = false; mSurfaceAvailable = false; mSurfaceView = new SurfaceView(context); mSurfaceView.getHolder().addCallback(new SurfaceCallback()); addView(mSurfaceView); } public void start(CameraSource cameraSource) throws IOException { if (cameraSource == null) { stop(); } mCameraSource = cameraSource; if (mCameraSource != null) { mStartRequested = true; startIfReady(); } } public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException { mOverlay = overlay; start(cameraSource); } public void stop() { if (mCameraSource != null) { mCameraSource.stop(); } } public void release() { if (mCameraSource != null) { mCameraSource.release(); mCameraSource = null; } } private void startIfReady() throws IOException { if (mStartRequested && mSurfaceAvailable) { mCameraSource.start(mSurfaceView.getHolder()); if (mOverlay != null) { Size size = mCameraSource.getPreviewSize(); int min = Math.min(size.getWidth(), size.getHeight()); int max = Math.max(size.getWidth(), size.getHeight()); if (isPortraitMode()) { // Swap width and height sizes when in portrait, since it will be rotated by // 90 degrees mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing()); } else { mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing()); } mOverlay.clear(); } mStartRequested = false; } } private class SurfaceCallback implements SurfaceHolder.Callback { @Override public void surfaceCreated(SurfaceHolder surface) { mSurfaceAvailable = true; try { startIfReady(); } catch (IOException e) { Log.e(TAG, "Could not start camera source.", e); } } @Override public void surfaceDestroyed(SurfaceHolder surface) { mSurfaceAvailable = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int width = 320; int height = 240; if (mCameraSource != null) { Size size = mCameraSource.getPreviewSize(); if (size != null) { width = size.getWidth(); height = size.getHeight(); } } // Swap width and height sizes when in portrait, since it will be rotated 90 degrees if (isPortraitMode()) { int tmp = width; width = height; height = tmp; } final int layoutWidth = right - left; final int layoutHeight = bottom - top; // Computes height and width for potentially doing fit width. int childWidth = layoutWidth; int childHeight = (int)(((float) layoutWidth / (float) width) * height); // If height is too tall using fit width, does fit height instead. if (childHeight > layoutHeight) { childHeight = layoutHeight; childWidth = (int)(((float) layoutHeight / (float) height) * width); } for (int i = 0; i < getChildCount(); ++i) { getChildAt(i).layout(0, 0, childWidth, childHeight); } try { startIfReady(); } catch (IOException e) { Log.e(TAG, "Could not start camera source.", e); } } private boolean isPortraitMode() { int orientation = mContext.getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { return false; } if (orientation == Configuration.ORIENTATION_PORTRAIT) { return true; } Log.d(TAG, "isPortraitMode returning false by default"); return false; } } ================================================ FILE: Android/FaceTracker/app/src/main/java/com/subhan_nadeem/android/gms/samples/vision/face/facetracker/ui/camera/GraphicOverlay.java ================================================ /* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.subhan_nadeem.android.gms.samples.vision.face.facetracker.ui.camera; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import com.google.android.gms.vision.CameraSource; import java.util.HashSet; import java.util.Set; /** * A view which renders a series of custom graphics to be overlayed on top of an associated preview * (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove * them, triggering the appropriate drawing and invalidation within the view.

* * Supports scaling and mirroring of the graphics relative the camera's preview properties. The * idea is that detection items are expressed in terms of a preview size, but need to be scaled up * to the full view size, and also mirrored in the case of the front-facing camera.

* * Associated {@link Graphic} items should use the following methods to convert to view coordinates * for the graphics that are drawn: *

    *
  1. {@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the * supplied value from the preview scale to the view scale.
  2. *
  3. {@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate * from the preview's coordinate system to the view coordinate system.
  4. *
*/ public class GraphicOverlay extends View { private final Object mLock = new Object(); private int mPreviewWidth; private float mWidthScaleFactor = 1.0f; private int mPreviewHeight; private float mHeightScaleFactor = 1.0f; private int mFacing = CameraSource.CAMERA_FACING_BACK; private Set mGraphics = new HashSet<>(); /** * Base class for a custom graphics object to be rendered within the graphic overlay. Subclass * this and implement the {@link Graphic#draw(Canvas)} method to define the * graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}. */ public static abstract class Graphic { private GraphicOverlay mOverlay; public Graphic(GraphicOverlay overlay) { mOverlay = overlay; } /** * Draw the graphic on the supplied canvas. Drawing should use the following methods to * convert to view coordinates for the graphics that are drawn: *
    *
  1. {@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of * the supplied value from the preview scale to the view scale.
  2. *
  3. {@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the * coordinate from the preview's coordinate system to the view coordinate system.
  4. *
* * @param canvas drawing canvas */ public abstract void draw(Canvas canvas); /** * Adjusts a horizontal value of the supplied value from the preview scale to the view * scale. */ public float scaleX(float horizontal) { return horizontal * mOverlay.mWidthScaleFactor; } /** * Adjusts a vertical value of the supplied value from the preview scale to the view scale. */ public float scaleY(float vertical) { return vertical * mOverlay.mHeightScaleFactor; } /** * Adjusts the x coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateX(float x) { if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) { return mOverlay.getWidth() - scaleX(x); } else { return scaleX(x); } } /** * Adjusts the y coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateY(float y) { return scaleY(y); } public void postInvalidate() { mOverlay.postInvalidate(); } } public GraphicOverlay(Context context, AttributeSet attrs) { super(context, attrs); } /** * Removes all graphics from the overlay. */ public void clear() { synchronized (mLock) { mGraphics.clear(); } postInvalidate(); } /** * Adds a graphic to the overlay. */ public void add(Graphic graphic) { synchronized (mLock) { mGraphics.add(graphic); } postInvalidate(); } /** * Removes a graphic from the overlay. */ public void remove(Graphic graphic) { synchronized (mLock) { mGraphics.remove(graphic); } postInvalidate(); } /** * Sets the camera attributes for size and facing direction, which informs how to transform * image coordinates later. */ public void setCameraInfo(int previewWidth, int previewHeight, int facing) { synchronized (mLock) { mPreviewWidth = previewWidth; mPreviewHeight = previewHeight; mFacing = facing; } postInvalidate(); } /** * Draws the overlay with its associated graphic objects. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); synchronized (mLock) { if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) { mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth; mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight; } for (Graphic graphic : mGraphics) { graphic.draw(canvas); } } } } ================================================ FILE: Android/FaceTracker/app/src/main/res/layout/activity_select_purpose.xml ================================================ ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/CLFaceDetectionImagePicker.storyboard ================================================ ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/CLFaceDetectionImagePickerViewController.h ================================================ // // CLFaceDetectionViewController.h // // Created by caesar on 26/02/14. // #import typedef NS_ENUM(NSInteger, CLCaptureDevicePosition) { CLCaptureDevicePositionBack = 1, CLCaptureDevicePositionFront = 2 } NS_AVAILABLE(10_7, 4_0); // Keys for customize the pickerView behavior extern NSString *const CLTotalDetectCountDownSecond; //Total length of waiting period for face detection - Default: 10 extern NSString *const CLFaceDetectionSquareImageName; //Image name for the face detection square image - Default: CameraSquare extern NSString *const CLFaceDetectionTimes; //Continually detecting face times, this will be helpful to make sure the people are not shaking his head by purpose in order to give u a not-clear image - Default: 5 extern NSString *const CLCameraPosition; //Choose which camera you want to use, CLCaptureDevicePositionBack or CLCaptureDevicePositionFront -Default: CLCaptureDevicePositionFront @protocol CLFaceDetectionImagePickerDelegate -(void)CLFaceDetectionImagePickerDidDismiss: (NSData *)data blnSuccess:(BOOL)blnSuccess; @optional -(NSDictionary *)faceDetectionBehaviorAttributes; //Optional Function, Set the FaceDetectionPlugin behavior attributes by using above keys @end @interface CLFaceDetectionImagePickerViewController : UIViewController @property (nonatomic, weak) id delegate; @end ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/CLFaceDetectionImagePickerViewController.m ================================================ // // CLFaceDetectionImagePickerViewController.m // DeputyKiosk // // Created by caesar on 26/02/14. // Copyright (c) 2014 Caesar. All rights reserved. // #import "CLFaceDetectionImagePickerViewController.h" #import #import #import #import #import #import #import "UIImage+CL.h" #define TOTAL_TIMES_COUNT_DOWN 4 //This is initial waiting time when the imagePicker is firstly opened. //Attribute Keys NSString *const CLTotalDetectCountDownSecond = @"CLTotalDetectCountDownSecond"; NSString *const CLFaceDetectionSquareImageName = @"CLFaceDetectionSquareImageName"; NSString *const CLFaceDetectionTimes = @"CLFaceDetectionTimes"; NSString *const CLCameraPosition = @"CLCameraPosition"; //Default Values static NSInteger const CLTotalDetectCountDownSecondDefault = 10; static NSInteger const CLFaceDetectionTimesDefault = 5; static NSString* const CLFaceDetectionSquareImageNameDefault = @"CameraSquare"; static NSInteger const CLCameraPositionDefault = AVCaptureDevicePositionFront; @interface CLFaceDetectionImagePickerViewController () @property (nonatomic) NSInteger totalCountDownWaitingSecond; @property (nonatomic) NSInteger totalFaceDetectionTimes; @property (nonatomic) NSInteger cameraPosition; @property (nonatomic, strong) NSString *faceDetectionSquareImageName; @property (weak, nonatomic) IBOutlet UIView *preView; @property (nonatomic, strong) AVCaptureSession *session; @property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput; @property (nonatomic, strong) AVCaptureVideoDataOutput *videoDataOutput; @property (nonatomic) dispatch_queue_t videoDataOutputQueue; @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @property (nonatomic, strong) CIDetector *faceDetector; @property (nonatomic, strong) UIImage *square; @property (nonatomic) double timesDetectFace; @property (nonatomic) double timesCountDown; @property (nonatomic, strong) NSTimer *timerNoFaceDetect; @property (nonatomic, strong) NSNumber *blnDisableAutoFaceDetection; - (void)setupAVCapture; - (void)teardownAVCapture; - (void)drawFaceBoxesForFeatures:(NSArray *)features forVideoBox:(CGRect)videoBox orientation:(UIDeviceOrientation)orientation; @end @implementation CLFaceDetectionImagePickerViewController - (id) init { return [[UIStoryboard storyboardWithName:@"CLFaceDetectionImagePicker" bundle:nil] instantiateViewControllerWithIdentifier:@"CLFaceDetectionImagePickerViewController"]; } -(void)setDelegate:(id)delegate { _delegate = delegate; [self applyCustomDefaults]; } -(void)applyCustomDefaults { NSDictionary *attributes; if ([self.delegate respondsToSelector:@selector(faceDetectionBehaviorAttributes)]) { attributes = [self.delegate faceDetectionBehaviorAttributes]; } self.totalCountDownWaitingSecond = attributes[CLTotalDetectCountDownSecond] ? [attributes[CLTotalDetectCountDownSecond] integerValue] : CLTotalDetectCountDownSecondDefault; self.square = [UIImage imageNamed: attributes[CLFaceDetectionSquareImageName] ? attributes[CLFaceDetectionSquareImageName] : CLFaceDetectionSquareImageNameDefault]; self.cameraPosition = attributes[CLCameraPosition] ? [attributes[CLCameraPosition] integerValue ]: CLCameraPositionDefault; self.totalFaceDetectionTimes = attributes[CLFaceDetectionTimes] ? [attributes[CLFaceDetectionTimes] integerValue] : CLFaceDetectionTimesDefault; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [self setupAVCapture]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self teardownAVCapture]; self.faceDetector = nil; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(UIImage *)square { if(!_square){ _square = [UIImage imageNamed:CLFaceDetectionSquareImageNameDefault]; } return _square; } -(CIDetector *)faceDetector { if(!_faceDetector){ NSDictionary *detectorOptions = [[NSDictionary alloc] initWithObjectsAndKeys:CIDetectorAccuracyLow, CIDetectorAccuracy, nil]; _faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:detectorOptions]; } return _faceDetector; } - (void)setupAVCapture { self.timesDetectFace = 0; self.timesCountDown = TOTAL_TIMES_COUNT_DOWN; NSError *error = nil; self.session = [[AVCaptureSession alloc] init]; [self.session setSessionPreset:AVCaptureSessionPreset640x480]; //Do not set too high, otherwise face detection will be slow. // Select a video device, make an input AVCaptureDevice *device; AVCaptureDevicePosition desiredPosition = self.cameraPosition; // find the front facing camera for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([d position] == desiredPosition) { device = d; break; } } // fall back to the default camera. if( nil == device ) { error = [NSError errorWithDomain:NSOSStatusErrorDomain code:404 userInfo:@{@"message": @"No camera found."}]; } // get the input device AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if( !error ) { // add the input to the session if ( [self.session canAddInput:deviceInput] ){ [self.session addInput:deviceInput]; } // Make a still image output self.stillImageOutput = [AVCaptureStillImageOutput new]; // [stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:AVCaptureStillImageIsCapturingStillImageContext]; if ( [self.session canAddOutput:self.stillImageOutput] ) [self.session addOutput:self.stillImageOutput]; // Make a video data output self.videoDataOutput = [[AVCaptureVideoDataOutput alloc] init]; // we want BGRA, both CoreGraphics and OpenGL work well with 'BGRA' NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; [self.videoDataOutput setVideoSettings:rgbOutputSettings]; [self.videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; // discard if the data output queue is blocked // create a serial dispatch queue used for the sample buffer delegate // a serial dispatch queue must be used to guarantee that video frames will be delivered in order // see the header doc for setSampleBufferDelegate:queue: for more information self.videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL); [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataOutputQueue]; if ( [self.session canAddOutput:self.videoDataOutput] ){ [self.session addOutput:self.videoDataOutput]; } // get the output for doing face detection. [[self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:YES]; self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session]; self.previewLayer.backgroundColor = [[UIColor blackColor] CGColor]; self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect; if([self adjustOutputOrientation] == NO){ __weak typeof(self) weakSelf = self; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self dismissViewControllerAnimated:YES completion:^{ [self throwError:@"It seems your camera orientation is not set properly. Please make sure your iPad is in landscape position and try again." title:nil]; [weakSelf.delegate CLFaceDetectionImagePickerDidDismiss: nil blnSuccess:NO]; }]; }); return; } CALayer *rootLayer = [self.preView layer]; [rootLayer setMasksToBounds:YES]; [self.previewLayer setFrame:[rootLayer bounds]]; [rootLayer addSublayer:self.previewLayer]; [self.session startRunning]; self.timerNoFaceDetect = [NSTimer scheduledTimerWithTimeInterval:self.totalCountDownWaitingSecond target:self selector:@selector(noFaceDetected) userInfo:nil repeats:NO]; } if (error) { [self throwError:[error localizedDescription] title:[NSString stringWithFormat:@"Please make sure your front camera is allowed to be accessed. \nYou can check it in Settings. \nFailed with errorCode %d", (int)[error code]]]; [self teardownAVCapture]; } } // clean up capture setup - (void)teardownAVCapture { for(AVCaptureInput *input in self.session.inputs){ [self.session removeInput:input]; } for(AVCaptureOutput *output in self.session.outputs){ [self.session removeOutput:output]; } [self.session stopRunning]; self.videoDataOutput = nil; self.videoDataOutputQueue = nil; [self.previewLayer removeFromSuperlayer]; self.previewLayer = nil; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { // get the image CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CFDictionaryRef attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, sampleBuffer, kCMAttachmentMode_ShouldPropagate); CIImage *ciImage = [[CIImage alloc] initWithCVPixelBuffer:pixelBuffer options:(__bridge NSDictionary *)attachments]; if (attachments) { CFRelease(attachments); } // make sure your device orientation is not locked. UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation]; if(!self.blnDisableAutoFaceDetection.intValue){ NSDictionary *imageOptions = nil; imageOptions = [NSDictionary dictionaryWithObject:[self exifOrientation:curDeviceOrientation] forKey:CIDetectorImageOrientation]; NSArray *features = [self.faceDetector featuresInImage:ciImage options:imageOptions]; if(!features.count){ self.timesDetectFace = 0; return; } if(self.timesDetectFace > self.totalFaceDetectionTimes){ return; } self.timesDetectFace++; // get the clean aperture // the clean aperture is a rectangle that defines the portion of the encoded pixel dimensions // that represents image data valid for display. CMFormatDescriptionRef fdesc = CMSampleBufferGetFormatDescription(sampleBuffer); CGRect clap = CMVideoFormatDescriptionGetCleanAperture(fdesc, false /*originIsTopLeft == false*/); dispatch_async(dispatch_get_main_queue(), ^(void) { [self drawFaceBoxesForFeatures:features forVideoBox:clap orientation:curDeviceOrientation]; }); }else{ if(self.timesCountDown < 0) return; self.timesCountDown -= 0.03; CMFormatDescriptionRef fdesc = CMSampleBufferGetFormatDescription(sampleBuffer); CGRect clap = CMVideoFormatDescriptionGetCleanAperture(fdesc, false /*originIsTopLeft == false*/); dispatch_async(dispatch_get_main_queue(), ^(void) { [self drawCountDownforVideoBox:clap orientation:curDeviceOrientation]; }); } if(self.timesDetectFace >= self.totalFaceDetectionTimes || self.timesCountDown <= 0){ [self.timerNoFaceDetect invalidate]; CIContext *temporaryContext = [CIContext contextWithOptions:nil]; CGImageRef videoImage = [temporaryContext createCGImage:ciImage fromRect:CGRectMake(0, 0, CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer))]; UIImage *picture = [[UIImage imageWithCGImage:videoImage] imageRotatedWithDeviceOrientation:YES]; NSData *compressedData = UIImageJPEGRepresentation(picture, 1.0); [self doCloseCaptureAndDelegateClientWithData:compressedData]; } } // utility routing used during image capture to set up capture orientation - (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation { AVCaptureVideoOrientation result = AVCaptureVideoOrientationLandscapeLeft; if ( deviceOrientation == UIDeviceOrientationLandscapeLeft ) result = AVCaptureVideoOrientationLandscapeRight; else if ( deviceOrientation == UIDeviceOrientationLandscapeRight ) result = AVCaptureVideoOrientationLandscapeLeft; return result; } -(BOOL)shouldAutorotate { return [self adjustOutputOrientation]; } -(BOOL)adjustOutputOrientation { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if(orientation != UIDeviceOrientationLandscapeLeft && orientation != UIDeviceOrientationLandscapeRight){ return NO; } [self.previewLayer.connection setVideoOrientation:[self avOrientationForDeviceOrientation:orientation]]; return YES; } - (NSNumber *) exifOrientation: (UIDeviceOrientation) orientation { int exifOrientation; /* kCGImagePropertyOrientation values The intended display orientation of the image. If present, this key is a CFNumber value with the same value as defined by the TIFF and EXIF specifications -- see enumeration of integer constants. The value specified where the origin (0,0) of the image is located. If not present, a value of 1 is assumed. used when calling featuresInImage: options: The value for this key is an integer NSNumber from 1..8 as found in kCGImagePropertyOrientation. If present, the detection will be done based on that orientation but the coordinates in the returned features will still be based on those of the image. */ enum { PHOTOS_EXIF_0ROW_TOP_0COL_LEFT = 1, // 1 = 0th row is at the top, and 0th column is on the left (THE DEFAULT). PHOTOS_EXIF_0ROW_TOP_0COL_RIGHT = 2, // 2 = 0th row is at the top, and 0th column is on the right. PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT = 3, // 3 = 0th row is at the bottom, and 0th column is on the right. PHOTOS_EXIF_0ROW_BOTTOM_0COL_LEFT = 4, // 4 = 0th row is at the bottom, and 0th column is on the left. PHOTOS_EXIF_0ROW_LEFT_0COL_TOP = 5, // 5 = 0th row is on the left, and 0th column is the top. PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP = 6, // 6 = 0th row is on the right, and 0th column is the top. PHOTOS_EXIF_0ROW_RIGHT_0COL_BOTTOM = 7, // 7 = 0th row is on the right, and 0th column is the bottom. PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM = 8 // 8 = 0th row is on the left, and 0th column is the bottom. }; switch (orientation) { case UIDeviceOrientationPortraitUpsideDown: // Device oriented vertically, home button on the top exifOrientation = PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM; break; case UIDeviceOrientationLandscapeLeft: // Device oriented horizontally, home button on the right // if (self.isUsingFrontFacingCamera) exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT; // else // exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT; break; case UIDeviceOrientationLandscapeRight: // Device oriented horizontally, home button on the left // if (self.isUsingFrontFacingCamera) exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT; // else // exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT; break; case UIDeviceOrientationPortrait: // Device oriented vertically, home button on the bottom default: exifOrientation = PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP; break; } return [NSNumber numberWithInt:exifOrientation]; } -(void)doCloseCaptureAndDelegateClientWithData: (NSData *)data { __weak typeof(self) weakSelf = self; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self dismissViewControllerAnimated:YES completion:^{ if(!data){ [self throwError:@"Sorry, we cannot detect your face." title:nil]; } [weakSelf.delegate CLFaceDetectionImagePickerDidDismiss: data blnSuccess:(data)?YES:NO]; }]; }); } -(void)noFaceDetected { [self doCloseCaptureAndDelegateClientWithData:nil]; } // find where the video box is positioned within the preview layer based on the video size and gravity + (CGRect)videoPreviewBoxForGravity:(NSString *)gravity frameSize:(CGSize)frameSize apertureSize:(CGSize)apertureSize { CGFloat apertureRatio = apertureSize.height / apertureSize.width; CGFloat viewRatio = frameSize.width / frameSize.height; CGSize size = CGSizeZero; if ([gravity isEqualToString:AVLayerVideoGravityResizeAspectFill]) { if (viewRatio > apertureRatio) { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } else { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } } else if ([gravity isEqualToString:AVLayerVideoGravityResizeAspect]) { if (viewRatio > apertureRatio) { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } else { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } } else if ([gravity isEqualToString:AVLayerVideoGravityResize]) { size.width = frameSize.width; size.height = frameSize.height; } CGRect videoBox; videoBox.size = size; if (size.width < frameSize.width) videoBox.origin.x = (frameSize.width - size.width) / 2; else videoBox.origin.x = (size.width - frameSize.width) / 2; if ( size.height < frameSize.height ) videoBox.origin.y = (frameSize.height - size.height) / 2; else videoBox.origin.y = (size.height - frameSize.height) / 2; return videoBox; } -(void)drawCountDownforVideoBox:(CGRect)clap orientation:(UIDeviceOrientation)orientation { NSArray *sublayers = [NSArray arrayWithArray:[self.previewLayer sublayers]]; NSInteger sublayersCount = [sublayers count], currentSublayer = 0; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; // hide all the CountDownLayer layers for ( CATextLayer *layer in sublayers ) { if ( [[layer name] isEqualToString:@"CountDownLayer"] ) [layer setHidden:YES]; } CGSize parentFrameSize = [self.preView frame].size; CATextLayer *featureLayer = nil; // re-use an existing layer if possible while ( !featureLayer && (currentSublayer < sublayersCount) ) { CATextLayer *currentLayer = [sublayers objectAtIndex:currentSublayer++]; if ( [[currentLayer name] isEqualToString:@"CountDownLayer"] ) { featureLayer = currentLayer; [currentLayer setHidden:NO]; } } // create a new one if necessary if ( !featureLayer ) { featureLayer = [CATextLayer new]; // [featureLayer setContents:(id)[self.square CGImage]]; [featureLayer setFont:@"Helvetica-Bold"]; [featureLayer setFontSize:90]; [featureLayer setAlignmentMode:kCAAlignmentCenter]; [featureLayer setForegroundColor:[[UIColor whiteColor] CGColor]]; [featureLayer setName:@"CountDownLayer"]; [self.previewLayer addSublayer:featureLayer]; } int countDown = @(self.timesCountDown).intValue; NSString *strCountDown = (countDown > 0)?[NSString stringWithFormat:@"%d", countDown]:@"Smile"; [featureLayer setString: strCountDown]; [featureLayer setFrame:CGRectMake( (parentFrameSize.width-300)/2, (parentFrameSize.height-300)/2, 300, 300)]; [CATransaction commit]; } // called asynchronously as the capture output is capturing sample buffers, this method asks the face detector (if on) // to detect features and for each draw the red square in a layer and set appropriate orientation - (void)drawFaceBoxesForFeatures:(NSArray *)features forVideoBox:(CGRect)clap orientation:(UIDeviceOrientation)orientation { NSArray *sublayers = [NSArray arrayWithArray:[self.previewLayer sublayers]]; NSInteger sublayersCount = [sublayers count], currentSublayer = 0; NSInteger featuresCount = [features count], currentFeature = 0; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; // hide all the face layers for ( CALayer *layer in sublayers ) { if ( [[layer name] isEqualToString:@"FaceLayer"] ) [layer setHidden:YES]; } if ( featuresCount == 0) { [CATransaction commit]; return; // early bail. } CGSize parentFrameSize = [self.preView frame].size; NSString *gravity = [self.previewLayer videoGravity]; CGRect previewBox = [CLFaceDetectionImagePickerViewController videoPreviewBoxForGravity:gravity frameSize:parentFrameSize apertureSize:clap.size]; for ( CIFaceFeature *ff in features ) { CGRect faceRect = [ff bounds]; // scale coordinates so they fit in the preview box, which may be scaled CGFloat widthScaleBy = previewBox.size.width / clap.size.width; CGFloat heightScaleBy = previewBox.size.height / clap.size.height; faceRect.origin.x *= widthScaleBy; faceRect.origin.y *= heightScaleBy; faceRect = CGRectOffset(faceRect, previewBox.origin.x, previewBox.origin.y); CALayer *featureLayer = nil; // re-use an existing layer if possible while ( !featureLayer && (currentSublayer < sublayersCount) ) { CALayer *currentLayer = [sublayers objectAtIndex:currentSublayer++]; if ( [[currentLayer name] isEqualToString:@"FaceLayer"] ) { featureLayer = currentLayer; [currentLayer setHidden:NO]; } } // create a new one if necessary if ( !featureLayer ) { featureLayer = [CALayer new]; [featureLayer setContents:(id)[self.square CGImage]]; [featureLayer setName:@"FaceLayer"]; [self.previewLayer addSublayer:featureLayer]; } [featureLayer setFrame:faceRect]; currentFeature++; } [CATransaction commit]; } //Throw Error -(void) throwError:(NSString *)error title:(NSString *)title { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: title message:error delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; [alertView show]; } @end ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/EZShopManager-Bridging-Header.h ================================================ #import "CLFaceDetectionImagePickerViewController.h" ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/EnrollViewController.swift ================================================ // // EnrollViewController.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-17. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import SwiftyJSON import FirebaseDatabase import FirebaseStorage struct KairosConfig { static let app_id = "4724eb0e" static let app_key = "f5795e224117ac3393343c6bc14c841b" } class EnrollViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLFaceDetectionImagePickerDelegate { @IBOutlet weak var userNameLabel: UITextField! var uuid = "" var images: [UIImage] = [] @IBAction func takePhoto() { if userNameLabel.text == "" { JGUtils.alert(title: "ERROR", message: "Enter user name") } uuid = UUID().uuidString userNameLabel.resignFirstResponder() JGUtils.alert(title: "Instruction", message: "Hold ipad on your eye level. It will take 3 photos. Press OK to start") { let imagePicker = CLFaceDetectionImagePickerViewController() imagePicker.delegate = self self.present(imagePicker, animated: true) let view = UIView(frame: self.view.frame) view.backgroundColor = UIColor.white let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: view.frame.width, height: 100))) label.text = self.messages[self.images.count] label.font = UIFont.systemFont(ofSize: 50) label.sizeToFit() view.addSubview(label) label.center = view.center self.view.addSubview(view) self.tempMessageContainer = view } // imagePicker.view.tintColor = view.tintColor // imagePicker.sourceType = .camera // imagePicker.delegate = self // imagePicker.cameraDevice = .front // // imagePicker.allowsEditing = true // present(imagePicker, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerEditedImage] as? UIImage { uuid = UUID().uuidString // Instantiate KairosAPI class let Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key) let imageData = UIImageJPEGRepresentation(image, 0) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop", "subject_id": uuid ] // Example - Enroll ActivityIndicator.shared.show(self.view) Kairos.request(method: "enroll", data: jsonBody) { data in let json = JSON(data) // print(json) DispatchQueue.main.sync { JGUtils.alert(title: "SUCCESS", message: "User is enrolled") self.enrollUser(image: image) ActivityIndicator.shared.hide() } } self.dismiss(animated: true, completion: nil) } } func enrollUser(image: UIImage) { uploadImage(image: image) } var photoURL = "" func uploadImage(image: UIImage) { let storage = FIRStorage.storage() // Create a root reference let storageRef = storage.reference() // Data in memory let data = UIImageJPEGRepresentation(image, 0.5) // Create a reference to the file you want to upload let riversRef = storageRef.child("images/" + uuid + ".jpg") // Upload the file to the path "images/rivers.jpg" let uploadTask = riversRef.put(data!, metadata: nil) { (metadata, error) in guard let metadata = metadata else { // Uh-oh, an error occurred! return } // Metadata contains file metadata such as size, content-type, and download URL. self.photoURL = metadata.downloadURLs!.first!.absoluteString let ref = FIRDatabase.database().reference() ref.child("users").child(self.uuid).setValue( ["name": self.userNameLabel.text!, "user_id": self.uuid, "is_in_store": false, "photo": self.photoURL]) self.userNameLabel.text = "" } } var tempMessageContainer:UIView = UIView() let messages = ["Taking photo 1/3","☺️Smile :D", "Last one!"] func clFaceDetectionImagePickerDidDismiss(_ data: Data!, blnSuccess: Bool) { tempMessageContainer.removeFromSuperview() if data != nil { if let image = UIImage(data: data) { if images.count < 2 { images.append(image) let view = UIView(frame: self.view.frame) view.backgroundColor = UIColor.white let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: view.frame.width, height: 100))) label.text = messages[images.count] label.font = UIFont.systemFont(ofSize: 50) label.sizeToFit() label.textAlignment = .left view.addSubview(label) label.center = view.center self.view.addSubview(view) tempMessageContainer = view let imagePicker = CLFaceDetectionImagePickerViewController() imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } else { images.append(image) // Instantiate KairosAPI class let Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key) // Example - Enroll ActivityIndicator.shared.show(self.view) let imageData = UIImageJPEGRepresentation(self.images[0], 1) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop", "subject_id": self.uuid ] Kairos.request(method: "enroll", data: jsonBody) { data in print("Photo 1") let json = JSON(data) print(json) let imageData = UIImageJPEGRepresentation(self.images[1], 1) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop", "subject_id": self.uuid ] Kairos.request(method: "enroll", data: jsonBody) { data in let json = JSON(data) print("Photo 2") print(json) let imageData = UIImageJPEGRepresentation(self.images[2], 1) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop", "subject_id": self.uuid ] Kairos.request(method: "enroll", data: jsonBody) { data in let json = JSON(data) print("Photo 3") print(json) DispatchQueue.main.sync { JGUtils.alert(title: "SUCCESS", message: "User is enrolled") self.enrollUser(image: self.images[2]) self.images.removeAll() ActivityIndicator.shared.hide() self.tabBarController?.selectedIndex = 1 } } } } } } } } @IBAction func gotostore() { self.tabBarController?.selectedIndex = 1 } override func viewDidLoad() { super.viewDidLoad() userNameLabel.becomeFirstResponder() // Do any additional setup after loading the view. } } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/GoogleService-Info.plist ================================================ AD_UNIT_ID_FOR_BANNER_TEST ca-app-pub-3940256099942544/2934735716 AD_UNIT_ID_FOR_INTERSTITIAL_TEST ca-app-pub-3940256099942544/4411468910 CLIENT_ID 89251823040-roa262gcilvr905ug5558vdq0p0n4umv.apps.googleusercontent.com REVERSED_CLIENT_ID com.googleusercontent.apps.89251823040-roa262gcilvr905ug5558vdq0p0n4umv API_KEY AIzaSyBobTBUxfcSLf7pX1N9c0z3qlqtK3tpjSE GCM_SENDER_ID 89251823040 PLIST_VERSION 1 BUNDLE_ID ca.jgchoi.EZShopManager PROJECT_ID hackvalley-5be01 STORAGE_BUCKET hackvalley-5be01.appspot.com IS_ADS_ENABLED IS_ANALYTICS_ENABLED IS_APPINVITE_ENABLED IS_GCM_ENABLED IS_SIGNIN_ENABLED GOOGLE_APP_ID 1:89251823040:ios:656a0064b1cd1b42 DATABASE_URL https://hackvalley-5be01.firebaseio.com ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/Info.plist ================================================ NSAppTransportSecurity NSAllowsArbitraryLoads CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleVersion 1 LSRequiresIPhoneOS NSCameraUsageDescription Take photo for enroll user UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations~ipad UIInterfaceOrientationLandscapeRight UIInterfaceOrientationLandscapeLeft ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/InventoriesViewController.swift ================================================ // // InventoriesViewController.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import SwiftyJSON import FirebaseDatabase import Kingfisher class InventoriesViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { var ref: FIRDatabaseReference! var items:[Item] = [] override func viewDidLoad() { super.viewDidLoad() ref = FIRDatabase.database().reference() let refHandle = ref.observe(FIRDataEventType.value, with: { (snapshot) in let db = JSON(snapshot.value) //print(db["users"]) if let _items = db["inventories"].array { self.items.removeAll() _items.forEach({ ( _itemJSON) in let new = Item() new.item_price = _itemJSON["item_price"].doubleValue new.item_id = _itemJSON["item_price"].intValue new.item_count = _itemJSON["item_count"].intValue new.item_name = _itemJSON["item_name"].stringValue new.item_description = _itemJSON["item_description"].stringValue new.item_image = _itemJSON["item_image"].stringValue self.items.append(new) }) self.items.remove(at: 0) self.collectionView.reloadData() } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var collectionView: UICollectionView! /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) cell.layer.cornerRadius = 5 cell.layer.borderWidth = 1 let item = items[indexPath.row] if let imageView = cell.viewWithTag(100) as? UIImageView { imageView.kf.setImage(with: URL(string: item.item_image)) } if let label = cell.viewWithTag(101) as? UILabel { label.text = item.item_name } if let label = cell.viewWithTag(102) as? UILabel { label.text = "$ \(item.item_price)" } if let label = cell.viewWithTag(104) as? UILabel { label.text = "\(item.item_count)" } if item.item_count == 0 { cell.backgroundColor = UIColor.red } else { cell.backgroundColor = UIColor.clear } return cell } } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/Item.swift ================================================ // // Item.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import Foundation class Item { var item_name = "" var item_id = 0 var item_price = 0.0 var item_description = "" var item_image = "" var item_count = 0 } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/JGUtils.swift ================================================ // // JGUtils.swift // emii // // Created by Jung Geon Choi on 2017-03-04. // Copyright © 2017 Emanant Inc. All rights reserved. // import Foundation import SwiftyJSON import UIKit class JGUtils { // MARK: - Variables static var vc: UIViewController { get { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } print("Failed to find first view controller @ JGUtils.getFrontViewController()") return UIViewController() } } // MARK: - Alert ONLY static func alert(title: String, message: String?, buttonMessage: String = "OK") { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: buttonMessage, style: .cancel, handler: nil)) vc.present(alert, animated: true, completion: nil) } static func alert(title: String, message: String?, buttonMessage: String = "OK", closure:@escaping (() -> ())) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: buttonMessage, style: .cancel, handler: { (_) in closure() })) vc.present(alert, animated: true, completion: nil) } // MARK: - Selection Alert } // MARK: - View Extension extension UIView { var animationDuration: TimeInterval { get { return 0.5 } } func hide() { self.alpha = 1.0 UIView.animate(withDuration: animationDuration) { self.alpha = 0.0 } } func show() { self.alpha = 0.0 UIView.animate(withDuration: animationDuration) { self.alpha = 1.0 } } } extension JSON { func hasError() -> Bool { let error = self["error"]["message"].stringValue return !error.isEmpty } var errorMessage: String { get { return self["error"]["message"].stringValue } } } // MARK: - Statusbard Indicator extension JGUtils { static func setNetworkIndicator(_ status: Bool) { UIApplication.shared.isNetworkActivityIndicatorVisible = status } } extension UIColor { static public var tint: UIColor { return UIColor( red: CGFloat(73.0/255.0), green: CGFloat(188.0/255.0), blue: CGFloat(167.0/255.0), alpha: CGFloat(1.0) ) } } // MARK: - String extension String { var formattedPhoneNumber: String { return "(" + self[0..<3] + ") " + self[3..<6] + "-" + self[6..<10] } var length: Int { return self.characters.count } subscript (i: Int) -> String { return self[Range(i ..< i + 1)] } func substring(from: Int) -> String { return self[Range(min(from, length) ..< length)] } func substring(to: Int) -> String { return self[Range(0 ..< max(0, to))] } subscript (r: Range) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return self[Range(start ..< end)] } } // MARK: - Notification extension Notification.Name { static let tokenReceivedFromWeb = Notification.Name("ReceivedTokenFromWeb") } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/MySplitViewController.swift ================================================ // // MySplitViewController.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit class MySplitViewController: UISplitViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let nv = viewControllers[0] as? UINavigationController { if let vc1 = nv.viewControllers[0] as? UsersTableViewController { if let vc2 = viewControllers[1] as? UserDetailsViewController { vc1.delegate = vc2 } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/UIImage+CL.h ================================================ // // UIImage+CL.h // CLFaceDetectionImagePicker // // Created by Caesar on 10/12/2014. // Copyright (c) 2014 Caesar. All rights reserved. // #import @interface UIImage (CL) - (UIImage *)imageRotatedWithDeviceOrientation: (BOOL)isFrontFacing; @end ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/UIImage+CL.m ================================================ // // UIImage+CL.m // CLFaceDetectionImagePicker // // Created by Caesar on 10/12/2014. // Copyright (c) 2014 Caesar. All rights reserved. // #import "UIImage+CL.h" @implementation UIImage (CL) static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;}; - (UIImage *)imageRotatedWithDeviceOrientation: (BOOL)isFrontFacing { CGFloat degrees = 0.; UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; switch (orientation) { case UIDeviceOrientationPortrait: degrees = -90.; break; case UIDeviceOrientationPortraitUpsideDown: degrees = 90.; break; case UIDeviceOrientationLandscapeLeft: if (isFrontFacing) degrees = 180.; else degrees = 0.; break; case UIDeviceOrientationLandscapeRight: if (isFrontFacing) degrees = 0.; else degrees = 180.; break; case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: default: break; // leave the layer in its last known orientation } // calculate the size of the rotated view's containing box for our drawing space UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)]; CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees)); rotatedViewBox.transform = t; CGSize rotatedSize = rotatedViewBox.frame.size; // Create the bitmap context UIGraphicsBeginImageContext(rotatedSize); CGContextRef bitmap = UIGraphicsGetCurrentContext(); // Move the origin to the middle of the image so we will rotate and scale around the center. CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2); // // Rotate the image context CGContextRotateCTM(bitmap, DegreesToRadians(degrees)); // Now, draw the rotated/scaled image into the context CGContextScaleCTM(bitmap, 1.0, -1.0); CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } @end ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/User.swift ================================================ import UIKit class User { var name = "" var photo = "" var user_id = "" var isInStore = false var items: [Item] = [] } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/UserDetailsViewController.swift ================================================ // // UserDetailsViewController.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit extension UserDetailsViewController: UserTableDelgate { func didSelectUser(user: User) { self.user = user reloadPage() } } class UserDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var user: User = User() @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var userStatusLabel: UILabel! @IBOutlet weak var userStatusCircle: UIView! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() userStatusCircle.clipsToBounds = true userStatusCircle.layer.cornerRadius = userStatusCircle.frame.width / 2 userImageView.clipsToBounds = true userImageView.layer.cornerRadius = userImageView.frame.width / 2 // Do any additional setup after loading the view. } func reloadPage() { userNameLabel.text = user.name userImageView.kf.setImage(with: URL(string: user.photo)) userStatusLabel.text = user.isInStore ? "In Store" : "Not In Store" userStatusCircle.backgroundColor = user.isInStore ? UIColor.green : UIColor.red tableView.reloadData() cartCover.removeFromSuperview() if user.items.count == 0 { cartCover = UIView(frame: tableView.frame) cartCover.backgroundColor = UIColor.white let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: tableView.frame.width, height: 50))) label.text = "Cart is Empty" label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 50) // label.center = cartCover.center cartCover.addSubview(label) view.addSubview(cartCover) } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } var cartCover = UIView() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return user.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) let item = user.items[indexPath.row] cell.textLabel?.text = item.item_name cell.detailTextLabel?.text = "$ \(item.item_price)" return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/UsersTableViewController.swift ================================================ // // UsersTableViewController.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import SwiftyJSON import FirebaseDatabase import Kingfisher protocol UserTableDelgate { func didSelectUser(user: User) } class UsersTableViewController: UITableViewController { var delegate: UserTableDelgate? var ref: FIRDatabaseReference! var showInStore = true @IBAction func segView(_ sender: UISegmentedControl) { showInStore = sender.selectedSegmentIndex == 0 tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() ref = FIRDatabase.database().reference() let refHandle = ref.observe(FIRDataEventType.value, with: { (snapshot) in let db = JSON(snapshot.value) //print(db["users"]) if let _users = db["users"].dictionary { self.users.removeAll() _users.forEach({ (_, _userJSON) in let new = User() print(_userJSON["user_id"].stringValue) new.name = _userJSON["name"].stringValue new.photo = _userJSON["photo"].stringValue new.user_id = _userJSON["user_id"].stringValue new.isInStore = _userJSON["is_in_store"].boolValue if let store = db["store"].dictionary { if let _items = store[new.user_id]?["cart"].arrayObject as? [Int] { _items.forEach({ (_item_id) in if _item_id > 0 { let newItem = Item() newItem.item_id = _item_id let _itemDetails = db["inventories"][_item_id].dictionaryValue newItem.item_name = _itemDetails["item_name"]!.stringValue newItem.item_price = _itemDetails["item_price"]!.doubleValue new.items.append(newItem) } }) } } print(new.items) self.users.append(new) }) self.tableView.reloadData() if self.selecteedIndex != nil { if (self.selecteedIndex?.row)! < self.dataSource().count { self.delegate?.didSelectUser(user: self.dataSource()[(self.selecteedIndex?.row)!]) } } } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var selecteedIndex:IndexPath? override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.didSelectUser(user: dataSource()[indexPath.row]) if selecteedIndex != nil { tableView.cellForRow(at: selecteedIndex!)?.accessoryType = .none } selecteedIndex = indexPath tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark tableView.deselectRow(at: indexPath, animated: true) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource().count } var users: [User] = [] func dataSource() -> [User] { return users.filter({ (user) -> Bool in if showInStore { return user.isInStore } return true }) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) let user = dataSource()[indexPath.row] if let imageView = cell.viewWithTag(100) as? UIImageView { imageView.layer.cornerRadius = imageView.frame.width/2 imageView.clipsToBounds = true imageView.kf.setImage(with: URL(string: user.photo)) } if let nameLabel = cell.viewWithTag(101) as? UILabel { nameLabel.text = user.name } cell.accessoryType = .none return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager/kairos.swift ================================================ /* * Copyright (c) 2017, Kairos AR, Inc. * All rights reserved. * * Api Docs: https://www.kairos.com/docs/api/ * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ import UIKit public class KairosAPI { let api_url: String = "https://api.kairos.com/" let app_id: String let app_key: String var headers: HTTPURLResponse? public init(app_id: String, app_key: String) { self.app_id = app_id self.app_key = app_key } public func convertImageToBase64String(file: String) -> String { let image = UIImage(named: file) let imageData = UIImageJPEGRepresentation(image!, 0) let base64String = imageData?.base64EncodedString(options:[]) return base64String! } // Kairos API - HTTP Request public func send(url:String, data: Dictionary? = [:], httpType: String, taskCallback: @escaping (Bool, AnyObject, AnyObject?) -> ()) -> Void { let jsonData = try? JSONSerialization.data(withJSONObject: data!) // create post request with headers let urlObject = URL(string: url)! var request = URLRequest(url: urlObject) request.httpMethod = httpType request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(self.app_id, forHTTPHeaderField: "app_id") request.addValue(self.app_key, forHTTPHeaderField: "app_key") // insert json data to the request request.httpBody = jsonData URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil) let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if let data = data { let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: []) let jsonErrors = (jsonResponse as? [String : AnyObject])?["Errors"] self.headers = response as? HTTPURLResponse if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode, jsonErrors == nil { taskCallback(true, jsonResponse as AnyObject!, jsonErrors as AnyObject?) } else { self.getError(errors: jsonErrors as AnyObject?) } } }) task.resume() } public func getError(errors: AnyObject?) -> Void { let errorCode = self.headers!.statusCode let errorMessage = "Could not get response" if errors != nil { } DispatchQueue.main.sync { ActivityIndicator.shared.hide() JGUtils.alert(title: "ERROR", message: errorMessage + "\nERROR CODE(\(errorCode))") } print("Error (\(errorCode)): \(errorMessage)") } public func request(method: String, data: Dictionary? = [:], httpTypeOverride: Any? = nil, callback: @escaping (AnyObject) -> ()) -> Void { let url = (self.api_url + method).replacingOccurrences(of: "\\/{2,}", with: "/", options: .regularExpression, range: nil) var httpType: String = "POST" // default let matchMediaId = "/v2/(media|analytics)/[a-z0-9]+" let range = url.range(of: matchMediaId, options: .regularExpression) if range != nil { httpType = "GET" } if httpTypeOverride != nil { httpType = httpTypeOverride as! String } self.send(url: url, data: data, httpType: httpType) { (ok, data, errors) in // if http error then display it if ok == false { self.getError(errors: errors) return } // else pass the data along callback(data) } } } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 61B71690E061E377BB62FD8B /* Pods_EZShopManager.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 36AE3B50135A121A9DEE7AC9 /* Pods_EZShopManager.framework */; }; D20D45EC1E7CE031001113EC /* JGUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = D20D45EB1E7CE031001113EC /* JGUtils.swift */; }; D20D45EE1E7CE0C8001113EC /* ActivitiyIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D20D45ED1E7CE0C8001113EC /* ActivitiyIndicator.swift */; }; D20D45F01E7CE14D001113EC /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = D20D45EF1E7CE14D001113EC /* GoogleService-Info.plist */; }; D20D46091E7D4475001113EC /* CLFaceDetectionImagePickerViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = D20D46061E7D4475001113EC /* CLFaceDetectionImagePickerViewController.m */; }; D20D460A1E7D4475001113EC /* UIImage+CL.m in Sources */ = {isa = PBXBuildFile; fileRef = D20D46081E7D4475001113EC /* UIImage+CL.m */; }; D20D460C1E7D4980001113EC /* CLFaceDetectionImagePicker.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D20D460B1E7D4980001113EC /* CLFaceDetectionImagePicker.storyboard */; }; D20D460F1E7D4D25001113EC /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D20D460E1E7D4D25001113EC /* Assets.xcassets */; }; D20D46111E7D5F04001113EC /* UsersTableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D20D46101E7D5F04001113EC /* UsersTableViewController.swift */; }; D20D46131E7D6188001113EC /* UserDetailsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D20D46121E7D6188001113EC /* UserDetailsViewController.swift */; }; D21E8BE71E7D63D000316040 /* MySplitViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D21E8BE61E7D63D000316040 /* MySplitViewController.swift */; }; D21E8BE91E7D691F00316040 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = D21E8BE81E7D691F00316040 /* User.swift */; }; D21E8BEB1E7D695300316040 /* Item.swift in Sources */ = {isa = PBXBuildFile; fileRef = D21E8BEA1E7D695300316040 /* Item.swift */; }; D25E55681E7DD4A7000B18D8 /* InventoriesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D25E55671E7DD4A7000B18D8 /* InventoriesViewController.swift */; }; D2A5C26B1E7CD15100CB7A92 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2A5C26A1E7CD15100CB7A92 /* AppDelegate.swift */; }; D2A5C2701E7CD15100CB7A92 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D2A5C26E1E7CD15100CB7A92 /* Main.storyboard */; }; D2A5C2751E7CD15100CB7A92 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D2A5C2731E7CD15100CB7A92 /* LaunchScreen.storyboard */; }; D2A5C27E1E7CD4BA00CB7A92 /* kairos.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2A5C27D1E7CD4BA00CB7A92 /* kairos.swift */; }; D2A5C2881E7CD5E000CB7A92 /* EnrollViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2A5C2871E7CD5E000CB7A92 /* EnrollViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 36AE3B50135A121A9DEE7AC9 /* Pods_EZShopManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_EZShopManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A321DCAF31FEACCFF80B5A25 /* Pods-EZShopManager.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-EZShopManager.debug.xcconfig"; path = "Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager.debug.xcconfig"; sourceTree = ""; }; AD2FC764B32F07AC46A0E19C /* Pods-EZShopManager.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-EZShopManager.release.xcconfig"; path = "Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager.release.xcconfig"; sourceTree = ""; }; D20D45EB1E7CE031001113EC /* JGUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JGUtils.swift; sourceTree = ""; }; D20D45ED1E7CE0C8001113EC /* ActivitiyIndicator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ActivitiyIndicator.swift; sourceTree = ""; }; D20D45EF1E7CE14D001113EC /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; D20D46051E7D4475001113EC /* CLFaceDetectionImagePickerViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CLFaceDetectionImagePickerViewController.h; sourceTree = ""; }; D20D46061E7D4475001113EC /* CLFaceDetectionImagePickerViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CLFaceDetectionImagePickerViewController.m; sourceTree = ""; }; D20D46071E7D4475001113EC /* UIImage+CL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+CL.h"; sourceTree = ""; }; D20D46081E7D4475001113EC /* UIImage+CL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+CL.m"; sourceTree = ""; }; D20D460B1E7D4980001113EC /* CLFaceDetectionImagePicker.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = CLFaceDetectionImagePicker.storyboard; sourceTree = ""; }; D20D460E1E7D4D25001113EC /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; D20D46101E7D5F04001113EC /* UsersTableViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UsersTableViewController.swift; sourceTree = ""; }; D20D46121E7D6188001113EC /* UserDetailsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserDetailsViewController.swift; sourceTree = ""; }; D21E8BE61E7D63D000316040 /* MySplitViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MySplitViewController.swift; sourceTree = ""; }; D21E8BE81E7D691F00316040 /* User.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; D21E8BEA1E7D695300316040 /* Item.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Item.swift; sourceTree = ""; }; D25E55671E7DD4A7000B18D8 /* InventoriesViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InventoriesViewController.swift; sourceTree = ""; }; D2A5C2671E7CD15100CB7A92 /* EZShopManager.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = EZShopManager.app; sourceTree = BUILT_PRODUCTS_DIR; }; D2A5C26A1E7CD15100CB7A92 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; D2A5C26F1E7CD15100CB7A92 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; D2A5C2741E7CD15100CB7A92 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; D2A5C2761E7CD15100CB7A92 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; D2A5C27D1E7CD4BA00CB7A92 /* kairos.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = kairos.swift; sourceTree = ""; }; D2A5C2871E7CD5E000CB7A92 /* EnrollViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnrollViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ D2A5C2641E7CD15000CB7A92 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 61B71690E061E377BB62FD8B /* Pods_EZShopManager.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ A66D37A6A666E7900AA023BC /* Frameworks */ = { isa = PBXGroup; children = ( 36AE3B50135A121A9DEE7AC9 /* Pods_EZShopManager.framework */, ); name = Frameworks; sourceTree = ""; }; D20D45EA1E7CDC09001113EC /* support */ = { isa = PBXGroup; children = ( D20D45EB1E7CE031001113EC /* JGUtils.swift */, D2A5C26A1E7CD15100CB7A92 /* AppDelegate.swift */, D20D45ED1E7CE0C8001113EC /* ActivitiyIndicator.swift */, D20D45EF1E7CE14D001113EC /* GoogleService-Info.plist */, D2A5C2731E7CD15100CB7A92 /* LaunchScreen.storyboard */, D2A5C2761E7CD15100CB7A92 /* Info.plist */, ); name = support; sourceTree = ""; }; D20D460D1E7D4984001113EC /* Facedetecting */ = { isa = PBXGroup; children = ( D20D46051E7D4475001113EC /* CLFaceDetectionImagePickerViewController.h */, D20D46061E7D4475001113EC /* CLFaceDetectionImagePickerViewController.m */, D20D460B1E7D4980001113EC /* CLFaceDetectionImagePicker.storyboard */, D20D46071E7D4475001113EC /* UIImage+CL.h */, D20D46081E7D4475001113EC /* UIImage+CL.m */, ); name = Facedetecting; sourceTree = ""; }; D2A5C25E1E7CD15000CB7A92 = { isa = PBXGroup; children = ( D2A5C2691E7CD15100CB7A92 /* EZShopManager */, D2A5C2681E7CD15100CB7A92 /* Products */, D2D277EB5656D398E00413BE /* Pods */, A66D37A6A666E7900AA023BC /* Frameworks */, ); sourceTree = ""; }; D2A5C2681E7CD15100CB7A92 /* Products */ = { isa = PBXGroup; children = ( D2A5C2671E7CD15100CB7A92 /* EZShopManager.app */, ); name = Products; sourceTree = ""; }; D2A5C2691E7CD15100CB7A92 /* EZShopManager */ = { isa = PBXGroup; children = ( D20D460E1E7D4D25001113EC /* Assets.xcassets */, D20D460D1E7D4984001113EC /* Facedetecting */, D20D45EA1E7CDC09001113EC /* support */, D2A5C27C1E7CD4AC00CB7A92 /* Karios */, D2A5C26E1E7CD15100CB7A92 /* Main.storyboard */, D2A5C2871E7CD5E000CB7A92 /* EnrollViewController.swift */, D20D46101E7D5F04001113EC /* UsersTableViewController.swift */, D20D46121E7D6188001113EC /* UserDetailsViewController.swift */, D21E8BE81E7D691F00316040 /* User.swift */, D21E8BEA1E7D695300316040 /* Item.swift */, D25E55671E7DD4A7000B18D8 /* InventoriesViewController.swift */, ); path = EZShopManager; sourceTree = ""; }; D2A5C27C1E7CD4AC00CB7A92 /* Karios */ = { isa = PBXGroup; children = ( D2A5C27D1E7CD4BA00CB7A92 /* kairos.swift */, D21E8BE61E7D63D000316040 /* MySplitViewController.swift */, ); name = Karios; sourceTree = ""; }; D2D277EB5656D398E00413BE /* Pods */ = { isa = PBXGroup; children = ( A321DCAF31FEACCFF80B5A25 /* Pods-EZShopManager.debug.xcconfig */, AD2FC764B32F07AC46A0E19C /* Pods-EZShopManager.release.xcconfig */, ); name = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ D2A5C2661E7CD15000CB7A92 /* EZShopManager */ = { isa = PBXNativeTarget; buildConfigurationList = D2A5C2791E7CD15100CB7A92 /* Build configuration list for PBXNativeTarget "EZShopManager" */; buildPhases = ( 41CB064A8C5346964B8211AC /* [CP] Check Pods Manifest.lock */, D2A5C2631E7CD15000CB7A92 /* Sources */, D2A5C2641E7CD15000CB7A92 /* Frameworks */, D2A5C2651E7CD15000CB7A92 /* Resources */, AFF9A09742A844832BB00E3E /* [CP] Embed Pods Frameworks */, 08CFED35516B2CD46FF12605 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = EZShopManager; productName = EZShopManager; productReference = D2A5C2671E7CD15100CB7A92 /* EZShopManager.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ D2A5C25F1E7CD15000CB7A92 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0820; LastUpgradeCheck = 0820; ORGANIZATIONNAME = "Jung Geon Choi"; TargetAttributes = { D2A5C2661E7CD15000CB7A92 = { CreatedOnToolsVersion = 8.2.1; DevelopmentTeam = VQJM9GW22Y; ProvisioningStyle = Automatic; }; }; }; buildConfigurationList = D2A5C2621E7CD15000CB7A92 /* Build configuration list for PBXProject "EZShopManager" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = D2A5C25E1E7CD15000CB7A92; productRefGroup = D2A5C2681E7CD15100CB7A92 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( D2A5C2661E7CD15000CB7A92 /* EZShopManager */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ D2A5C2651E7CD15000CB7A92 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( D2A5C2751E7CD15100CB7A92 /* LaunchScreen.storyboard in Resources */, D20D460C1E7D4980001113EC /* CLFaceDetectionImagePicker.storyboard in Resources */, D20D45F01E7CE14D001113EC /* GoogleService-Info.plist in Resources */, D2A5C2701E7CD15100CB7A92 /* Main.storyboard in Resources */, D20D460F1E7D4D25001113EC /* Assets.xcassets in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 08CFED35516B2CD46FF12605 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-resources.sh\"\n"; showEnvVarsInLog = 0; }; 41CB064A8C5346964B8211AC /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_ROOT}/../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"; showEnvVarsInLog = 0; }; AFF9A09742A844832BB00E3E /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ D2A5C2631E7CD15000CB7A92 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( D2A5C2881E7CD5E000CB7A92 /* EnrollViewController.swift in Sources */, D21E8BE71E7D63D000316040 /* MySplitViewController.swift in Sources */, D2A5C27E1E7CD4BA00CB7A92 /* kairos.swift in Sources */, D20D46111E7D5F04001113EC /* UsersTableViewController.swift in Sources */, D21E8BEB1E7D695300316040 /* Item.swift in Sources */, D25E55681E7DD4A7000B18D8 /* InventoriesViewController.swift in Sources */, D20D45EC1E7CE031001113EC /* JGUtils.swift in Sources */, D2A5C26B1E7CD15100CB7A92 /* AppDelegate.swift in Sources */, D20D46091E7D4475001113EC /* CLFaceDetectionImagePickerViewController.m in Sources */, D20D45EE1E7CE0C8001113EC /* ActivitiyIndicator.swift in Sources */, D20D460A1E7D4475001113EC /* UIImage+CL.m in Sources */, D20D46131E7D6188001113EC /* UserDetailsViewController.swift in Sources */, D21E8BE91E7D691F00316040 /* User.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ D2A5C26E1E7CD15100CB7A92 /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( D2A5C26F1E7CD15100CB7A92 /* Base */, ); name = Main.storyboard; sourceTree = ""; }; D2A5C2731E7CD15100CB7A92 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( D2A5C2741E7CD15100CB7A92 /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ D2A5C2771E7CD15100CB7A92 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = 2; }; name = Debug; }; D2A5C2781E7CD15100CB7A92 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = 2; VALIDATE_PRODUCT = YES; }; name = Release; }; D2A5C27A1E7CD15100CB7A92 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = A321DCAF31FEACCFF80B5A25 /* Pods-EZShopManager.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; DEVELOPMENT_TEAM = VQJM9GW22Y; INFOPLIST_FILE = EZShopManager/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = ca.jgchoi.EZShopManager; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "EZshopManager/EZShopManager-Bridging-Header.h"; SWIFT_VERSION = 3.0; }; name = Debug; }; D2A5C27B1E7CD15100CB7A92 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = AD2FC764B32F07AC46A0E19C /* Pods-EZShopManager.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; DEVELOPMENT_TEAM = VQJM9GW22Y; INFOPLIST_FILE = EZShopManager/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = ca.jgchoi.EZShopManager; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "EZshopManager/EZShopManager-Bridging-Header.h"; SWIFT_VERSION = 3.0; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ D2A5C2621E7CD15000CB7A92 /* Build configuration list for PBXProject "EZShopManager" */ = { isa = XCConfigurationList; buildConfigurations = ( D2A5C2771E7CD15100CB7A92 /* Debug */, D2A5C2781E7CD15100CB7A92 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; D2A5C2791E7CD15100CB7A92 /* Build configuration list for PBXNativeTarget "EZShopManager" */ = { isa = XCConfigurationList; buildConfigurations = ( D2A5C27A1E7CD15100CB7A92 /* Debug */, D2A5C27B1E7CD15100CB7A92 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = D2A5C25F1E7CD15000CB7A92 /* Project object */; } ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/EZShopManager.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/xcschememanagement.plist ================================================ SchemeUserState EZShopManager.xcscheme orderHint 0 SuppressBuildableAutocreation D2A5C2661E7CD15000CB7A92 primary ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: iOS/Manager/EZShopManager/EZShopManager.xcworkspace/xcuserdata/jchoi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Podfile ================================================ # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'EZShopManager' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for EZShopManager pod 'AlamofireSwiftyJSON' pod 'Firebase/Core' pod 'Firebase/Database' pod 'Firebase/Storage' pod 'Kingfisher', '~> 3.0' end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/LICENSE ================================================ Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/README.md ================================================ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) Alamofire is an HTTP networking library written in Swift. - [Features](#features) - [Component Libraries](#component-libraries) - [Requirements](#requirements) - [Migration Guides](#migration-guides) - [Communication](#communication) - [Installation](#installation) - [Usage](#usage) - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) - [Advanced Usage](#advanced-usage) - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) - **Connection -** [Security](#security), [Network Reachability](#network-reachability) - [Open Radars](#open-radars) - [FAQ](#faq) - [Credits](#credits) - [Donations](#donations) - [License](#license) ## Features - [x] Chainable Request / Response Methods - [x] URL / JSON / plist Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData - [x] Download File using Request or Resume Data - [x] Authentication with URLCredential - [x] HTTP Response Validation - [x] Upload and Download Progress Closures with Progress - [x] cURL Command Output - [x] Dynamically Adapt and Retry Requests - [x] TLS Certificate and Public Key Pinning - [x] Network Reachability - [x] Comprehensive Unit and Integration Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) ## Component Libraries In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. - [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. ## Requirements - iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ - Xcode 8.1+ - Swift 3.0+ ## Migration Guides - [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) - [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) - [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) ## Communication - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). - If you **found a bug**, open an issue. - If you **have a feature request**, open an issue. - If you **want to contribute**, submit a pull request. ## Installation ### CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: ```bash $ gem install cocoapods ``` > CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' use_frameworks! target '' do pod 'Alamofire', '~> 4.3' end ``` Then, run the following command: ```bash $ pod install ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with [Homebrew](http://brew.sh/) using the following command: ```bash $ brew update $ brew install carthage ``` To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "Alamofire/Alamofire" ~> 4.3 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. ### Swift Pacakge Manager The [Swift Pacakage Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. ```swift dependencies: [ .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) ] ``` ### Manually If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. #### Embedded Framework - Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: ```bash $ git init ``` - Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git ``` - Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - Select the top `Alamofire.framework` for iOS and the bottom one for OS X. > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. - And that's it! > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. --- ## Usage ### Making a Request ```swift import Alamofire Alamofire.request("https://httpbin.org/get") ``` ### Response Handling Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } ``` In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. > Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. Alamofire contains five different response handlers by default including: ```swift // Response Handler - Unserialized Response func response( queue: DispatchQueue?, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self // Response Data Handler - Serialized into Data func responseData( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response String Handler - Serialized into String func responseString( queue: DispatchQueue?, encoding: String.Encoding?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response JSON Handler - Serialized into Any func responseJSON( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response PropertyList (plist) Handler - Serialized into Any func responsePropertyList( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void)) -> Self ``` None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. > For example, response status codes in the `400..<499` and `500..<599` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. #### Response Handler The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. ```swift Alamofire.request("https://httpbin.org/get").response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } ``` > We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. ```swift Alamofire.request("https://httpbin.org/get").responseData { response in debugPrint("All Response Info: \(response)") if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } ``` #### Response String Handler The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. ```swift Alamofire.request("https://httpbin.org/get").responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") } ``` > If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. #### Response JSON Handler The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in debugPrint(response) if let json = response.result.value { print("JSON: \(json)") } } ``` > All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. #### Chained Response Handlers Response handlers can even be chained: ```swift Alamofire.request("https://httpbin.org/get") .responseString { response in print("Response String: \(response.result.value)") } .responseJSON { response in print("Response JSON: \(response.result.value)") } ``` > It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. #### Response Handler Queue Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. ```swift let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in print("Executing response handler on utility queue") } ``` ### Response Validation By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. #### Manual Validation ```swift Alamofire.request("https://httpbin.org/get") .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseData { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } } ``` #### Automatic Validation Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. ```swift Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } } ``` ### Response Caching Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. > By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. ### HTTP Methods The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): ```swift public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } ``` These values can be passed as the `method` argument to the `Alamofire.request` API: ```swift Alamofire.request("https://httpbin.org/get") // method defaults to `.get` Alamofire.request("https://httpbin.org/post", method: .post) Alamofire.request("https://httpbin.org/put", method: .put) Alamofire.request("https://httpbin.org/delete", method: .delete) ``` > The `Alamofire.request` method parameter defaults to `.get`. ### Parameter Encoding Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. #### URL Encoding The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: - `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. - `.queryString` - Sets or appends encoded query string result to existing query string. - `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). ##### GET Request With URL-Encoded Parameters ```swift let parameters: Parameters = ["foo": "bar"] // All three of these calls are equivalent Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) // https://httpbin.org/get?foo=bar ``` ##### POST Request With URL-Encoded Parameters ```swift let parameters: Parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ] ] // All three of these calls are equivalent Alamofire.request("https://httpbin.org/post", parameters: parameters) Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody) // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 ``` #### JSON Encoding The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. ##### POST Request with JSON-Encoded Parameters ```swift let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ] ] // Both calls are equivalent Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) // HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} ``` #### Property List Encoding The `PropertyListEncoding` uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. #### Custom Encoding In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. ```swift struct JSONStringArrayEncoding: ParameterEncoding { private let array: [String] init(array: [String]) { self.array = array } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = urlRequest.urlRequest let data = try JSONSerialization.data(withJSONObject: array, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return urlRequest } } ``` #### Manual Parameter Encoding of a URLRequest The `ParameterEncoding` APIs can be used outside of making network requests. ```swift let url = URL(string: "https://httpbin.org/get")! var urlRequest = URLRequest(url: url) let parameters: Parameters = ["foo": "bar"] let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) ``` ### HTTP Headers Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. ```swift let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json" ] Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in debugPrint(response) } ``` > For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: - `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). - `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). - `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. ### Authentication Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). **Supported Authentication Schemes** - [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) - [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) - [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) - [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) #### HTTP Basic Authentication The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: ```swift let user = "user" let password = "password" Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .responseJSON { response in debugPrint(response) } ``` Depending upon your server implementation, an `Authorization` header may also be appropriate: ```swift let user = "user" let password = "password" var headers: HTTPHeaders = [:] if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { headers[authorizationHeader.key] = authorizationHeader.value } Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) .responseJSON { response in debugPrint(response) } ``` #### Authentication with URLCredential ```swift let user = "user" let password = "password" let credential = URLCredential(user: user, password: password, persistence: .forSession) Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(usingCredential: credential) .responseJSON { response in debugPrint(response) } ``` > It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. ### Downloading Data to a File Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. > This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. ```swift Alamofire.download("https://httpbin.org/image/png").responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` > The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. #### Download File Destination You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: - `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. - `.removePreviousFile` - Removes a previous file from the destination URL if specified. ```swift let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendPathComponent("pig.png") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(urlString, to: destination).response { response in print(response) if response.error == nil, let imagePath = response.destinationURL?.path { let image = UIImage(contentsOfFile: imagePath) } } ``` You can also use the suggested download destination API. ```swift let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory) Alamofire.download("https://httpbin.org/image/png", to: destination) ``` #### Download Progress Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. ```swift Alamofire.download("https://httpbin.org/image/png") .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. ```swift let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.download("https://httpbin.org/image/png") .downloadProgress(queue: utilityQueue) { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` #### Resuming a Download If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. > **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). ```swift class ImageRequestor { private var resumeData: Data? private var image: UIImage? func fetchImage(completion: (UIImage?) -> Void) { guard image == nil else { completion(image) ; return } let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendPathComponent("pig.png") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } let request: DownloadRequest if let resumeData = resumeData { request = Alamofire.download(resumingWith: resumeData) } else { request = Alamofire.download("https://httpbin.org/image/png") } request.responseData { response in switch response.result { case .success(let data): self.image = UIImage(data: data) case .failure: self.resumeData = response.resumeData } } } } ``` ### Uploading Data to a Server When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. > The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. #### Uploading Data ```swift let imageData = UIPNGRepresentation(image)! Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response) } ``` #### Uploading a File ```swift let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response) } ``` #### Uploading Multipart Form Data ```swift Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") }, to: "https://httpbin.org/post", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) ``` #### Upload Progress While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. ```swift let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") Alamofire.upload(fileURL, to: "https://httpbin.org/post") .uploadProgress { progress in // main queue by default print("Upload Progress: \(progress.fractionCompleted)") } .downloadProgress { progress in // main queue by default print("Download Progress: \(progress.fractionCompleted)") } .responseJSON { response in debugPrint(response) } ``` ### Statistical Metrics #### Timeline Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.timeline) } ``` The above reports the following `Timeline` info: - `Latency`: 0.428 seconds - `Request Duration`: 0.428 seconds - `Serialization Duration`: 0.001 seconds - `Total Duration`: 0.429 seconds #### URL Session Task Metrics In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.metrics) } ``` It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in if #available(iOS 10.0. *) { print(response.metrics) } } ``` ### cURL Command Output Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. #### CustomStringConvertible ```swift let request = Alamofire.request("https://httpbin.org/ip") print(request) // GET https://httpbin.org/ip (200) ``` #### CustomDebugStringConvertible ```swift let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) debugPrint(request) ``` Outputs: ```bash $ curl -i \ -H "User-Agent: Alamofire/4.0.0" \ -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ "https://httpbin.org/get?foo=bar" ``` --- ## Advanced Usage Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. **Recommended Reading** - [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) - [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) - [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) - [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) ### Session Manager Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. As such, the following two statements are equivalent: ```swift Alamofire.request("https://httpbin.org/get") ``` ```swift let sessionManager = Alamofire.SessionManager.default sessionManager.request("https://httpbin.org/get") ``` Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). #### Creating a Session Manager with Default Configuration ```swift let configuration = URLSessionConfiguration.default let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Creating a Session Manager with Background Configuration ```swift let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Creating a Session Manager with Ephemeral Configuration ```swift let configuration = URLSessionConfiguration.ephemeral let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Modifying the Session Configuration ```swift var defaultHeaders = Alamofire.SessionManager.default.defaultHTTPHeaders defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = defaultHeaders let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` > This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. ### Session Delegate By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. #### Override Closures The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: ```swift /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? ``` The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. ```swift let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) let delegate: Alamofire.SessionDelegate = sessionManager.delegate delegate.taskWillPerformHTTPRedirection = { session, task, response, request in var finalRequest = request if let originalRequest = task.originalRequest, let urlString = originalRequest.url?.urlString, urlString.contains("apple.com") { finalRequest = originalRequest } return finalRequest } ``` #### Subclassing Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. ```swift class LoggingSessionDelegate: SessionDelegate { override func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { print("URLSession will perform HTTP redirection to request: \(request)") super.urlSession( session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler ) } } ``` Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. > It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. ### Request The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. Requests can be suspended, resumed and cancelled: - `suspend()`: Suspends the underlying task and dispatch queue. - `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. - `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. ### Routing Requests As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. #### URLConvertible Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: ```swift let urlString = "https://httpbin.org/post" Alamofire.request(urlString, method: .post) let url = URL(string: urlString)! Alamofire.request(url, method: .post) let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! Alamofire.request(urlComponents, method: .post) ``` Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. ##### Type-Safe Routing ```swift extension User: URLConvertible { static let baseURLString = "https://example.com" func asURL() throws -> URL { let urlString = User.baseURLString + "/users/\(username)/" return try urlString.asURL() } } ``` ```swift let user = User(username: "mattt") Alamofire.request(user) // https://example.com/users/mattt ``` #### URLRequestConvertible Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): ```swift let url = URL(string: "https://httpbin.org/post")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" let parameters = ["foo": "bar"] do { urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) } catch { // No-op } urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") Alamofire.request(urlRequest) ``` Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. ##### API Parameter Abstraction ```swift enum Router: URLRequestConvertible { case search(query: String, page: Int) static let baseURLString = "https://example.com" static let perPage = 50 // MARK: URLRequestConvertible func asURLRequest() throws -> URLRequest { let result: (path: String, parameters: Parameters) = { switch self { case let .search(query, page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case let .search(query, _): return ("/search", ["q": query]) } }() let url = try Router.baseURLString.asURL() let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) return try URLEncoding.default.encode(urlRequest, with: result.parameters) } } ``` ```swift Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 ``` ##### CRUD & Authorization ```swift import Alamofire enum Router: URLRequestConvertible { case createUser(parameters: Parameters) case readUser(username: String) case updateUser(username: String, parameters: Parameters) case destroyUser(username: String) static let baseURLString = "https://example.com" var method: HTTPMethod { switch self { case .createUser: return .post case .readUser: return .get case .updateUser: return .put case .destroyUser: return .delete } } var path: String { switch self { case .createUser: return "/users" case .readUser(let username): return "/users/\(username)" case .updateUser(let username, _): return "/users/\(username)" case .destroyUser(let username): return "/users/\(username)" } } // MARK: URLRequestConvertible func asURLRequest() throws -> URLRequest { let url = try Router.baseURLString.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(path)) urlRequest.httpMethod = method.rawValue switch self { case .createUser(let parameters): urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) case .updateUser(_, let parameters): urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) default: break } return urlRequest } } ``` ```swift Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt ``` ### Adapting and Retrying Requests Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. #### RequestAdapter The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. ```swift class AccessTokenAdapter: RequestAdapter { private let accessToken: String init(accessToken: String) { self.accessToken = accessToken } func adapt(_ urlRequest: URLRequest) throws -> URLRequest { var urlRequest = urlRequest if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") } return urlRequest } } ``` ```swift let sessionManager = SessionManager() sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") sessionManager.request("https://httpbin.org/get") ``` #### RequestRetrier The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. > **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. > To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. ```swift class OAuth2Handler: RequestAdapter, RequestRetrier { private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void private let sessionManager: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() private let lock = NSLock() private var clientID: String private var baseURLString: String private var accessToken: String private var refreshToken: String private var isRefreshing = false private var requestsToRetry: [RequestRetryCompletion] = [] // MARK: - Initialization public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { self.clientID = clientID self.baseURLString = baseURLString self.accessToken = accessToken self.refreshToken = refreshToken } // MARK: - RequestAdapter func adapt(_ urlRequest: URLRequest) throws -> URLRequest { if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { var urlRequest = urlRequest urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") return urlRequest } return urlRequest } // MARK: - RequestRetrier func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { requestsToRetry.append(completion) if !isRefreshing { refreshTokens { [weak self] succeeded, accessToken, refreshToken in guard let strongSelf = self else { return } strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } if let accessToken = accessToken, let refreshToken = refreshToken { strongSelf.accessToken = accessToken strongSelf.refreshToken = refreshToken } strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } strongSelf.requestsToRetry.removeAll() } } } else { completion(false, 0.0) } } // MARK: - Private - Refresh Tokens private func refreshTokens(completion: @escaping RefreshCompletion) { guard !isRefreshing else { return } isRefreshing = true let urlString = "\(baseURLString)/oauth2/token" let parameters: [String: Any] = [ "access_token": accessToken, "refresh_token": refreshToken, "client_id": clientID, "grant_type": "refresh_token" ] sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { [weak self] response in guard let strongSelf = self else { return } if let json = response.result.value as? [String: Any], let accessToken = json["access_token"] as? String, let refreshToken = json["refresh_token"] as? String { completion(true, accessToken, refreshToken) } else { completion(false, nil, nil) } strongSelf.isRefreshing = false } } } ``` ```swift let baseURLString = "https://some.domain-behind-oauth2.com" let oauthHandler = OAuth2Handler( clientID: "12345678", baseURLString: baseURLString, accessToken: "abcd1234", refreshToken: "ef56789a" ) let sessionManager = SessionManager() sessionManager.adapter = oauthHandler sessionManager.retrier = oauthHandler let urlString = "\(baseURLString)/some/endpoint" sessionManager.request(urlString).validate().responseJSON { response in debugPrint(response) } ``` Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. > If you needed them to execute in the same order they were created, you could sort them by their task identifiers. The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. ### Custom Response Serialization #### Handling Errors Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. For example, here's a simple `BackendError` enum which will be used in later examples: ```swift enum BackendError: Error { case network(error: Error) // Capture any underlying Error from the URLSession API case dataSerialization(error: Error) case jsonSerialization(error: Error) case xmlSerialization(error: Error) case objectSerialization(reason: String) } ``` #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: ```swift extension DataRequest { static func xmlResponseSerializer() -> DataResponseSerializer { return DataResponseSerializer { request, response, data, error in // Pass through any underlying URLSession error to the .network case. guard error == nil else { return .failure(BackendError.network(error: error!)) } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. let result = Request.serializeResponseData(response: response, data: data, error: nil) guard case let .success(validData) = result else { return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) } do { let xml = try ONOXMLDocument(data: validData) return .success(xml) } catch { return .failure(BackendError.xmlSerialization(error: error)) } } } @discardableResult func responseXMLDocument( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.xmlResponseSerializer(), completionHandler: completionHandler ) } } ``` #### Generic Response Object Serialization Generics can be used to provide automatic, type-safe response object serialization. ```swift protocol ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) } extension DataRequest { func responseObject( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { let responseSerializer = DataResponseSerializer { request, response, data, error in guard error == nil else { return .failure(BackendError.network(error: error!)) } let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) guard case let .success(jsonObject) = result else { return .failure(BackendError.jsonSerialization(error: result.error!)) } guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) } return .success(responseObject) } return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) } } ``` ```swift struct User: ResponseObjectSerializable, CustomStringConvertible { let username: String let name: String var description: String { return "User: { username: \(username), name: \(name) }" } init?(response: HTTPURLResponse, representation: Any) { guard let username = response.url?.lastPathComponent, let representation = representation as? [String: Any], let name = representation["name"] as? String else { return nil } self.username = username self.name = name } } ``` ```swift Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in debugPrint(response) if let user = response.result.value { print("User: { username: \(user.username), name: \(user.name) }") } } ``` The same approach can also be used to handle endpoints that return a representation of a collection of objects: ```swift protocol ResponseCollectionSerializable { static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] } extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { var collection: [Self] = [] if let representation = representation as? [[String: Any]] { for itemRepresentation in representation { if let item = Self(response: response, representation: itemRepresentation) { collection.append(item) } } } return collection } } ``` ```swift extension DataRequest { @discardableResult func responseCollection( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self { let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in guard error == nil else { return .failure(BackendError.network(error: error!)) } let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = jsonSerializer.serializeResponse(request, response, data, nil) guard case let .success(jsonObject) = result else { return .failure(BackendError.jsonSerialization(error: result.error!)) } guard let response = response else { let reason = "Response collection could not be serialized due to nil response." return .failure(BackendError.objectSerialization(reason: reason)) } return .success(T.collection(from: response, withRepresentation: jsonObject)) } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } } ``` ```swift struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { let username: String let name: String var description: String { return "User: { username: \(username), name: \(name) }" } init?(response: HTTPURLResponse, representation: Any) { guard let username = response.url?.lastPathComponent, let representation = representation as? [String: Any], let name = representation["name"] as? String else { return nil } self.username = username self.name = name } } ``` ```swift Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in debugPrint(response) if let users = response.result.value { users.forEach { print("- \($0)") } } } ``` ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. #### ServerTrustPolicy The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. ```swift let serverTrustPolicy = ServerTrustPolicy.pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true ) ``` There are many different cases of server trust evaluation giving you complete control over the validation process: * `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. * `pinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. * `pinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. * `disableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. * `customEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. #### Server Trust Policy Manager The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. ```swift let serverTrustPolicies: [String: ServerTrustPolicy] = [ "test.example.com": .pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true ), "insecure.expired-apis.com": .disableEvaluation ] let sessionManager = SessionManager( serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) ) ``` > Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. These server trust policies will result in the following behavior: - `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: - Certificate chain MUST be valid. - Certificate chain MUST include one of the pinned certificates. - Challenge host MUST match the host in the certificate chain's leaf certificate. - `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. - All other hosts will use the default evaluation provided by Apple. ##### Subclassing Server Trust Policy Manager If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. ```swift class CustomServerTrustPolicyManager: ServerTrustPolicyManager { override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { var policy: ServerTrustPolicy? // Implement your custom domain matching behavior... return policy } } ``` #### Validating the Host The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. > It is recommended that `validateHost` always be set to `true` in production environments. #### Validating the Certificate Chain Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. > It is recommended that `validateCertificateChain` always be set to `true` in production environments. #### App Transport Security With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. ```xml NSAppTransportSecurity NSExceptionDomains example.com NSExceptionAllowsInsecureHTTPLoads NSExceptionRequiresForwardSecrecy NSIncludesSubdomains NSTemporaryExceptionMinimumTLSVersion TLSv1.2 ``` Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. > It is recommended to always use valid certificates in production environments. ### Network Reachability The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. ```swift let manager = NetworkReachabilityManager(host: "www.apple.com") manager?.listener = { status in print("Network Status Changed: \(status)") } manager?.startListening() ``` > Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. There are some important things to remember when using network reachability to determine what to do next. - **Do NOT** use Reachability to determine if a network request should be sent. - You should **ALWAYS** send it. - When Reachability is restored, use the event to retry failed network requests. - Even though the network requests may still fail, this is a good moment to retry them. - The network reachability status can be useful for determining why a network request may have failed. - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." > It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. --- ## Open Radars The following radars have some effect on the current implementation of Alamofire. - [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case - [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage - `rdar://26870455` - Background URL Session Configurations do not work in the simulator - `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` ## FAQ ### What's the origin of the name Alamofire? Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. ### What logic belongs in a Router vs. a Request Adapter? Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. --- ## Credits Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. ### Security Disclosure If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. ## Donations The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: - Pay our legal fees to register as a federal non-profit organization - Pay our yearly legal fees to keep the non-profit in good status - Pay for our mail servers to help us stay on top of all questions and security issues - Potentially fund test servers to make it easier for us to test the edge cases - Potentially fund developers to work on one of our projects full-time The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! ## License Alamofire is released under the MIT license. See LICENSE for details. ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/AFError.swift ================================================ // // AFError.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with /// their own associated reasons. /// /// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. /// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. /// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. /// - responseValidationFailed: Returned when a `validate()` call fails. /// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. public enum AFError: Error { /// The underlying reason the parameter encoding error occurred. /// /// - missingURL: The URL request did not have a URL to encode. /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the /// encoding process. /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during /// encoding process. public enum ParameterEncodingFailureReason { case missingURL case jsonEncodingFailed(error: Error) case propertyListEncodingFailed(error: Error) } /// The underlying reason the multipart encoding error occurred. /// /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a /// file URL. /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty /// `lastPathComponent` or `pathExtension. /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw /// an error. /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by /// the system. /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided /// threw an error. /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the /// encoded data to disk. /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file /// already exists at the provided `fileURL`. /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is /// not a file URL. /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an /// underlying error. /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with /// underlying system error. public enum MultipartEncodingFailureReason { case bodyPartURLInvalid(url: URL) case bodyPartFilenameInvalid(in: URL) case bodyPartFileNotReachable(at: URL) case bodyPartFileNotReachableWithError(atURL: URL, error: Error) case bodyPartFileIsDirectory(at: URL) case bodyPartFileSizeNotAvailable(at: URL) case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) case bodyPartInputStreamCreationFailed(for: URL) case outputStreamCreationFailed(for: URL) case outputStreamFileAlreadyExists(at: URL) case outputStreamURLInvalid(url: URL) case outputStreamWriteFailed(error: Error) case inputStreamReadFailed(error: Error) } /// The underlying reason the response validation error occurred. /// /// - dataFileNil: The data file containing the server response did not exist. /// - dataFileReadFailed: The data file containing the server response could not be read. /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` /// provided did not contain wildcard type. /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided /// `acceptableContentTypes`. /// - unacceptableStatusCode: The response status code was not acceptable. public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(code: Int) } /// The underlying reason the response serialization error occurred. /// /// - inputDataNil: The server response contained no data. /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. /// - inputFileNil: The file containing the server response did not exist. /// - inputFileReadFailed: The file containing the server response could not be read. /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. public enum ResponseSerializationFailureReason { case inputDataNil case inputDataNilOrZeroLength case inputFileNil case inputFileReadFailed(at: URL) case stringSerializationFailed(encoding: String.Encoding) case jsonSerializationFailed(error: Error) case propertyListSerializationFailed(error: Error) } case invalidURL(url: URLConvertible) case parameterEncodingFailed(reason: ParameterEncodingFailureReason) case multipartEncodingFailed(reason: MultipartEncodingFailureReason) case responseValidationFailed(reason: ResponseValidationFailureReason) case responseSerializationFailed(reason: ResponseSerializationFailureReason) } // MARK: - Adapt Error struct AdaptError: Error { let error: Error } extension Error { var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } } // MARK: - Error Booleans extension AFError { /// Returns whether the AFError is an invalid URL error. public var isInvalidURLError: Bool { if case .invalidURL = self { return true } return false } /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will /// contain the associated value. public var isParameterEncodingError: Bool { if case .parameterEncodingFailed = self { return true } return false } /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties /// will contain the associated values. public var isMultipartEncodingError: Bool { if case .multipartEncodingFailed = self { return true } return false } /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, /// `responseContentType`, and `responseCode` properties will contain the associated values. public var isResponseValidationError: Bool { if case .responseValidationFailed = self { return true } return false } /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and /// `underlyingError` properties will contain the associated values. public var isResponseSerializationError: Bool { if case .responseSerializationFailed = self { return true } return false } } // MARK: - Convenience Properties extension AFError { /// The `URLConvertible` associated with the error. public var urlConvertible: URLConvertible? { switch self { case .invalidURL(let url): return url default: return nil } } /// The `URL` associated with the error. public var url: URL? { switch self { case .multipartEncodingFailed(let reason): return reason.url default: return nil } } /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. public var underlyingError: Error? { switch self { case .parameterEncodingFailed(let reason): return reason.underlyingError case .multipartEncodingFailed(let reason): return reason.underlyingError case .responseSerializationFailed(let reason): return reason.underlyingError default: return nil } } /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. public var acceptableContentTypes: [String]? { switch self { case .responseValidationFailed(let reason): return reason.acceptableContentTypes default: return nil } } /// The response `Content-Type` of a `.responseValidationFailed` error. public var responseContentType: String? { switch self { case .responseValidationFailed(let reason): return reason.responseContentType default: return nil } } /// The response code of a `.responseValidationFailed` error. public var responseCode: Int? { switch self { case .responseValidationFailed(let reason): return reason.responseCode default: return nil } } /// The `String.Encoding` associated with a failed `.stringResponse()` call. public var failedStringEncoding: String.Encoding? { switch self { case .responseSerializationFailed(let reason): return reason.failedStringEncoding default: return nil } } } extension AFError.ParameterEncodingFailureReason { var underlyingError: Error? { switch self { case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): return error default: return nil } } } extension AFError.MultipartEncodingFailureReason { var url: URL? { switch self { case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): return url default: return nil } } var underlyingError: Error? { switch self { case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): return error default: return nil } } } extension AFError.ResponseValidationFailureReason { var acceptableContentTypes: [String]? { switch self { case .missingContentType(let types), .unacceptableContentType(let types, _): return types default: return nil } } var responseContentType: String? { switch self { case .unacceptableContentType(_, let responseType): return responseType default: return nil } } var responseCode: Int? { switch self { case .unacceptableStatusCode(let code): return code default: return nil } } } extension AFError.ResponseSerializationFailureReason { var failedStringEncoding: String.Encoding? { switch self { case .stringSerializationFailed(let encoding): return encoding default: return nil } } var underlyingError: Error? { switch self { case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): return error default: return nil } } } // MARK: - Error Descriptions extension AFError: LocalizedError { public var errorDescription: String? { switch self { case .invalidURL(let url): return "URL is not valid: \(url)" case .parameterEncodingFailed(let reason): return reason.localizedDescription case .multipartEncodingFailed(let reason): return reason.localizedDescription case .responseValidationFailed(let reason): return reason.localizedDescription case .responseSerializationFailed(let reason): return reason.localizedDescription } } } extension AFError.ParameterEncodingFailureReason { var localizedDescription: String { switch self { case .missingURL: return "URL request to encode was missing a URL" case .jsonEncodingFailed(let error): return "JSON could not be encoded because of error:\n\(error.localizedDescription)" case .propertyListEncodingFailed(let error): return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" } } } extension AFError.MultipartEncodingFailureReason { var localizedDescription: String { switch self { case .bodyPartURLInvalid(let url): return "The URL provided is not a file URL: \(url)" case .bodyPartFilenameInvalid(let url): return "The URL provided does not have a valid filename: \(url)" case .bodyPartFileNotReachable(let url): return "The URL provided is not reachable: \(url)" case .bodyPartFileNotReachableWithError(let url, let error): return ( "The system returned an error while checking the provided URL for " + "reachability.\nURL: \(url)\nError: \(error)" ) case .bodyPartFileIsDirectory(let url): return "The URL provided is a directory: \(url)" case .bodyPartFileSizeNotAvailable(let url): return "Could not fetch the file size from the provided URL: \(url)" case .bodyPartFileSizeQueryFailedWithError(let url, let error): return ( "The system returned an error while attempting to fetch the file size from the " + "provided URL.\nURL: \(url)\nError: \(error)" ) case .bodyPartInputStreamCreationFailed(let url): return "Failed to create an InputStream for the provided URL: \(url)" case .outputStreamCreationFailed(let url): return "Failed to create an OutputStream for URL: \(url)" case .outputStreamFileAlreadyExists(let url): return "A file already exists at the provided URL: \(url)" case .outputStreamURLInvalid(let url): return "The provided OutputStream URL is invalid: \(url)" case .outputStreamWriteFailed(let error): return "OutputStream write failed with error: \(error)" case .inputStreamReadFailed(let error): return "InputStream read failed with error: \(error)" } } } extension AFError.ResponseSerializationFailureReason { var localizedDescription: String { switch self { case .inputDataNil: return "Response could not be serialized, input data was nil." case .inputDataNilOrZeroLength: return "Response could not be serialized, input data was nil or zero length." case .inputFileNil: return "Response could not be serialized, input file was nil." case .inputFileReadFailed(let url): return "Response could not be serialized, input file could not be read: \(url)." case .stringSerializationFailed(let encoding): return "String could not be serialized with encoding: \(encoding)." case .jsonSerializationFailed(let error): return "JSON could not be serialized because of error:\n\(error.localizedDescription)" case .propertyListSerializationFailed(let error): return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" } } } extension AFError.ResponseValidationFailureReason { var localizedDescription: String { switch self { case .dataFileNil: return "Response could not be validated, data file was nil." case .dataFileReadFailed(let url): return "Response could not be validated, data file could not be read: \(url)." case .missingContentType(let types): return ( "Response Content-Type was missing and acceptable content types " + "(\(types.joined(separator: ","))) do not match \"*/*\"." ) case .unacceptableContentType(let acceptableTypes, let responseType): return ( "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + "\(acceptableTypes.joined(separator: ","))." ) case .unacceptableStatusCode(let code): return "Response status code was unacceptable: \(code)." } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Alamofire.swift ================================================ // // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct /// URL requests. public protocol URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. func asURL() throws -> URL } extension String: URLConvertible { /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. /// /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } return url } } extension URL: URLConvertible { /// Returns self. public func asURL() throws -> URL { return self } } extension URLComponents: URLConvertible { /// Returns a URL if `url` is not nil, otherise throws an `Error`. /// /// - throws: An `AFError.invalidURL` if `url` is `nil`. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = url else { throw AFError.invalidURL(url: self) } return url } } // MARK: - /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. public protocol URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. func asURLRequest() throws -> URLRequest } extension URLRequestConvertible { /// The URL request. public var urlRequest: URLRequest? { return try? asURLRequest() } } extension URLRequest: URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. public func asURLRequest() throws -> URLRequest { return self } } // MARK: - extension URLRequest { /// Creates an instance with the specified `method`, `urlString` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The new `URLRequest` instance. public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { let url = try url.asURL() self.init(url: url) httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { setValue(headerValue, forHTTPHeaderField: headerField) } } } func adapt(using adapter: RequestAdapter?) throws -> URLRequest { guard let adapter = adapter else { return self } return try adapter.adapt(self) } } // MARK: - Data Request /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult public func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { return SessionManager.default.request( url, method: method, parameters: parameters, encoding: encoding, headers: headers ) } /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest`. /// /// - parameter urlRequest: The URL request /// /// - returns: The created `DataRequest`. @discardableResult public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { return SessionManager.default.request(urlRequest) } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download( url, method: method, parameters: parameters, encoding: encoding, headers: headers, to: destination ) } /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter urlRequest: The URL request. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(urlRequest, to: destination) } // MARK: Resume Data /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional /// information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(resumingWith: resumeData, to: destination) } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) } /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(fileURL, with: urlRequest) } // MARK: Data /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(data, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(data, with: urlRequest) } // MARK: InputStream /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `stream`. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(stream, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `stream`. /// /// - parameter urlRequest: The URL request. /// - parameter stream: The stream to upload. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(stream, with: urlRequest) } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, to: url, method: method, headers: headers, encodingCompletion: encodingCompletion ) } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` /// and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(withHostName hostName: String, port: Int) -> StreamRequest { return SessionManager.default.stream(withHostName: hostName, port: port) } // MARK: NetService /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(with netService: NetService) -> StreamRequest { return SessionManager.default.stream(with: netService) } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift ================================================ // // DispatchQueue+Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Dispatch import Foundation extension DispatchQueue { static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { asyncAfter(deadline: .now() + delay, execute: closure) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/MultipartFormData.swift ================================================ // // MultipartFormData.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(macOS) import CoreServices #endif /// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode /// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead /// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the /// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for /// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. /// /// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well /// and the w3 form documentation. /// /// - https://www.ietf.org/rfc/rfc2388.txt /// - https://www.ietf.org/rfc/rfc2045.txt /// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 open class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { case .initial: boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" case .encapsulated: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" case .final: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } class BodyPart { let headers: HTTPHeaders let bodyStream: InputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: AFError? private let streamBufferSize: Int // MARK: - Lifecycle /// Creates a multipart form data object. /// /// - returns: The multipart form data object. public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /// /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more /// information, please refer to the following article: /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html /// self.streamBufferSize = 1024 } // MARK: - Body Parts /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. public func append(_ data: Data, withName name: String) { let headers = contentHeaders(withName: name) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, mimeType: String) { let headers = contentHeaders(withName: name, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the /// system associated MIME type. /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. public func append(_ fileURL: URL, withName name: String) { let fileName = fileURL.lastPathComponent let pathExtension = fileURL.pathExtension if !fileName.isEmpty && !pathExtension.isEmpty { let mime = mimeType(forPathExtension: pathExtension) append(fileURL, withName: name, fileName: fileName, mimeType: mime) } else { setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) } } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) /// - Content-Type: #{mimeType} (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.isFileURL else { setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ do { let isReachable = try fileURL.checkPromisedItemIsReachable() guard isReachable else { setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) return } } catch { setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false let path = fileURL.path guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ let bodyContentLength: UInt64 do { guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) return } bodyContentLength = fileSize.uint64Value } catch { setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = InputStream(url: fileURL) else { setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) return } append(stream, withLength: bodyContentLength, headers: headers) } /// Creates a body part from the stream and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. public func append( _ stream: InputStream, withLength length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) append(stream, withLength: length, headers: headers) } /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - HTTP headers /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter headers: The HTTP headers for the body part. public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /// Encodes all the appended body parts into a single `Data` value. /// /// It is important to note that this method will load all the appended body parts into memory all at the same /// time. This method should only be used when the encoded data will have a small memory footprint. For large data /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. /// /// - throws: An `AFError` if encoding encounters an error. /// /// - returns: The encoded `Data` if encoding is successful. public func encode() throws -> Data { if let bodyPartError = bodyPartError { throw bodyPartError } var encoded = Data() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encode(bodyPart) encoded.append(encodedData) } return encoded } /// Writes the appended body parts into the given file URL. /// /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, /// this approach is very memory efficient and should be used for large body part data. /// /// - parameter fileURL: The file URL to write the multipart form data into. /// /// - throws: An `AFError` if encoding encounters an error. public func writeEncodedData(to fileURL: URL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if FileManager.default.fileExists(atPath: fileURL.path) { throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) } else if !fileURL.isFileURL { throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) } guard let outputStream = OutputStream(url: fileURL, append: false) else { throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) } outputStream.open() defer { outputStream.close() } self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try write(bodyPart, to: outputStream) } } // MARK: - Private - Body Part Encoding private func encode(_ bodyPart: BodyPart) throws -> Data { var encoded = Data() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.append(initialData) let headerData = encodeHeaders(for: bodyPart) encoded.append(headerData) let bodyStreamData = try encodeBodyStream(for: bodyPart) encoded.append(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.append(finalBoundaryData()) } return encoded } private func encodeHeaders(for bodyPart: BodyPart) -> Data { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.crlf)" } headerText += EncodingCharacters.crlf return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let error = inputStream.streamError { throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) } if bytesRead > 0 { encoded.append(buffer, count: bytesRead) } else { break } } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { try writeInitialBoundaryData(for: bodyPart, to: outputStream) try writeHeaderData(for: bodyPart, to: outputStream) try writeBodyStream(for: bodyPart, to: outputStream) try writeFinalBoundaryData(for: bodyPart, to: outputStream) } private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try write(initialData, to: outputStream) } private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let headerData = encodeHeaders(for: bodyPart) return try write(headerData, to: outputStream) } private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let error = outputStream.streamError { throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten.. String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { var disposition = "form-data; name=\"\(name)\"" if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } var headers = ["Content-Disposition": disposition] if let mimeType = mimeType { headers["Content-Type"] = mimeType } return headers } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) } private func encapsulatedBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) } private func finalBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { guard bodyPartError == nil else { return } bodyPartError = AFError.multipartEncodingFailed(reason: reason) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/NetworkReachabilityManager.swift ================================================ // // NetworkReachabilityManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) import Foundation import SystemConfiguration /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and /// WiFi network interfaces. /// /// Reachability can be used to determine background information about why a network operation failed, or to retry /// network requests when a connection is established. It should not be used to prevent a user from initiating a network /// request, as it's possible that an initial request may be required to establish reachability. public class NetworkReachabilityManager { /// Defines the various states of network reachability. /// /// - unknown: It is unknown whether the network is reachable. /// - notReachable: The network is not reachable. /// - reachable: The network is reachable. public enum NetworkReachabilityStatus { case unknown case notReachable case reachable(ConnectionType) } /// Defines the various connection types detected by reachability flags. /// /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. /// - wwan: The connection type is a WWAN connection. public enum ConnectionType { case ethernetOrWiFi case wwan } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void // MARK: - Properties /// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } /// Whether the network is currently reachable over Ethernet or WiFi interface. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } /// The current network reachability status. public var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. public var listenerQueue: DispatchQueue = DispatchQueue.main /// A closure executed when the network reachability status changes. public var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability private var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /// Creates a `NetworkReachabilityManager` instance with the specified host. /// /// - parameter host: The host used to evaluate network reachability. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. /// /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing /// status of the device, both IPv4 and IPv6. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?() { var address = sockaddr_in() address.sin_len = UInt8(MemoryLayout.size) address.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(to: &address, { pointer in return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { return SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability self.previousFlags = SCNetworkReachabilityFlags() } deinit { stopListening() } // MARK: - Listening /// Starts listening for changes in network reachability status. /// /// - returns: `true` if listening was started successfully, `false` otherwise. @discardableResult public func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = Unmanaged.passUnretained(self).toOpaque() let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) listenerQueue.async { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } return callbackEnabled && queueEnabled } /// Stops listening for changes in network reachability status. public func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(_ flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard flags.contains(.reachable) else { return .notReachable } var networkStatus: NetworkReachabilityStatus = .notReachable if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) { if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } } #if os(iOS) if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } #endif return networkStatus } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /// Returns whether the two network reachability status values are equal. /// /// - parameter lhs: The left-hand side value to compare. /// - parameter rhs: The right-hand side value to compare. /// /// - returns: `true` if the two values are equal, `false` otherwise. public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.notReachable, .notReachable): return true case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Notifications.swift ================================================ // // Notifications.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Notification.Name { /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") } } // MARK: - extension Notification { /// Used as a namespace for all `Notification` user info dictionary keys. public struct Key { /// User info dictionary key representing the `URLSessionTask` associated with the notification. public static let Task = "org.alamofire.notification.key.task" } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/ParameterEncoding.swift ================================================ // // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode /// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending /// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent) { self.destination = destination } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: "\(key)[]", value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape((value.boolValue ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape((bool ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex.. String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. /// /// - parameter urlRequest: The request to apply the JSON object to. /// - parameter jsonObject: The JSON object to apply to the request. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header /// field of an encoded request is set to `application/x-plist`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Request.swift ================================================ // // Request.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } /// The number of times the request has been retried. open internal(set) var retryCount: UInt = 0 let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.sync { session.dataTask(with: urlRequest) } } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let requestable = originalTask as? Requestable { return requestable.urlRequest } return nil } /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.sync { session.downloadTask(withResumeData: resumeData) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { return urlRequest } return nil } /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } guard let uploadable = originalTask as? Uploadable else { return nil } switch uploadable { case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): return urlRequest } } /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.sync { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.sync { session.streamTask(with: netService) } } return task } } } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Response.swift ================================================ // // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/ResponseSerialization.swift ================================================ // // ResponseSerialization.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The type in which all data response serializers must conform to in order to serialize a response. public protocol DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, data and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } } // MARK: - /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DataResponseSerializer: DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, data and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { self.serializeResponse = serializeResponse } } // MARK: - /// The type in which all download response serializers must conform to in order to serialize a response. public protocol DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, url and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } } // MARK: - /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, url and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { self.serializeResponse = serializeResponse } } // MARK: - Timeline extension Request { var timeline: Timeline { let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime return Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) } } // MARK: - Default extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var dataResponse = DefaultDataResponse( request: self.request, response: self.response, data: self.delegate.data, error: self.delegate.error, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) completionHandler(dataResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DataResponse) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) var dataResponse = DataResponse( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } } return self } } extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDownloadResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var downloadResponse = DefaultDownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, error: self.downloadDelegate.error, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) completionHandler(downloadResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data contained in the destination url. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.downloadDelegate.fileURL, self.downloadDelegate.error ) var downloadResponse = DownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, result: result, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self } } // MARK: - Data extension Request { /// Returns a result data type that contains the response data as-is. /// /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return .success(validData) } } extension DataRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseData(response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseData(response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } // MARK: - String extension Request { /// Returns a result string type initialized from the response data with the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } } extension DataRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(json) } catch { return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /// Returns a plist object contained in a result type constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponsePropertyList( options: PropertyListSerialization.ReadOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) return .success(plist) } catch { return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set = [204, 205] ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Result.swift ================================================ // // Result.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to represent whether a request was successful or encountered an error. /// /// - success: The request and all post processing operations were successful resulting in the serialization of the /// provided associated value. /// /// - failure: The request encountered an error resulting in a failure. The associated values are the original data /// provided by the server as well as the error that caused the failure. public enum Result { case success(Value) case failure(Error) /// Returns `true` if the result is a success, `false` otherwise. public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } /// Returns `true` if the result is a failure, `false` otherwise. public var isFailure: Bool { return !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { case .success(let value): return value case .failure: return nil } } /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { case .success: return nil case .failure(let error): return error } } } // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { case .success: return "SUCCESS" case .failure: return "FAILURE" } } } // MARK: - CustomDebugStringConvertible extension Result: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes whether the result was a /// success or failure in addition to the value or error. public var debugDescription: String { switch self { case .success(let value): return "SUCCESS: \(value)" case .failure(let error): return "FAILURE: \(error)" } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/ServerTrustPolicy.swift ================================================ // // ServerTrustPolicy.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. open class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. open let policies: [String: ServerTrustPolicy] /// Initializes the `ServerTrustPolicyManager` instance with the given policies. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key /// pinning for host3 and disabling evaluation for host4. /// /// - parameter policies: A dictionary of all policies mapped to a particular host. /// /// - returns: The new `ServerTrustPolicyManager` instance. public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /// Returns the `ServerTrustPolicy` for the given host if applicable. /// /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override /// this method and implement more complex mapping implementations such as wildcards. /// /// - parameter host: The host to use when searching for a matching policy. /// /// - returns: The server trust policy for the given host if found. open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension URLSession { private struct AssociatedKeys { static var managerKey = "URLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when /// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust /// with a given set of criteria to determine whether the server trust is valid and the connection should be made. /// /// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other /// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged /// to route all communication over an HTTPS connection with pinning enabled. /// /// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to /// validate the host provided by the challenge. Applications are encouraged to always /// validate the host in production environments to guarantee the validity of the server's /// certificate chain. /// /// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to /// validate the host provided by the challenge as well as specify the revocation flags for /// testing for revoked certificates. Apple platforms did not start testing for revoked /// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is /// demonstrated in our TLS tests. Applications are encouraged to always validate the host /// in production environments to guarantee the validity of the server's certificate chain. /// /// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is /// considered valid if one of the pinned certificates match one of the server certificates. /// By validating both the certificate chain and host, certificate pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered /// valid if one of the pinned public keys match one of the server certificate public keys. /// By validating both the certificate chain and host, public key pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. /// /// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. public enum ServerTrustPolicy { case performDefaultEvaluation(validateHost: Bool) case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case disableEvaluation case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) // MARK: - Bundle Location /// Returns all certificates within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `.cer` files. /// /// - returns: All certificates within the given bundle. public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) }.joined()) for path in paths { if let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, let certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /// Returns all public keys within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `*.cer` files. /// /// - returns: All public keys within the given bundle. public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificates(in: bundle) { if let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /// Evaluates whether the server trust is valid for the given host. /// /// - parameter serverTrust: The server trust to evaluate. /// - parameter host: The host of the challenge protection space. /// /// - returns: Whether the server trust is valid. public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .performDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) serverTrustIsValid = trustIsValid(serverTrust) case let .performRevokedEvaluation(validateHost, revocationFlags): let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) serverTrustIsValid = trustIsValid(serverTrust) case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateData(for: serverTrust) let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData == pinnedCertificateData { serverTrustIsValid = true break outerLoop } } } } case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .disableEvaluation: serverTrustIsValid = true case let .customEvaluation(closure): serverTrustIsValid = closure(serverTrust, host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(_ trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType.unspecified let proceed = SecTrustResultType.proceed isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateData(for trust: SecTrust) -> [Data] { var certificates: [SecCertificate] = [] for index in 0.. [Data] { return certificates.map { SecCertificateCopyData($0) as Data } } // MARK: - Private - Public Key Extraction private static func publicKeys(for trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0.. SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/SessionDelegate.swift ================================================ // // SessionDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for handling all delegate callbacks for the underlying session. open class SessionDelegate: NSObject { // MARK: URLSessionDelegate Overrides /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? // MARK: URLSessionTaskDelegate Overrides /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and /// requires the caller to call the `completionHandler`. open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? // MARK: URLSessionDataDelegate Overrides /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)? // MARK: URLSessionDownloadDelegate Overrides /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: URLSessionStreamDelegate Overrides #if !os(watchOS) /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? #endif // MARK: Properties var retrier: RequestRetrier? weak var sessionManager: SessionManager? private var requests: [Int: Request] = [:] private let lock = NSLock() /// Access the task delegate for the specified task in a thread-safe manner. open subscript(task: URLSessionTask) -> Request? { get { lock.lock() ; defer { lock.unlock() } return requests[task.taskIdentifier] } set { lock.lock() ; defer { lock.unlock() } requests[task.taskIdentifier] = newValue } } // MARK: Lifecycle /// Initializes the `SessionDelegate` instance. /// /// - returns: The new `SessionDelegate` instance. public override init() { super.init() } // MARK: NSObject Overrides /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond /// to a specified message. /// /// - parameter selector: A selector that identifies a message. /// /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. open override func responds(to selector: Selector) -> Bool { #if !os(macOS) if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif #if !os(watchOS) if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { switch selector { case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): return streamTaskReadClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): return streamTaskWriteClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): return streamTaskBetterRouteDiscovered != nil case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): return streamTaskDidBecomeInputAndOutputStreams != nil default: break } } #endif switch selector { case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return type(of: self).instancesRespond(to: selector) } } } // MARK: - URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the delegate that the session has been invalidated. /// /// - parameter session: The session object that was invalidated. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { sessionDidBecomeInvalidWithError?(session, error) } /// Requests credentials from the delegate in response to a session-level authentication request from the /// remote server. /// /// - parameter session: The session containing the task that requested authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } completionHandler(disposition, credential) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// /// - parameter session: The session that no longer has any outstanding requests. open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } #endif } // MARK: - URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// /// - parameter session: The session containing the task whose request resulted in a redirect. /// - parameter task: The task whose request resulted in a redirect. /// - parameter response: An object containing the server’s response to the original request. /// - parameter request: A URL request object filled out with the new location. /// - parameter completionHandler: A closure that your handler should call with either the value of the request /// parameter, a modified URL request object, or NULL to refuse the redirect and /// return the body of the redirect response. open func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// /// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task]?.delegate { delegate.urlSession( session, task: task, didReceive: challenge, completionHandler: completionHandler ) } else { urlSession(session, didReceive: challenge, completionHandler: completionHandler) } } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// /// - parameter session: The session containing the task that needs a new body stream. /// - parameter task: The task that needs a new body stream. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. open func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task]?.delegate { delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) } } /// Periodically informs the delegate of the progress of sending body content to the server. /// /// - parameter session: The session containing the data task. /// - parameter task: The data task. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. /// - parameter totalBytesSent: The total number of bytes sent so far. /// - parameter totalBytesExpectedToSend: The expected length of the body data. open func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } #if !os(watchOS) /// Tells the delegate that the session finished collecting metrics for the task. /// /// - parameter session: The session collecting the metrics. /// - parameter task: The task whose metrics have been collected. /// - parameter metrics: The collected metrics. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) @objc(URLSession:task:didFinishCollectingMetrics:) open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { self[task]?.delegate.metrics = metrics } #endif /// Tells the delegate that the task finished transferring data. /// /// - parameter session: The session containing the task whose request finished transferring data. /// - parameter task: The task whose request finished transferring data. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { /// Executed after it is determined that the request is not going to be retried let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in guard let strongSelf = self else { return } if let taskDidComplete = strongSelf.taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = strongSelf[task]?.delegate { delegate.urlSession(session, task: task, didCompleteWithError: error) } NotificationCenter.default.post( name: Notification.Name.Task.DidComplete, object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } // Run all validations on the request before checking if an error occurred request.validations.forEach { $0() } // Determine whether an error has occurred var error: Error? = error if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { error = taskDelegate.error } /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request /// should be retried. Otherwise, complete the task by notifying the task delegate. if let retrier = retrier, let error = error { retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in guard shouldRetry else { completeTask(session, task, error) ; return } DispatchQueue.utility.after(timeDelay) { [weak self] in guard let strongSelf = self else { return } let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false if retrySucceeded, let task = request.task { strongSelf[task] = request return } else { completeTask(session, task, error) } } } } else { completeTask(session, task, error) } } } // MARK: - URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// /// - parameter session: The session containing the data task that received an initial reply. /// - parameter dataTask: The data task that received an initial reply. /// - parameter response: A URL response object populated with headers. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a /// constant to indicate whether the transfer should continue as a data task or /// should become a download task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: URLSession.ResponseDisposition = .allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /// Tells the delegate that the data task was changed to a download task. /// /// - parameter session: The session containing the task that was replaced by a download task. /// - parameter dataTask: The data task that was replaced by a download task. /// - parameter downloadTask: The new download task that replaced the data task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) } } /// Tells the delegate that the data task has received some of the expected data. /// /// - parameter session: The session containing the data task that provided data. /// - parameter dataTask: The data task that provided data. /// - parameter data: A data object containing the transferred data. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession(session, dataTask: dataTask, didReceive: data) } } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// /// - parameter session: The session containing the data (or upload) task. /// - parameter dataTask: The data (or upload) task. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma /// and Cache-Control headers. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed /// response, a modified version of that response, or NULL to prevent caching the /// response. If your delegate implements this method, it must call this completion /// handler; otherwise, your app leaks memory. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } } // MARK: - URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that finished. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either /// open the file for reading or move it to a permanent location in your app’s sandbox /// container directory before returning from this delegate method. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } } /// Periodically informs the delegate about the download’s progress. /// /// - parameter session: The session containing the download task. /// - parameter downloadTask: The download task. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate /// method was called. /// - parameter totalBytesWritten: The total number of bytes transferred so far. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length /// header. If this header was not provided, the value is /// `NSURLSessionTransferSizeUnknown`. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /// Tells the delegate that the download task has resumed downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the /// existing content, then this value is zero. Otherwise, this value is an /// integer representing the number of bytes on disk that do not need to be /// retrieved again. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } } // MARK: - URLSessionStreamDelegate #if !os(watchOS) @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /// Tells the delegate that the write side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /// Tells the delegate that the system has determined that a better route to the host is available. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. /// - parameter inputStream: The new input stream. /// - parameter outputStream: The new output stream. open func urlSession( _ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) } } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/SessionManager.swift ================================================ // // SessionManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. open class SessionManager { // MARK: - Helper Types /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as /// associated values. /// /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with /// streaming information. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding /// error. public enum MultipartFormDataEncodingResult { case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) case failure(Error) } // MARK: - Properties /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use /// directly for any ad hoc requests. open static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. open static let defaultHTTPHeaders: HTTPHeaders = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` let userAgent: String = { if let info = Bundle.main.infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() let alamofireVersion: String = { guard let afInfo = Bundle(for: SessionManager.self).infoDictionary, let build = afInfo["CFBundleShortVersionString"] else { return "Unknown" } return "Alamofire/\(build)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() /// Default memory threshold used when encoding `MultipartFormData` in bytes. open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 /// The underlying session. open let session: URLSession /// The session delegate handling all the task and session delegate callbacks. open let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. open var startRequestsImmediately: Bool = true /// The request adapter called each time a new request is created. open var adapter: RequestAdapter? /// The request retrier called each time a request encounters an error to determine whether to retry the request. open var retrier: RequestRetrier? { get { return delegate.retrier } set { delegate.retrier = newValue } } /// The background completion handler closure provided by the UIApplicationDelegate /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation /// will automatically call the handler. /// /// If you need to handle your own events before the handler is called, then you need to override the /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. /// /// `nil` by default. open var backgroundCompletionHandler: (() -> Void)? let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) // MARK: - Lifecycle /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter configuration: The configuration used to construct the managed session. /// `URLSessionConfiguration.default` by default. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by /// default. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance. public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter session: The URL session. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionManager = self delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Data Request /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` /// and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult open func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) return request(encodedURLRequest) } catch { return request(originalRequest, failedWith: error) } } /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request. /// /// - returns: The created `DataRequest`. open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try urlRequest.asURLRequest() let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) let task = try originalTask.task(session: session, adapter: adapter, queue: queue) let request = DataRequest(session: session, requestTask: .data(originalTask, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return request(originalRequest, failedWith: error) } } // MARK: Private - Request Implementation private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { var requestTask: Request.RequestTask = .data(nil, nil) if let urlRequest = urlRequest { let originalTask = DataRequest.Requestable(urlRequest: urlRequest) requestTask = .data(originalTask, nil) } let underlyingError = error.underlyingAdaptError ?? error let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: request, with: underlyingError) } else { if startRequestsImmediately { request.resume() } } return request } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, /// `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return download(encodedURLRequest, to: destination) } catch { return download(nil, to: destination, failedWith: error) } } /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save /// them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try urlRequest.asURLRequest() return download(.request(urlRequest), to: destination) } catch { return download(nil, to: destination, failedWith: error) } } // MARK: Resume Data /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve /// the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for /// additional information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return download(.resumeData(resumeData), to: destination) } // MARK: Private - Download Implementation private func download( _ downloadable: DownloadRequest.Downloadable, to destination: DownloadRequest.DownloadFileDestination?) -> DownloadRequest { do { let task = try downloadable.task(session: session, adapter: adapter, queue: queue) let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) download.downloadDelegate.destination = destination delegate[task] = download if startRequestsImmediately { download.resume() } return download } catch { return download(downloadable, to: destination, failedWith: error) } } private func download( _ downloadable: DownloadRequest.Downloadable?, to destination: DownloadRequest.DownloadFileDestination?, failedWith error: Error) -> DownloadRequest { var downloadTask: Request.RequestTask = .download(nil, nil) if let downloadable = downloadable { downloadTask = .download(downloadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) download.downloadDelegate.destination = destination if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: download, with: underlyingError) } else { if startRequestsImmediately { download.resume() } } return download } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(fileURL, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.file(fileURL, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: Data /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(data, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.data(data, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: InputStream /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(stream, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.stream(stream, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } catch { DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { DispatchQueue.global(qos: .utility).async { let formData = MultipartFormData() multipartFormData(formData) var tempFileURL: URL? do { var urlRequestWithContentType = try urlRequest.asURLRequest() urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(data, with: urlRequestWithContentType), streamingFromDisk: false, streamFileURL: nil ) DispatchQueue.main.async { encodingCompletion?(encodingResult) } } else { let fileManager = FileManager.default let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) tempFileURL = fileURL var directoryError: Error? // Create directory inside serial queue to ensure two threads don't do this in parallel self.queue.sync { do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { directoryError = error } } if let directoryError = directoryError { throw directoryError } try formData.writeEncodedData(to: fileURL) let upload = self.upload(fileURL, with: urlRequestWithContentType) // Cleanup the temp file once the upload is complete upload.delegate.queue.addOperation { do { try FileManager.default.removeItem(at: fileURL) } catch { // No-op } } DispatchQueue.main.async { let encodingResult = MultipartFormDataEncodingResult.success( request: upload, streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } } catch { // Cleanup the temp file in the event that the multipart form data encoding failed if let tempFileURL = tempFileURL { do { try FileManager.default.removeItem(at: tempFileURL) } catch { // No-op } } DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } } // MARK: Private - Upload Implementation private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { do { let task = try uploadable.task(session: session, adapter: adapter, queue: queue) let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) if case let .stream(inputStream, _) = uploadable { upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } } delegate[task] = upload if startRequestsImmediately { upload.resume() } return upload } catch { return upload(uploadable, failedWith: error) } } private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { var uploadTask: Request.RequestTask = .upload(nil, nil) if let uploadable = uploadable { uploadTask = .upload(uploadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: upload, with: underlyingError) } else { if startRequestsImmediately { upload.resume() } } return upload } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(withHostName hostName: String, port: Int) -> StreamRequest { return stream(.stream(hostName: hostName, port: port)) } // MARK: NetService /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(with netService: NetService) -> StreamRequest { return stream(.netService(netService)) } // MARK: Private - Stream Implementation @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { do { let task = try streamable.task(session: session, adapter: adapter, queue: queue) let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return stream(failedWith: error) } } @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(failedWith error: Error) -> StreamRequest { let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) if startRequestsImmediately { stream.resume() } return stream } #endif // MARK: - Internal - Retry Request func retry(_ request: Request) -> Bool { guard let originalTask = request.originalTask else { return false } do { let task = try originalTask.task(session: session, adapter: adapter, queue: queue) request.delegate.task = task // resets all task delegate data request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { DispatchQueue.utility.async { [weak self] in guard let strongSelf = self else { return } retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in guard let strongSelf = self else { return } guard shouldRetry else { if strongSelf.startRequestsImmediately { request.resume() } return } DispatchQueue.utility.after(timeDelay) { guard let strongSelf = self else { return } let retrySucceeded = strongSelf.retry(request) if retrySucceeded, let task = request.task { strongSelf.delegate[task] = request } else { if strongSelf.startRequestsImmediately { request.resume() } } } } } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/TaskDelegate.swift ================================================ // // TaskDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as /// executing all operations attached to the serial operation queue upon task completion. open class TaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. open let queue: OperationQueue /// The data returned by the server. public var data: Data? { return nil } /// The error generated throughout the lifecyle of the task. public var error: Error? var task: URLSessionTask? { didSet { reset() } } var initialResponseTime: CFAbsoluteTime? var credential: URLCredential? var metrics: AnyObject? // URLSessionTaskMetrics // MARK: Lifecycle init(task: URLSessionTask?) { self.task = task self.queue = { let operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true operationQueue.qualityOfService = .utility return operationQueue }() } func reset() { error = nil initialResponseTime = nil } // MARK: URLSessionTaskDelegate var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } @objc(URLSession:task:didReceiveChallenge:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } else { if challenge.previousFailureCount > 0 { disposition = .rejectProtectionSpace } else { credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) if credential != nil { disposition = .useCredential } } } completionHandler(disposition, credential) } @objc(URLSession:task:needNewBodyStream:) func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { var bodyStream: InputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } @objc(URLSession:task:didCompleteWithError:) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { if self.error == nil { self.error = error } if let downloadDelegate = self as? DownloadTaskDelegate, let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data { downloadDelegate.resumeData = resumeData } } queue.isSuspended = false } } } // MARK: - class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { // MARK: Properties var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } override var data: Data? { if dataStream != nil { return nil } else { return mutableData } } var progress: Progress var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? var dataStream: ((_ data: Data) -> Void)? private var totalBytesReceived: Int64 = 0 private var mutableData: Data private var expectedContentLength: Int64? // MARK: Lifecycle override init(task: URLSessionTask?) { mutableData = Data() progress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() progress = Progress(totalUnitCount: 0) totalBytesReceived = 0 mutableData = Data() expectedContentLength = nil } // MARK: URLSessionDataDelegate var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { var disposition: URLSession.ResponseDisposition = .allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data) } else { mutableData.append(data) } let bytesReceived = Int64(data.count) totalBytesReceived += bytesReceived let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived if let progressHandler = progressHandler { progressHandler.queue.async { progressHandler.closure(self.progress) } } } } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { var cachedResponse: CachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } // MARK: - class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { // MARK: Properties var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } var progress: Progress var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? var resumeData: Data? override var data: Data? { return resumeData } var destination: DownloadRequest.DownloadFileDestination? var temporaryURL: URL? var destinationURL: URL? var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } // MARK: Lifecycle override init(task: URLSessionTask?) { progress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() progress = Progress(totalUnitCount: 0) resumeData = nil } // MARK: URLSessionDownloadDelegate var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { temporaryURL = location guard let destination = destination, let response = downloadTask.response as? HTTPURLResponse else { return } let result = destination(location, response) let destinationURL = result.destinationURL let options = result.options self.destinationURL = destinationURL do { if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.removeItem(at: destinationURL) } if options.contains(.createIntermediateDirectories) { let directory = destinationURL.deletingLastPathComponent() try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } try FileManager.default.moveItem(at: location, to: destinationURL) } catch { self.error = error } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite ) } else { progress.totalUnitCount = totalBytesExpectedToWrite progress.completedUnitCount = totalBytesWritten if let progressHandler = progressHandler { progressHandler.queue.async { progressHandler.closure(self.progress) } } } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else { progress.totalUnitCount = expectedTotalBytes progress.completedUnitCount = fileOffset } } } // MARK: - class UploadTaskDelegate: DataTaskDelegate { // MARK: Properties var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } var uploadProgress: Progress var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? // MARK: Lifecycle override init(task: URLSessionTask?) { uploadProgress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() uploadProgress = Progress(totalUnitCount: 0) } // MARK: URLSessionTaskDelegate var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? func URLSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { uploadProgress.totalUnitCount = totalBytesExpectedToSend uploadProgress.completedUnitCount = totalBytesSent if let uploadProgressHandler = uploadProgressHandler { uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } } } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Timeline.swift ================================================ // // Timeline.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: TimeInterval /// Creates a new `Timeline` instance with the specified request times. /// /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. /// Defaults to `0.0`. /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults /// to `0.0`. /// /// - returns: The new `Timeline` instance. public init( requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime self.latency = initialResponseTime - requestStartTime self.requestDuration = requestCompletedTime - requestStartTime self.serializationDuration = serializationCompletedTime - requestCompletedTime self.totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Alamofire/Source/Validation.swift ================================================ // // Validation.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Request { // MARK: Helper Types fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason /// Used to represent whether validation was successful or encountered an error resulting in a failure. /// /// - success: The validation was successful. /// - failure: The validation failed encountering the provided error. public enum ValidationResult { case success case failure(Error) } fileprivate struct MIMEType { let type: String let subtype: String var isWildcard: Bool { return type == "*" && subtype == "*" } init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) return split.components(separatedBy: "/") }() if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false } } } // MARK: Properties fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { return accept.components(separatedBy: ",") } return ["*/*"] } // MARK: Status Code fileprivate func validate( statusCode acceptableStatusCodes: S, response: HTTPURLResponse) -> ValidationResult where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { return .success } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(AFError.responseValidationFailed(reason: reason)) } } // MARK: Content Type fileprivate func validate( contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, data.count > 0 else { return .success } guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .success } } let error: AFError = { let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { return .success } } let error: AFError = { let reason: ErrorReason = .unacceptableContentType( acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType ) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } } // MARK: - extension DataRequest { /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the /// request was valid. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(self.request, response, self.delegate.data) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in return self.validate(contentType: acceptableContentTypes, response: response, data: data) } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } // MARK: - extension DownloadRequest { /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a /// destination URL, and returns whether the request was valid. public typealias Validation = ( _ request: URLRequest?, _ response: HTTPURLResponse, _ temporaryURL: URL?, _ destinationURL: URL?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in let request = self.request let temporaryURL = self.downloadDelegate.temporaryURL let destinationURL = self.downloadDelegate.destinationURL if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(request, response, temporaryURL, destinationURL) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, _, _ in let fileURL = self.downloadDelegate.fileURL guard let validFileURL = fileURL else { return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) } do { let data = try Data(contentsOf: validFileURL) return self.validate(contentType: acceptableContentTypes, response: response, data: data) } catch { return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) } } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/AlamofireSwiftyJSON/LICENSE ================================================ Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/Manager/EZShopManager/Pods/AlamofireSwiftyJSON/README.md ================================================ #AlamofireSwiftyJSON [![Build Status](https://travis-ci.org/starboychina/AlamofireSwiftyJSON.svg)](https://travis-ci.org/starboychina/AlamofireSwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![SwiftLint](https://img.shields.io/badge/SwiftLint-passing-brightgreen.svg)](https://github.com/realm/SwiftLint) [![codecov.io](https://codecov.io/github/starboychina/AlamofireSwiftyJSON/coverage.svg?branch=master)](https://codecov.io/gh/starboychina/AlamofireSwiftyJSON?branch=master) [![GitHub release](https://img.shields.io/github/release/starboychina/AlamofireSwiftyJSON.svg)](https://github.com/starboychina/AlamofireSwiftyJSON/releases) --- Easy way to use both [Alamofire](https://github.com/Alamofire/Alamofire) and [SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON) ## Requirements - iOS 8.0+ / Mac OS X 10.9+ - Xcode 7.0 ## Install - CocoaPods ```swift source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! target "target name" do pod 'AlamofireSwiftyJSON' end ``` - [Carthage](https://github.com/Carthage/Carthage) ```swift github "starboychina/AlamofireSwiftyJSON" ``` ## Usage ```swift let URL = "http://httpbin.org/get" Alamofire.request(.GET, URL, parameters: ["foo": "bar"]).responseSwiftyJSON { response in print("###Success: \(response.result.isSuccess)") //now response.result.value is SwiftyJSON.JSON type print("###Value: \(response.result.value?["args"].array)") } ``` ================================================ FILE: iOS/Manager/EZShopManager/Pods/AlamofireSwiftyJSON/Source/AlamofireSwiftyJSON.swift ================================================ // // AlamofireSwiftyJSON.swift // AlamofireSwiftyJSON // // Created by Hikaru on 2016/01/29. // Copyright © 2016年 Hikaru. All rights reserved. // import Alamofire import SwiftyJSON /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set = [204, 205] // MARK: - Request for SwiftyJSON extension DataRequest { /// Creates a response serializer that /// returns a SwiftyJSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func serializeResponseSwiftyJSON( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseSwiftyJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: /// The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseSwiftyJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.serializeResponseSwiftyJSON(options: options), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed /// from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseSwiftyJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(JSON.null) } guard let validData = data, !validData.isEmpty else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(JSON(json)) } catch { return .failure(AFError.responseSerializationFailed( reason: .jsonSerializationFailed(error: error))) } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Firebase/Core/Sources/Firebase.h ================================================ #import #import #if !defined(__has_include) #error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \ import the headers individually." #else #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #endif // defined(__has_include) ================================================ FILE: iOS/Manager/EZShopManager/Pods/Firebase/Core/Sources/module.modulemap ================================================ module Firebase { export * header "Firebase.h" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Firebase/README.md ================================================ # Firebase APIs for iOS Simplify your iOS development, grow your user base, and monetize more effectively with Firebase services. Much more information can be found at [https://firebase.google.com](https://firebase.google.com). ## Install a Firebase SDK using CocoaPods Firebase distributes several iOS specific APIs and SDKs via CocoaPods. You can install the CocoaPods tool on OS X by running the following command from the terminal. Detailed information is available in the [Getting Started guide](https://guides.cocoapods.org/using/getting-started.html#getting-started). ``` $ sudo gem install cocoapods ``` ## Try out an SDK You can try any of the SDKs with `pod try`. Run the following command and select the SDK you are interested in when prompted: ``` $ pod try Firebase ``` Note that some SDKs may require credentials. More information is available in the SDK-specific documentation at [https://firebase.google.com/docs/](https://firebase.google.com/docs/). ## Add a Firebase SDK to your iOS app CocoaPods is used to install and manage dependencies in existing Xcode projects. 1. Create an Xcode project, and save it to your local machine. 2. Create a file named `Podfile` in your project directory. This file defines your project's dependencies, and is commonly referred to as a Podspec. 3. Open `Podfile`, and add your dependencies. A simple Podspec is shown here: ``` platform :ios, '7.0' pod 'Firebase' ``` 4. Save the file. 5. Open a terminal and `cd` to the directory containing the Podfile. ``` $ cd /project/ ``` 6. Run the `pod install` command. This will install the SDKs specified in the Podspec, along with any dependencies they may have. ``` $ pod install ``` 7. Open your app's `.xcworkspace` file to launch Xcode. Use this file for all development on your app. 8. You can also install other Firebase SDKs by adding the subspecs in the Podfile. ``` pod 'Firebase/AdMob' pod 'Firebase/Analytics' pod 'Firebase/AppIndexing' pod 'Firebase/Auth' pod 'Firebase/Crash' pod 'Firebase/Database' pod 'Firebase/DynamicLinks' pod 'Firebase/Invites' pod 'Firebase/Messaging' pod 'Firebase/RemoteConfig' pod 'Firebase/Storage' ``` ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics ================================================ [File too large to display: 14.3 MB] ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h ================================================ #import #import "FIRAnalytics.h" /** * Provides App Delegate handlers to be used in your App Delegate. * * To save time integrating Firebase Analytics in an application, Firebase Analytics does not * require delegation implementation from the AppDelegate. Instead this is automatically done by * Firebase Analytics. Should you choose instead to delegate manually, you can turn off the App * Delegate Proxy by adding FirebaseAppDelegateProxyEnabled into your app's Info.plist and setting * it to NO, and adding the methods in this category to corresponding delegation handlers. * * To handle Universal Links, you must return YES in * [UIApplicationDelegate application:didFinishLaunchingWithOptions:]. */ @interface FIRAnalytics (AppDelegate) /** * Handles events related to a URL session that are waiting to be processed. * * For optimal use of Firebase Analytics, call this method from the * [UIApplicationDelegate application:handleEventsForBackgroundURLSession:completionHandler] * method of the app delegate in your app. * * @param identifier The identifier of the URL session requiring attention. * @param completionHandler The completion handler to call when you finish processing the events. * Calling this completion handler lets the system know that your app's user interface is * updated and a new snapshot can be taken. */ + (void)handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler; /** * Handles the event when the app is launched by a URL. * * Call this method from [UIApplicationDelegate application:openURL:options:] (on iOS 9.0 and * above), or [UIApplicationDelegate application:openURL:sourceApplication:annotation:] (on iOS 8.x * and below) in your app. * * @param url The URL resource to open. This resource can be a network resource or a file. */ + (void)handleOpenURL:(NSURL *)url; /** * Handles the event when the app receives data associated with user activity that includes a * Universal Link (on iOS 9.0 and above). * * Call this method from [UIApplication continueUserActivity:restorationHandler:] in your app * delegate (on iOS 9.0 and above). * * @param userActivity The activity object containing the data associated with the task the user * was performing. */ + (void)handleUserActivity:(id)userActivity; @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h ================================================ #import #import "FIREventNames.h" #import "FIRParameterNames.h" #import "FIRUserPropertyNames.h" NS_ASSUME_NONNULL_BEGIN /// The top level Firebase Analytics singleton that provides methods for logging events and setting /// user properties. See the developer guides for general /// information on using Firebase Analytics in your apps. @interface FIRAnalytics : NSObject /// Logs an app event. The event can have up to 25 parameters. Events with the same name must have /// the same parameters. Up to 500 event names are supported. Using predefined events and/or /// parameters is recommended for optimal reporting. /// /// The following event names are reserved and cannot be used: ///
    ///
  • app_clear_data
  • ///
  • app_remove
  • ///
  • app_update
  • ///
  • error
  • ///
  • first_open
  • ///
  • in_app_purchase
  • ///
  • notification_dismiss
  • ///
  • notification_foreground
  • ///
  • notification_open
  • ///
  • notification_receive
  • ///
  • os_update
  • ///
  • session_start
  • ///
  • user_engagement
  • ///
/// /// @param name The name of the event. Should contain 1 to 40 alphanumeric characters or /// underscores. The name must start with an alphabetic character. Some event names are /// reserved. See FIREventNames.h for the list of reserved event names. The "firebase_" prefix /// is reserved and should not be used. Note that event names are case-sensitive and that /// logging two events whose names differ only in case will result in two distinct events. /// @param parameters The dictionary of event parameters. Passing nil indicates that the event has /// no parameters. Parameter names can be up to 40 characters long and must start with an /// alphabetic character and contain only alphanumeric characters and underscores. Only NSString /// and NSNumber (signed 64-bit integer and 64-bit floating-point number) parameter types are /// supported. NSString parameter values can be up to 100 characters long. The "firebase_" /// prefix is reserved and should not be used for parameter names. + (void)logEventWithName:(NSString *)name parameters:(nullable NSDictionary *)parameters; /// Sets a user property to a given value. Up to 25 user property names are supported. Once set, /// user property values persist throughout the app lifecycle and across sessions. /// /// The following user property names are reserved and cannot be used: ///
    ///
  • first_open_time
  • ///
  • last_deep_link_referrer
  • ///
  • user_id
  • ///
/// /// @param value The value of the user property. Values can be up to 36 characters long. Setting the /// value to nil removes the user property. /// @param name The name of the user property to set. Should contain 1 to 24 alphanumeric characters /// or underscores and must start with an alphabetic character. The "firebase_" prefix is /// reserved and should not be used for user property names. + (void)setUserPropertyString:(nullable NSString *)value forName:(NSString *)name; /// Sets the user ID property. This feature must be used in accordance with /// Google's Privacy Policy /// /// @param userID The user ID to ascribe to the user of this app on this device, which must be /// non-empty and no more than 36 characters long. Setting userID to nil removes the user ID. + (void)setUserID:(nullable NSString *)userID; /// Sets the current screen name, which specifies the current visual context in your app. This helps /// identify the areas in your app where users spend their time and how they interact with your app. /// /// Note that screen reporting is enabled automatically and records the class name of the current /// UIViewController for you without requiring you to call this method. If you implement /// viewDidAppear in your UIViewController but do not call [super viewDidAppear:], that screen class /// will not be automatically tracked. The class name can optionally be overridden by calling this /// method in the viewDidAppear callback of your UIViewController and specifying the /// screenClassOverride parameter. /// /// If your app does not use a distinct UIViewController for each screen, you should call this /// method and specify a distinct screenName each time a new screen is presented to the user. /// /// The screen name and screen class remain in effect until the current UIViewController changes or /// a new call to setScreenName:screenClass: is made. /// /// @param screenName The name of the current screen. Should contain 1 to 100 characters. Set to nil /// to clear the current screen name. /// @param screenClassOverride The name of the screen class. Should contain 1 to 100 characters. By /// default this is the class name of the current UIViewController. Set to nil to revert to the /// default class name. + (void)setScreenName:(nullable NSString *)screenName screenClass:(nullable NSString *)screenClassOverride; /// The unique ID for this instance of the application. + (NSString *)appInstanceID; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalyticsConfiguration.h ================================================ #import ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRApp.h ================================================ #import ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRConfiguration.h ================================================ #import ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h ================================================ /// @file FIREventNames.h /// /// Predefined event names. /// /// An Event is an important occurrence in your app that you want to measure. You can report up to /// 500 different types of Events per app and you can associate up to 25 unique parameters with each /// Event type. Some common events are suggested below, but you may also choose to specify custom /// Event types that are associated with your specific app. Each event type is identified by a /// unique name. Event names can be up to 40 characters long, may only contain alphanumeric /// characters and underscores ("_"), and must start with an alphabetic character. The "firebase_" /// prefix is reserved and should not be used. /// Add Payment Info event. This event signifies that a user has submitted their payment information /// to your app. static NSString *const kFIREventAddPaymentInfo = @"add_payment_info"; /// E-Commerce Add To Cart event. This event signifies that an item was added to a cart for /// purchase. Add this event to a funnel with kFIREventEcommercePurchase to gauge the effectiveness /// of your checkout process. Note: If you supply the @c kFIRParameterValue parameter, you must /// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
static NSString *const kFIREventAddToCart = @"add_to_cart"; /// E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. /// Use this event to identify popular gift items in your app. Note: If you supply the /// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency /// parameter so that revenue metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventAddToWishlist = @"add_to_wishlist"; /// App Open event. By logging this event when an App is moved to the foreground, developers can /// understand how often users leave and return during the course of a Session. Although Sessions /// are automatically reported, this event can provide further clarification around the continuous /// engagement of app-users. static NSString *const kFIREventAppOpen = @"app_open"; /// E-Commerce Begin Checkout event. This event signifies that a user has begun the process of /// checking out. Add this event to a funnel with your kFIREventEcommercePurchase event to gauge the /// effectiveness of your checkout process. Note: If you supply the @c kFIRParameterValue /// parameter, you must also supply the @c kFIRParameterCurrency parameter so that revenue /// metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventBeginCheckout = @"begin_checkout"; /// Campaign Detail event. Log this event to supply the referral details of a re-engagement /// campaign. Note: you must supply at least one of the required parameters kFIRParameterSource, /// kFIRParameterMedium or kFIRParameterCampaign. Params: /// ///
    ///
  • @c kFIRParameterSource (NSString)
  • ///
  • @c kFIRParameterMedium (NSString)
  • ///
  • @c kFIRParameterCampaign (NSString)
  • ///
  • @c kFIRParameterTerm (NSString) (optional)
  • ///
  • @c kFIRParameterContent (NSString) (optional)
  • ///
  • @c kFIRParameterAdNetworkClickID (NSString) (optional)
  • ///
  • @c kFIRParameterCP1 (NSString) (optional)
  • ///
static NSString *const kFIREventCampaignDetails = @"campaign_details"; /// Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log /// this along with @c kFIREventSpendVirtualCurrency to better understand your virtual economy. /// Params: /// ///
    ///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • ///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • ///
static NSString *const kFIREventEarnVirtualCurrency = @"earn_virtual_currency"; /// E-Commerce Purchase event. This event signifies that an item was purchased by a user. Note: /// This is different from the in-app purchase event, which is reported automatically for App /// Store-based apps. Note: If you supply the @c kFIRParameterValue parameter, you must also /// supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
  • @c kFIRParameterTax (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterShipping (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCoupon (NSString) (optional)
  • ///
  • @c kFIRParameterLocation (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventEcommercePurchase = @"ecommerce_purchase"; /// Generate Lead event. Log this event when a lead has been generated in the app to understand the /// efficacy of your install and re-engagement campaigns. Note: If you supply the /// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency /// parameter so that revenue metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventGenerateLead = @"generate_lead"; /// Join Group event. Log this event when a user joins a group such as a guild, team or family. Use /// this event to analyze how popular certain groups or social features are in your app. Params: /// ///
    ///
  • @c kFIRParameterGroupID (NSString)
  • ///
static NSString *const kFIREventJoinGroup = @"join_group"; /// Level Up event. This event signifies that a player has leveled up in your gaming app. It can /// help you gauge the level distribution of your userbase and help you identify certain levels that /// are difficult to pass. Params: /// ///
    ///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterCharacter (NSString) (optional)
  • ///
static NSString *const kFIREventLevelUp = @"level_up"; /// Login event. Apps with a login feature can report this event to signify that a user has logged /// in. static NSString *const kFIREventLogin = @"login"; /// Post Score event. Log this event when the user posts a score in your gaming app. This event can /// help you understand how users are actually performing in your game and it can help you correlate /// high scores with certain audiences or behaviors. Params: /// ///
    ///
  • @c kFIRParameterScore (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber) (optional)
  • ///
  • @c kFIRParameterCharacter (NSString) (optional)
  • ///
static NSString *const kFIREventPostScore = @"post_score"; /// Present Offer event. This event signifies that the app has presented a purchase offer to a user. /// Add this event to a funnel with the kFIREventAddToCart and kFIREventEcommercePurchase to gauge /// your conversion process. Note: If you supply the @c kFIRParameterValue parameter, you must /// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventPresentOffer = @"present_offer"; /// E-Commerce Purchase Refund event. This event signifies that an item purchase was refunded. /// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the /// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. /// Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
static NSString *const kFIREventPurchaseRefund = @"purchase_refund"; /// Search event. Apps that support search features can use this event to contextualize search /// operations by supplying the appropriate, corresponding parameters. This event can help you /// identify the most popular content in your app. Params: /// ///
    ///
  • @c kFIRParameterSearchTerm (NSString)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventSearch = @"search"; /// Select Content event. This general purpose event signifies that a user has selected some content /// of a certain type in an app. The content can be any object in your app. This event can help you /// identify popular content and categories of content in your app. Params: /// ///
    ///
  • @c kFIRParameterContentType (NSString)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
static NSString *const kFIREventSelectContent = @"select_content"; /// Share event. Apps with social features can log the Share event to identify the most viral /// content. Params: /// ///
    ///
  • @c kFIRParameterContentType (NSString)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
static NSString *const kFIREventShare = @"share"; /// Sign Up event. This event indicates that a user has signed up for an account in your app. The /// parameter signifies the method by which the user signed up. Use this event to understand the /// different behaviors between logged in and logged out users. Params: /// ///
    ///
  • @c kFIRParameterSignUpMethod (NSString)
  • ///
static NSString *const kFIREventSignUp = @"sign_up"; /// Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can /// help you identify which virtual goods are the most popular objects of purchase. Params: /// ///
    ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • ///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • ///
static NSString *const kFIREventSpendVirtualCurrency = @"spend_virtual_currency"; /// Tutorial Begin event. This event signifies the start of the on-boarding process in your app. Use /// this in a funnel with kFIREventTutorialComplete to understand how many users complete this /// process and move on to the full app experience. static NSString *const kFIREventTutorialBegin = @"tutorial_begin"; /// Tutorial End event. Use this event to signify the user's completion of your app's on-boarding /// process. Add this to a funnel with kFIREventTutorialBegin to gauge the completion rate of your /// on-boarding process. static NSString *const kFIREventTutorialComplete = @"tutorial_complete"; /// Unlock Achievement event. Log this event when the user has unlocked an achievement in your /// game. Since achievements generally represent the breadth of a gaming experience, this event can /// help you understand how many users are experiencing all that your game has to offer. Params: /// ///
    ///
  • @c kFIRParameterAchievementID (NSString)
  • ///
static NSString *const kFIREventUnlockAchievement = @"unlock_achievement"; /// View Item event. This event signifies that some content was shown to the user. This content may /// be a product, a webpage or just a simple image or text. Use the appropriate parameters to /// contextualize the event. Use this event to discover the most popular items viewed in your app. /// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the /// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. /// Params: /// ///
    ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterFlightNumber (NSString) (optional) for travel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// travel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterSearchTerm (NSString) (optional) for travel bookings
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventViewItem = @"view_item"; /// View Item List event. Log this event when the user has been presented with a list of items of a /// certain category. Params: /// ///
    ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
static NSString *const kFIREventViewItemList = @"view_item_list"; /// View Search Results event. Log this event when the user has been presented with the results of a /// search. Params: /// ///
    ///
  • @c kFIRParameterSearchTerm (NSString)
  • ///
static NSString *const kFIREventViewSearchResults = @"view_search_results"; ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIROptions.h ================================================ #import ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h ================================================ /// @file FIRParameterNames.h /// /// Predefined event parameter names. /// /// Params supply information that contextualize Events. You can associate up to 25 unique Params /// with each Event type. Some Params are suggested below for certain common Events, but you are /// not limited to these. You may supply extra Params for suggested Events or custom Params for /// Custom events. Param names can be up to 40 characters long, may only contain alphanumeric /// characters and underscores ("_"), and must start with an alphabetic character. Param values can /// be up to 100 characters long. The "firebase_" prefix is reserved and should not be used. /// Game achievement ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterAchievementID : @"10_matches_won",
///       // ...
///     };
/// 
static NSString *const kFIRParameterAchievementID = @"achievement_id"; /// Ad Network Click ID (NSString). Used for network-specific click IDs which vary in format. ///
///     NSDictionary *params = @{
///       kFIRParameterAdNetworkClickID : @"1234567",
///       // ...
///     };
/// 
static NSString *const kFIRParameterAdNetworkClickID = @"aclid"; /// The individual campaign name, slogan, promo code, etc. Some networks have pre-defined macro to /// capture campaign information, otherwise can be populated by developer. Highly Recommended /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCampaign : @"winter_promotion",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCampaign = @"campaign"; /// Character used in game (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCharacter : @"beat_boss",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCharacter = @"character"; /// Campaign content (NSString). static NSString *const kFIRParameterContent = @"content"; /// Type of content selected (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterContentType : @"news article",
///       // ...
///     };
/// 
static NSString *const kFIRParameterContentType = @"content_type"; /// Coupon code for a purchasable item (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCoupon : @"zz123",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCoupon = @"coupon"; /// Campaign custom parameter (NSString). Used as a method of capturing custom data in a campaign. /// Use varies by network. ///
///     NSDictionary *params = @{
///       kFIRParameterCP1 : @"custom_data",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCP1 = @"cp1"; /// Purchase currency in 3-letter /// ISO_4217 format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCurrency : @"USD",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCurrency = @"currency"; /// Flight or Travel destination (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterDestination : @"Mountain View, CA",
///       // ...
///     };
/// 
static NSString *const kFIRParameterDestination = @"destination"; /// The arrival date, check-out date or rental end date for the item. This should be in /// YYYY-MM-DD format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterEndDate : @"2015-09-14",
///       // ...
///     };
/// 
static NSString *const kFIRParameterEndDate = @"end_date"; /// Flight number for travel events (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterFlightNumber : @"ZZ800",
///       // ...
///     };
/// 
static NSString *const kFIRParameterFlightNumber = @"flight_number"; /// Group/clan/guild ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterGroupID : @"g1",
///       // ...
///     };
/// 
static NSString *const kFIRParameterGroupID = @"group_id"; /// Item category (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemCategory : @"t-shirts",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemCategory = @"item_category"; /// Item ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemID : @"p7654",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemID = @"item_id"; /// The Google Place ID (NSString) that /// corresponds to the associated item. Alternatively, you can supply your own custom Location ID. ///
///     NSDictionary *params = @{
///       kFIRParameterItemLocationID : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemLocationID = @"item_location_id"; /// Item name (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemName : @"abc",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemName = @"item_name"; /// Level in game (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterLevel : @(42),
///       // ...
///     };
/// 
static NSString *const kFIRParameterLevel = @"level"; /// Location (NSString). The Google Place ID /// that corresponds to the associated event. Alternatively, you can supply your own custom /// Location ID. ///
///     NSDictionary *params = @{
///       kFIRParameterLocation : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
///       // ...
///     };
/// 
static NSString *const kFIRParameterLocation = @"location"; /// The advertising or marketing medium, for example: cpc, banner, email, push. Highly recommended /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterMedium : @"email",
///       // ...
///     };
/// 
static NSString *const kFIRParameterMedium = @"medium"; /// Number of nights staying at hotel (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfNights : @(3),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfNights = @"number_of_nights"; /// Number of passengers traveling (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfPassengers : @(11),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfPassengers = @"number_of_passengers"; /// Number of rooms for travel events (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfRooms : @(2),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfRooms = @"number_of_rooms"; /// Flight or Travel origin (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterOrigin : @"Mountain View, CA",
///       // ...
///     };
/// 
static NSString *const kFIRParameterOrigin = @"origin"; /// Purchase price (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterPrice : @(1.0),
///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterPrice = @"price"; /// Purchase quantity (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterQuantity : @(1),
///       // ...
///     };
/// 
static NSString *const kFIRParameterQuantity = @"quantity"; /// Score in game (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterScore : @(4200),
///       // ...
///     };
/// 
static NSString *const kFIRParameterScore = @"score"; /// The search string/keywords used (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSearchTerm : @"periodic table",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSearchTerm = @"search_term"; /// Shipping cost (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterShipping : @(9.50),
///       kFIRParameterCurrency : @"USD",  // e.g. $9.50 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterShipping = @"shipping"; /// Sign up method (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSignUpMethod : @"google",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSignUpMethod = @"sign_up_method"; /// The origin of your traffic, such as an Ad network (for example, google) or partner (urban /// airship). Identify the advertiser, site, publication, etc. that is sending traffic to your /// property. Highly recommended (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSource : @"InMobi",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSource = @"source"; /// The departure date, check-in date or rental start date for the item. This should be in /// YYYY-MM-DD format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterStartDate : @"2015-09-14",
///       // ...
///     };
/// 
static NSString *const kFIRParameterStartDate = @"start_date"; /// Tax amount (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterTax : @(1.0),
///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterTax = @"tax"; /// If you're manually tagging keyword campaigns, you should use utm_term to specify the keyword /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTerm : @"game",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTerm = @"term"; /// A single ID for a ecommerce group transaction (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTransactionID : @"ab7236dd9823",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTransactionID = @"transaction_id"; /// Travel class (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTravelClass : @"business",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTravelClass = @"travel_class"; /// A context-specific numeric value which is accumulated automatically for each event type. This is /// a general purpose parameter that is useful for accumulating a key metric that pertains to an /// event. Examples include revenue, distance, time and points. Value should be specified as signed /// 64-bit integer or double as NSNumber. Notes: Values for pre-defined currency-related events /// (such as @c kFIREventAddToCart) should be supplied using double as NSNumber and must be /// accompanied by a @c kFIRParameterCurrency parameter. The valid range of accumulated values is /// [-9,223,372,036,854.77, 9,223,372,036,854.77]. ///
///     NSDictionary *params = @{
///       kFIRParameterValue : @(3.99),
///       kFIRParameterCurrency : @"USD",  // e.g. $3.99 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterValue = @"value"; /// Name of virtual currency type (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterVirtualCurrencyName : @"virtual_currency_name",
///       // ...
///     };
/// 
static NSString *const kFIRParameterVirtualCurrencyName = @"virtual_currency_name"; ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h ================================================ /// @file FIRUserPropertyNames.h /// /// Predefined user property names. /// /// A UserProperty is an attribute that describes the app-user. By supplying UserProperties, you can /// later analyze different behaviors of various segments of your userbase. You may supply up to 25 /// unique UserProperties per app, and you can use the name and value of your choosing for each one. /// UserProperty names can be up to 24 characters long, may only contain alphanumeric characters and /// underscores ("_"), and must start with an alphabetic character. UserProperty values can be up to /// 36 characters long. The "firebase_" prefix is reserved and should not be used. /// The method used to sign in. For example, "google", "facebook" or "twitter". static NSString *const kFIRUserPropertySignUpMethod = @"sign_up_method"; ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h ================================================ #import "FIRAnalyticsConfiguration.h" #import "FIRApp.h" #import "FIRConfiguration.h" #import "FIROptions.h" #import "FIRAnalytics+AppDelegate.h" #import "FIRAnalytics.h" #import "FIREventNames.h" #import "FIRParameterNames.h" #import "FIRUserPropertyNames.h" ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap ================================================ framework module FirebaseAnalytics { umbrella header "FirebaseAnalytics.h" export * module * { export *} link "sqlite3" link "z" link framework "CoreGraphics" link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRAnalyticsConfiguration.h ================================================ #import /** * This class provides configuration fields for Firebase Analytics. */ @interface FIRAnalyticsConfiguration : NSObject /** * Returns the shared instance of FIRAnalyticsConfiguration. */ + (FIRAnalyticsConfiguration *)sharedInstance; /** * Sets the minimum engagement time in seconds required to start a new session. The default value * is 10 seconds. */ - (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval; /** * Sets the interval of inactivity in seconds that terminates the current session. The default * value is 1800 seconds (30 minutes). */ - (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval; /** * Sets whether analytics collection is enabled for this app on this device. This setting is * persisted across app sessions. By default it is enabled. */ - (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled; /** * Deprecated. Sets whether measurement and reporting are enabled for this app on this device. By * default they are enabled. */ - (void)setIsEnabled:(BOOL)isEnabled DEPRECATED_MSG_ATTRIBUTE("Use setAnalyticsCollectionEnabled: instead."); @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRApp.h ================================================ #import #import @class FIROptions; NS_ASSUME_NONNULL_BEGIN /** A block that takes a BOOL and has no return value. */ typedef void (^FIRAppVoidBoolCallback)(BOOL success); /** * The entry point of Firebase SDKs. * * Initialize and configure FIRApp using +[FIRApp configure] * or other customized ways as shown below. * * The logging system has two modes: default mode and debug mode. In default mode, only logs with * log level Notice, Warning and Error will be sent to device. In debug mode, all logs will be sent * to device. The log levels that Firebase uses are consistent with the ASL log levels. * * Enable debug mode by passing the -FIRDebugEnabled argument to the application. You can add this * argument in the application's Xcode scheme. When debug mode is enabled via -FIRDebugEnabled, * further executions of the application will also be in debug mode. In order to return to default * mode, you must explicitly disable the debug mode with the application argument -FIRDebugDisabled. * * It is also possible to change the default logging level in code by calling setLoggerLevel: on * the FIRConfiguration interface. */ @interface FIRApp : NSObject /** * Configures a default Firebase app. Raises an exception if any configuration step fails. The * default app is named "__FIRAPP_DEFAULT". This method should be called after the app is launched * and before using Firebase services. This method is thread safe. */ + (void)configure; /** * Configures the default Firebase app with the provided options. The default app is named * "__FIRAPP_DEFAULT". Raises an exception if any configuration step fails. This method is thread * safe. * * @param options The Firebase application options used to configure the service. */ + (void)configureWithOptions:(FIROptions *)options; /** * Configures a Firebase app with the given name and options. Raises an exception if any * configuration step fails. This method is thread safe. * * @param name The application's name given by the developer. The name should should only contain Letters, Numbers and Underscore. * @param options The Firebase application options used to configure the services. */ + (void)configureWithName:(NSString *)name options:(FIROptions *)options; /** * Returns the default app, or nil if the default app does not exist. */ + (nullable FIRApp *)defaultApp NS_SWIFT_NAME(defaultApp()); /** * Returns a previously created FIRApp instance with the given name, or nil if no such app exists. * This method is thread safe. */ + (nullable FIRApp *)appNamed:(NSString *)name; /** * Returns the set of all extant FIRApp instances, or nil if there are no FIRApp instances. This * method is thread safe. */ + (nullable NSDictionary *)allApps; /** * Cleans up the current FIRApp, freeing associated data and returning its name to the pool for * future use. This method is thread safe. */ - (void)deleteApp:(FIRAppVoidBoolCallback)completion; /** * FIRApp instances should not be initialized directly. Call +[FIRApp configure], * +[FIRApp configureWithOptions:], or +[FIRApp configureWithNames:options:] directly. */ - (instancetype)init NS_UNAVAILABLE; /** * Gets the name of this app. */ @property(nonatomic, copy, readonly) NSString *name; /** * Gets the options for this app. */ @property(nonatomic, readonly) FIROptions *options; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRConfiguration.h ================================================ #import #import "FIRAnalyticsConfiguration.h" #import "FIRLoggerLevel.h" /** * The log levels used by FIRConfiguration. */ typedef NS_ENUM(NSInteger, FIRLogLevel) { /** Error */ kFIRLogLevelError __deprecated = 0, /** Warning */ kFIRLogLevelWarning __deprecated, /** Info */ kFIRLogLevelInfo __deprecated, /** Debug */ kFIRLogLevelDebug __deprecated, /** Assert */ kFIRLogLevelAssert __deprecated, /** Max */ kFIRLogLevelMax __deprecated = kFIRLogLevelAssert } DEPRECATED_MSG_ATTRIBUTE( "Use -FIRDebugEnabled and -FIRDebugDisabled or setLoggerLevel. See FIRApp.h for more details."); /** * This interface provides global level properties that the developer can tweak, and the singleton * of the Firebase Analytics configuration class. */ @interface FIRConfiguration : NSObject /** Returns the shared configuration object. */ + (FIRConfiguration *)sharedInstance; /** The configuration class for Firebase Analytics. */ @property(nonatomic, readwrite) FIRAnalyticsConfiguration *analyticsConfiguration; /** Global log level. Defaults to kFIRLogLevelError. */ @property(nonatomic, readwrite, assign) FIRLogLevel logLevel DEPRECATED_MSG_ATTRIBUTE( "Use -FIRDebugEnabled and -FIRDebugDisabled or setLoggerLevel. See FIRApp.h for more details."); /** * Sets the logging level for internal Firebase logging. Firebase will only log messages * that are logged at or below loggerLevel. The messages are logged both to the Xcode * console and to the device's log. Note that if an app is running from AppStore, it will * never log above FIRLoggerLevelNotice even if loggerLevel is set to a higher (more verbose) * setting. * * @param loggerLevel The maximum logging level. The default level is set to FIRLoggerLevelNotice. */ - (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel; @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRLoggerLevel.h ================================================ /** * The log levels used by internal logging. */ typedef NS_ENUM(NSInteger, FIRLoggerLevel) { FIRLoggerLevelError = 3 /*ASL_LEVEL_ERR*/, FIRLoggerLevelWarning = 4 /*ASL_LEVEL_WARNING*/, FIRLoggerLevelNotice = 5 /*ASL_LEVEL_NOTICE*/, FIRLoggerLevelInfo = 6 /*ASL_LEVEL_INFO*/, FIRLoggerLevelDebug = 7 /*ASL_LEVEL_DEBUG*/, FIRLoggerLevelMin = FIRLoggerLevelError, FIRLoggerLevelMax = FIRLoggerLevelDebug }; ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIROptions.h ================================================ #import /** * This class provides constant fields of Google APIs. */ @interface FIROptions : NSObject /** * Returns the default options. */ + (FIROptions *)defaultOptions; /** * An iOS API key used for authenticating requests from your app, e.g. * @"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk", used to identify your app to Google servers. */ @property(nonatomic, readonly, copy) NSString *APIKey; /** * The OAuth2 client ID for iOS application used to authenticate Google users, for example * @"12345.apps.googleusercontent.com", used for signing in with Google. */ @property(nonatomic, readonly, copy) NSString *clientID; /** * The tracking ID for Google Analytics, e.g. @"UA-12345678-1", used to configure Google Analytics. */ @property(nonatomic, readonly, copy) NSString *trackingID; /** * The Project Number from the Google Developer's console, for example @"012345678901", used to * configure Google Cloud Messaging. */ @property(nonatomic, readonly, copy) NSString *GCMSenderID; /** * The Android client ID used in Google AppInvite when an iOS app has its Android version, for * example @"12345.apps.googleusercontent.com". */ @property(nonatomic, readonly, copy) NSString *androidClientID; /** * The Google App ID that is used to uniquely identify an instance of an app. */ @property(nonatomic, readonly, copy) NSString *googleAppID; /** * The database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". */ @property(nonatomic, readonly, copy) NSString *databaseURL; /** * The URL scheme used to set up Durable Deep Link service. */ @property(nonatomic, readwrite, copy) NSString *deepLinkURLScheme; /** * The Google Cloud Storage bucket name, e.g. @"abc-xyz-123.storage.firebase.com". */ @property(nonatomic, readonly, copy) NSString *storageBucket; /** * Initializes a customized instance of FIROptions with keys. googleAppID, bundleID and GCMSenderID * are required. Other keys may required for configuring specific services. */ - (instancetype)initWithGoogleAppID:(NSString *)googleAppID bundleID:(NSString *)bundleID GCMSenderID:(NSString *)GCMSenderID APIKey:(NSString *)APIKey clientID:(NSString *)clientID trackingID:(NSString *)trackingID androidClientID:(NSString *)androidClientID databaseURL:(NSString *)databaseURL storageBucket:(NSString *)storageBucket deepLinkURLScheme:(NSString *)deepLinkURLScheme; /** * Initializes a customized instance of FIROptions from the file at the given plist file path. * For example, * NSString *filePath = * [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; * FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; * Returns nil if the plist file does not exist or is invalid. */ - (instancetype)initWithContentsOfFile:(NSString *)plistPath; @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FirebaseCore.h ================================================ #import "FIRAnalyticsConfiguration.h" #import "FIRApp.h" #import "FIRConfiguration.h" #import "FIRLoggerLevel.h" #import "FIROptions.h" ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Modules/module.modulemap ================================================ framework module FirebaseCore { umbrella header "FirebaseCore.h" export * module * { export *} link "c++" link "z" link framework "CoreGraphics" link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/FirebaseDatabase ================================================ [File too large to display: 35.0 MB] ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataEventType.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef Firebase_FIRDataEventType_h #define Firebase_FIRDataEventType_h /** * This enum is the set of events that you can observe at a Firebase Database location. */ typedef NS_ENUM(NSInteger, FIRDataEventType) { /// A new child node is added to a location. FIRDataEventTypeChildAdded, /// A child node is removed from a location. FIRDataEventTypeChildRemoved, /// A child node at a location changes. FIRDataEventTypeChildChanged, /// A child node moves relative to the other child nodes at a location. FIRDataEventTypeChildMoved, /// Any data changes at a location or, recursively, at any child node. FIRDataEventTypeValue }; #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataSnapshot.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import NS_ASSUME_NONNULL_BEGIN @class FIRDatabaseReference; /** * A FIRDataSnapshot contains data from a Firebase Database location. Any time you read * Firebase data, you receive the data as a FIRDataSnapshot. * * FIRDataSnapshots are passed to the blocks you attach with observeEventType:withBlock: or observeSingleEvent:withBlock:. * They are efficiently-generated immutable copies of the data at a Firebase Database location. * They can't be modified and will never change. To modify data at a location, * use a FIRDatabaseReference (e.g. with setValue:). */ @interface FIRDataSnapshot : NSObject #pragma mark - Navigating and inspecting a snapshot /** * Gets a FIRDataSnapshot for the location at the specified relative path. * The relative path can either be a simple child key (e.g. 'fred') * or a deeper slash-separated path (e.g. 'fred/name/first'). If the child * location has no data, an empty FIRDataSnapshot is returned. * * @param childPathString A relative path to the location of child data. * @return The FIRDataSnapshot for the child location. */ - (FIRDataSnapshot *)childSnapshotForPath:(NSString *)childPathString; /** * Return YES if the specified child exists. * * @param childPathString A relative path to the location of a potential child. * @return YES if data exists at the specified childPathString, else NO. */ - (BOOL) hasChild:(NSString *)childPathString; /** * Return YES if the DataSnapshot has any children. * * @return YES if this snapshot has any children, else NO. */ - (BOOL) hasChildren; /** * Return YES if the DataSnapshot contains a non-null value. * * @return YES if this snapshot contains a non-null value, else NO. */ - (BOOL) exists; #pragma mark - Data export /** * Returns the raw value at this location, coupled with any metadata, such as priority. * * Priorities, where they exist, are accessible under the ".priority" key in instances of NSDictionary. * For leaf locations with priorities, the value will be under the ".value" key. */ - (id __nullable) valueInExportFormat; #pragma mark - Properties /** * Returns the contents of this data snapshot as native types. * * Data types returned: * + NSDictionary * + NSArray * + NSNumber (also includes booleans) * + NSString * * @return The data as a native object. */ @property (strong, readonly, nonatomic, nullable) id value; /** * Gets the number of children for this DataSnapshot. * * @return An integer indicating the number of children. */ @property (readonly, nonatomic) NSUInteger childrenCount; /** * Gets a FIRDatabaseReference for the location that this data came from. * * @return A FIRDatabaseReference instance for the location of this data. */ @property (nonatomic, readonly, strong) FIRDatabaseReference * ref; /** * The key of the location that generated this FIRDataSnapshot. * * @return An NSString containing the key for the location of this FIRDataSnapshot. */ @property (strong, readonly, nonatomic) NSString* key; /** * An iterator for snapshots of the child nodes in this snapshot. * You can use the native for..in syntax: * * for (FIRDataSnapshot* child in snapshot.children) { * ... * } * * @return An NSEnumerator of the children. */ @property (strong, readonly, nonatomic) NSEnumerator* children; /** * The priority of the data in this FIRDataSnapshot. * * @return The priority as a string, or nil if no priority was set. */ @property (strong, readonly, nonatomic, nullable) id priority; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabase.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDatabaseReference.h" @class FIRApp; NS_ASSUME_NONNULL_BEGIN /** * The entry point for accessing a Firebase Database. You can get an instance by calling * [FIRDatabase database]. To access a location in the database and read or write data, * use [FIRDatabase reference]. */ @interface FIRDatabase : NSObject /** * Gets the instance of FIRDatabase for the default FIRApp. * * @return A FIRDatabase instance. */ + (FIRDatabase *) database NS_SWIFT_NAME(database()); /** * Gets an instance of FIRDatabase for a specific FIRApp. * * @param app The FIRApp to get a FIRDatabase for. * @return A FIRDatabase instance. */ + (FIRDatabase *) databaseForApp:(FIRApp*)app NS_SWIFT_NAME(database(app:)); /** The FIRApp instance to which this FIRDatabase belongs. */ @property (weak, readonly, nonatomic) FIRApp *app; /** * Gets a FIRDatabaseReference for the root of your Firebase Database. */ - (FIRDatabaseReference *) reference; /** * Gets a FIRDatabaseReference for the provided path. * * @param path Path to a location in your Firebase Database. * @return A FIRDatabaseReference pointing to the specified path. */ - (FIRDatabaseReference *) referenceWithPath:(NSString *)path; /** * Gets a FIRDatabaseReference for the provided URL. The URL must be a URL to a path * within this Firebase Database. To create a FIRDatabaseReference to a different database, * create a FIRApp} with a FIROptions object configured with the appropriate database URL. * * @param url A URL to a path within your database. * @return A FIRDatabaseReference for the provided URL. */ - (FIRDatabaseReference *) referenceFromURL:(NSString *)databaseUrl; /** * The Firebase Database client automatically queues writes and sends them to the server at the earliest opportunity, * depending on network connectivity. In some cases (e.g. offline usage) there may be a large number of writes * waiting to be sent. Calling this method will purge all outstanding writes so they are abandoned. * * All writes will be purged, including transactions and onDisconnect writes. The writes will * be rolled back locally, perhaps triggering events for affected event listeners, and the client will not * (re-)send them to the Firebase Database backend. */ - (void)purgeOutstandingWrites; /** * Shuts down our connection to the Firebase Database backend until goOnline is called. */ - (void)goOffline; /** * Resumes our connection to the Firebase Database backend after a previous goOffline call. */ - (void)goOnline; /** * The Firebase Database client will cache synchronized data and keep track of all writes you've * initiated while your application is running. It seamlessly handles intermittent network * connections and re-sends write operations when the network connection is restored. * * However by default your write operations and cached data are only stored in-memory and will * be lost when your app restarts. By setting this value to `YES`, the data will be persisted * to on-device (disk) storage and will thus be available again when the app is restarted * (even when there is no network connectivity at that time). Note that this property must be * set before creating your first Database reference and only needs to be called once per * application. * */ @property (nonatomic) BOOL persistenceEnabled; /** * By default the Firebase Database client will use up to 10MB of disk space to cache data. If the cache grows beyond * this size, the client will start removing data that hasn't been recently used. If you find that your application * caches too little or too much data, call this method to change the cache size. This property must be set before * creating your first FIRDatabaseReference and only needs to be called once per application. * * Note that the specified cache size is only an approximation and the size on disk may temporarily exceed it * at times. Cache sizes smaller than 1 MB or greater than 100 MB are not supported. */ @property (nonatomic) NSUInteger persistenceCacheSizeBytes; /** * Sets the dispatch queue on which all events are raised. The default queue is the main queue. * * Note that this must be set before creating your first Database reference. */ @property (nonatomic, strong) dispatch_queue_t callbackQueue; /** * Enables verbose diagnostic logging. * * @param enabled YES to enable logging, NO to disable. */ + (void) setLoggingEnabled:(BOOL)enabled; /** Retrieve the Firebase Database SDK version. */ + (NSString *) sdkVersion; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseQuery.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDataEventType.h" #import "FIRDataSnapshot.h" NS_ASSUME_NONNULL_BEGIN /** * A FIRDatabaseHandle is used to identify listeners of Firebase Database events. These handles * are returned by observeEventType: and and can later be passed to removeObserverWithHandle: to * stop receiving updates. */ typedef NSUInteger FIRDatabaseHandle; /** * A FIRDatabaseQuery instance represents a query over the data at a particular location. * * You create one by calling one of the query methods (queryOrderedByChild:, queryStartingAtValue:, etc.) * on a FIRDatabaseReference. The query methods can be chained to further specify the data you are interested in * observing */ @interface FIRDatabaseQuery : NSObject #pragma mark - Attach observers to read data /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; #pragma mark - Detaching observers /** * Detach a block previously attached with observeEventType:withBlock:. * * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. */ - (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; /** * Detach all blocks previously attached to this Firebase Database location with observeEventType:withBlock: */ - (void) removeAllObservers; /** * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept * synced, it will not be evicted from the persistent disk cache. * * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. */ - (void) keepSynced:(BOOL)keepSynced; #pragma mark - Querying and limiting /** * queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; /** * queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; /** * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, * queryEndingAtValue:, or queryEqualToValue:. * * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. */ - (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; /** * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child keys. */ - (FIRDatabaseQuery *) queryOrderedByKey; /** * queryOrderedByValue: is used to generate a reference to a view of the data that's been sorted by child value. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child value. */ - (FIRDatabaseQuery *) queryOrderedByValue; /** * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child priorities. */ - (FIRDatabaseQuery *) queryOrderedByPriority; /** * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value * greater than or equal to startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; /** * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. This is most * useful when implementing pagination in a case where multiple nodes can match the startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; /** * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value * less than or equal to endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; /** * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value * less than endValue, or equal to endValue and with a key less than or equal to childKey. This is most useful when * implementing pagination in a case where multiple nodes can match the endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; /** * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal * to the supplied argument. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @return A FIRDatabaseQuery instance, limited to data with the supplied value. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; /** * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value * equal to the supplied argument and with their key equal to childKey. There will be at most one node that matches * because child keys are unique. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @param childKey The name of nodes with the right value * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; #pragma mark - Properties /** * Gets a FIRDatabaseReference for the location of this query. * * @return A FIRDatabaseReference for the location of this query. */ @property (nonatomic, readonly, strong) FIRDatabaseReference * ref; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseReference.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDatabaseQuery.h" #import "FIRDatabase.h" #import "FIRDataSnapshot.h" #import "FIRMutableData.h" #import "FIRTransactionResult.h" #import "FIRServerValue.h" NS_ASSUME_NONNULL_BEGIN @class FIRDatabase; /** * A FIRDatabaseReference represents a particular location in your Firebase Database * and can be used for reading or writing data to that Firebase Database location. * * This class is the starting point for all Firebase Database operations. After you've * obtained your first FIRDatabaseReference via [FIRDatabase reference], you can use it * to read data (ie. observeEventType:withBlock:), write data (ie. setValue:), and to * create new FIRDatabaseReferences (ie. child:). */ @interface FIRDatabaseReference : FIRDatabaseQuery #pragma mark - Getting references to children locations /** * Gets a FIRDatabaseReference for the location at the specified relative path. * The relative path can either be a simple child key (e.g. 'fred') or a * deeper slash-separated path (e.g. 'fred/name/first'). * * @param pathString A relative path from this location to the desired child location. * @return A FIRDatabaseReference for the specified relative path. */ - (FIRDatabaseReference *)child:(NSString *)pathString; /** * childByAppendingPath: is deprecated, use child: instead. */ - (FIRDatabaseReference *)childByAppendingPath:(NSString *)pathString __deprecated_msg("use child: instead"); /** * childByAutoId generates a new child location using a unique key and returns a * FIRDatabaseReference to it. This is useful when the children of a Firebase Database * location represent a list of items. * * The unique key generated by childByAutoId: is prefixed with a client-generated * timestamp so that the resulting list will be chronologically-sorted. * * @return A FIRDatabaseReference for the generated location. */ - (FIRDatabaseReference *) childByAutoId; #pragma mark - Writing data /** Write data to this Firebase Database location. This will overwrite any data at this location and all child locations. Data types that can be set are: - NSString -- @"Hello World" - NSNumber (also includes boolean) -- @YES, @43, @4.333 - NSDictionary -- @{@"key": @"value", @"nested": @{@"another": @"value"} } - NSArray The effect of the write will be visible immediately and the corresponding events will be triggered. Synchronization of the data to the Firebase Database servers will also be started. Passing null for the new value is equivalent to calling remove:; all data at this location or any child location will be deleted. Note that setValue: will remove any priority stored at this location, so if priority is meant to be preserved, you should use setValue:andPriority: instead. @param value The value to be written. */ - (void) setValue:(nullable id)value; /** * The same as setValue: with a block that gets triggered after the write operation has * been committed to the Firebase Database servers. * * @param value The value to be written. * @param block The block to be called after the write has been committed to the Firebase Database servers. */ - (void) setValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * The same as setValue: with an additional priority to be attached to the data being written. * Priorities are used to order items. * * @param value The value to be written. * @param priority The priority to be attached to that data. */ - (void) setValue:(nullable id)value andPriority:(nullable id)priority; /** * The same as setValue:andPriority: with a block that gets triggered after the write operation has * been committed to the Firebase Database servers. * * @param value The value to be written. * @param priority The priority to be attached to that data. * @param block The block to be called after the write has been committed to the Firebase Database servers. */ - (void) setValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Remove the data at this Firebase Database location. Any data at child locations will also be deleted. * * The effect of the delete will be visible immediately and the corresponding events * will be triggered. Synchronization of the delete to the Firebase Database servers will * also be started. * * remove: is equivalent to calling setValue:nil */ - (void) removeValue; /** * The same as remove: with a block that gets triggered after the remove operation has * been committed to the Firebase Database servers. * * @param block The block to be called after the remove has been committed to the Firebase Database servers. */ - (void) removeValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Sets a priority for the data at this Firebase Database location. * Priorities can be used to provide a custom ordering for the children at a location * (if no priorities are specified, the children are ordered by key). * * You cannot set a priority on an empty location. For this reason * setValue:andPriority: should be used when setting initial data with a specific priority * and setPriority: should be used when updating the priority of existing data. * * Children are sorted based on this priority using the following rules: * * Children with no priority come first. * Children with a number as their priority come next. They are sorted numerically by priority (small to large). * Children with a string as their priority come last. They are sorted lexicographically by priority. * Whenever two children have the same priority (including no priority), they are sorted by key. Numeric * keys come first (sorted numerically), followed by the remaining keys (sorted lexicographically). * * Note that priorities are parsed and ordered as IEEE 754 double-precision floating-point numbers. * Keys are always stored as strings and are treated as numbers only when they can be parsed as a * 32-bit integer * * @param priority The priority to set at the specified location. */ - (void) setPriority:(nullable id)priority; /** * The same as setPriority: with a block that is called once the priority has * been committed to the Firebase Database servers. * * @param priority The priority to set at the specified location. * @param block The block that is triggered after the priority has been written on the servers. */ - (void) setPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Updates the values at the specified paths in the dictionary without overwriting other * keys at this location. * * @param values A dictionary of the keys to change and their new values */ - (void) updateChildValues:(NSDictionary *)values; /** * The same as update: with a block that is called once the update has been committed to the * Firebase Database servers * * @param values A dictionary of the keys to change and their new values * @param block The block that is triggered after the update has been written on the Firebase Database servers */ - (void) updateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; #pragma mark - Attaching observers to read data /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * Use removeObserverWithHandle: to stop receiving updates. * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; #pragma mark - Detaching observers /** * Detach a block previously attached with observeEventType:withBlock:. * * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. */ - (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; /** * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept * synced, it will not be evicted from the persistent disk cache. * * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. */ - (void) keepSynced:(BOOL)keepSynced; /** * Removes all observers at the current reference, but does not remove any observers at child references. * removeAllObservers must be called again for each child reference where a listener was established to remove the observers. */ - (void) removeAllObservers; #pragma mark - Querying and limiting /** * queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; /** * queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; /** * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, * queryEndingAtValue:, or queryEqualToValue:. * * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. */ - (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; /** * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child keys. */ - (FIRDatabaseQuery *) queryOrderedByKey; /** * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child priorities. */ - (FIRDatabaseQuery *) queryOrderedByPriority; /** * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value * greater than or equal to startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; /** * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; /** * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value * less than or equal to endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; /** * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value * less than endValue, or equal to endValue and with a key less than or equal to childKey. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; /** * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal * to the supplied argument. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @return A FIRDatabaseQuery instance, limited to data with the supplied value. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; /** * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value * equal to the supplied argument with a key equal to childKey. There will be at most one node that matches because * child keys are unique. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @param childKey The key of nodes with the right value * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; #pragma mark - Managing presence /** * Ensure the data at this location is set to the specified value when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * onDisconnectSetValue: is especially useful for implementing "presence" systems, * where a value should be changed or cleared when a user disconnects * so that he appears "offline" to other users. * * @param value The value to be set after the connection is lost. */ - (void) onDisconnectSetValue:(nullable id)value; /** * Ensure the data at this location is set to the specified value when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers * * @param value The value to be set after the connection is lost. * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectSetValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data at this location is set to the specified value and priority when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * @param value The value to be set after the connection is lost. * @param priority The priority to be set after the connection is lost. */ - (void) onDisconnectSetValue:(nullable id)value andPriority:(id)priority; /** * Ensure the data at this location is set to the specified value and priority when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers * * @param value The value to be set after the connection is lost. * @param priority The priority to be set after the connection is lost. * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectSetValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data at this location is removed when * the client is disconnected (due to closing the app, navigating * to a new page, or network issues). * * onDisconnectRemoveValue is especially useful for implementing "presence" systems. */ - (void) onDisconnectRemoveValue; /** * Ensure the data at this location is removed when * the client is disconnected (due to closing the app, navigating * to a new page, or network issues). * * onDisconnectRemoveValueWithCompletionBlock: is especially useful for implementing "presence" systems. * * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectRemoveValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data has the specified child values updated when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * * @param values A dictionary of child node keys and the values to set them to after the connection is lost. */ - (void) onDisconnectUpdateChildValues:(NSDictionary *)values; /** * Ensure the data has the specified child values updated when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * * @param values A dictionary of child node keys and the values to set them to after the connection is lost. * @param block A block that will be called once the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectUpdateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the * connection is lost, call cancelDisconnectOperations: */ - (void) cancelDisconnectOperations; /** * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the * connection is lost, call cancelDisconnectOperations: * * @param block A block that will be triggered once the Firebase Database servers have acknowledged the cancel request. */ - (void) cancelDisconnectOperationsWithCompletionBlock:(nullable void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; #pragma mark - Manual Connection Management /** * Manually disconnect the Firebase Database client from the server and disable automatic reconnection. * * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) * and goOnline( ) methods may be used to manually control the client connection in cases where * a persistent connection is undesirable. * * While offline, the Firebase Database client will no longer receive data updates from the server. However, * all database operations performed locally will continue to immediately fire events, allowing * your application to continue behaving normally. Additionally, each operation performed locally * will automatically be queued and retried upon reconnection to the Firebase Database server. * * To reconnect to the Firebase Database server and begin receiving remote events, see goOnline( ). * Once the connection is reestablished, the Firebase Database client will transmit the appropriate data * and fire the appropriate events so that your client "catches up" automatically. * * Note: Invoking this method will impact all Firebase Database connections. */ + (void) goOffline; /** * Manually reestablish a connection to the Firebase Database server and enable automatic reconnection. * * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) * and goOnline( ) methods may be used to manually control the client connection in cases where * a persistent connection is undesirable. * * This method should be used after invoking goOffline( ) to disable the active connection. * Once reconnected, the Firebase Database client will automatically transmit the proper data and fire * the appropriate events so that your client "catches up" automatically. * * To disconnect from the Firebase Database server, see goOffline( ). * * Note: Invoking this method will impact all Firebase Database connections. */ + (void) goOnline; #pragma mark - Transactions /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult */ - (void) runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block; /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. */ - (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock; /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by return [FIRTransactionResult abort]. * * Since your block may be run multiple times, this client could see several immediate states that don't exist on the server. You can suppress those immediate states until the server confirms the final state of the transaction. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. * @param localEvents Set this to NO to suppress events raised for intermediate states, and only get events based on the final state of the transaction. */ - (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(nullable void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock withLocalEvents:(BOOL)localEvents; #pragma mark - Retrieving String Representation /** * Gets the absolute URL of this Firebase Database location. * * @return The absolute URL of the referenced Firebase Database location. */ - (NSString *) description; #pragma mark - Properties /** * Gets a FIRDatabaseReference for the parent location. * If this instance refers to the root of your Firebase Database, it has no parent, * and therefore parent( ) will return null. * * @return A FIRDatabaseReference for the parent location. */ @property (strong, readonly, nonatomic, nullable) FIRDatabaseReference * parent; /** * Gets a FIRDatabaseReference for the root location * * @return A new FIRDatabaseReference to root location. */ @property (strong, readonly, nonatomic) FIRDatabaseReference * root; /** * Gets the last token in a Firebase Database location (e.g. 'fred' in https://SampleChat.firebaseIO-demo.com/users/fred) * * @return The key of the location this reference points to. */ @property (strong, readonly, nonatomic) NSString* key; /** * Gets the URL for the Firebase Database location referenced by this FIRDatabaseReference. * * @return The url of the location this reference points to. */ @property (strong, readonly, nonatomic) NSString* URL; /** * Gets the FIRDatabase instance associated with this reference. * * @return The FIRDatabase object for this reference. */ @property (strong, readonly, nonatomic) FIRDatabase *database; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRMutableData.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import NS_ASSUME_NONNULL_BEGIN /** * A FIRMutableData instance is populated with data from a Firebase Database location. * When you are using runTransactionBlock:, you will be given an instance containing the current * data at that location. Your block will be responsible for updating that instance to the data * you wish to save at that location, and then returning using [FIRTransactionResult successWithValue:]. * * To modify the data, set its value property to any of the native types support by Firebase Database: * * + NSNumber (includes BOOL) * + NSDictionary * + NSArray * + NSString * + nil / NSNull to remove the data * * Note that changes made to a child FIRMutableData instance will be visible to the parent. */ @interface FIRMutableData : NSObject #pragma mark - Inspecting and navigating the data /** * Returns boolean indicating whether this mutable data has children. * * @return YES if this data contains child nodes. */ - (BOOL) hasChildren; /** * Indicates whether this mutable data has a child at the given path. * * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' * @return YES if this data contains a child at the specified relative path */ - (BOOL) hasChildAtPath:(NSString *)path; /** * Used to obtain a FIRMutableData instance that encapsulates the data at the given relative path. * Note that changes made to the child will be visible to the parent. * * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' * @return A FIRMutableData instance containing the data at the given path */ - (FIRMutableData *)childDataByAppendingPath:(NSString *)path; #pragma mark - Properties /** * To modify the data contained by this instance of FIRMutableData, set this to any of the native types supported by Firebase Database: * * + NSNumber (includes BOOL) * + NSDictionary * + NSArray * + NSString * + nil / NSNull to remove the data * * Note that setting this value will override the priority at this location. * * @return The current data at this location as a native object */ @property (strong, nonatomic, nullable) id value; /** * Set this property to update the priority of the data at this location. Can be set to the following types: * * + NSNumber * + NSString * + nil / NSNull to remove the priority * * @return The priority of the data at this location */ @property (strong, nonatomic, nullable) id priority; /** * @return The number of child nodes at this location */ @property (readonly, nonatomic) NSUInteger childrenCount; /** * Used to iterate over the children at this location. You can use the native for .. in syntax: * * for (FIRMutableData* child in data.children) { * ... * } * * Note that this enumerator operates on an immutable copy of the child list. So, you can modify the instance * during iteration, but the new additions will not be visible until you get a new enumerator. */ @property (readonly, nonatomic, strong) NSEnumerator* children; /** * @return The key name of this node, or nil if it is the top-most location */ @property (readonly, nonatomic, strong, nullable) NSString* key; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRServerValue.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ NS_ASSUME_NONNULL_BEGIN /** * Placeholder values you may write into Firebase Database as a value or priority * that will automatically be populated by the Firebase Database server. */ @interface FIRServerValue : NSObject /** * Placeholder value for the number of milliseconds since the Unix epoch */ + (NSDictionary *) timestamp; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRTransactionResult.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRMutableData.h" NS_ASSUME_NONNULL_BEGIN /** * Used for runTransactionBlock:. An FIRTransactionResult instance is a container for the results of the transaction. */ @interface FIRTransactionResult : NSObject /** * Used for runTransactionBlock:. Indicates that the new value should be saved at this location * * @param value A FIRMutableData instance containing the new value to be set * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: */ + (FIRTransactionResult *)successWithValue:(FIRMutableData *)value; /** * Used for runTransactionBlock:. Indicates that the current transaction should no longer proceed. * * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: */ + (FIRTransactionResult *) abort; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FirebaseDatabase.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2016 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FirebaseDatabase_h #define FirebaseDatabase_h #import "FIRDatabase.h" #import "FIRDatabaseQuery.h" #import "FIRDatabaseReference.h" #import "FIRDataEventType.h" #import "FIRDataSnapshot.h" #import "FIRMutableData.h" #import "FIRServerValue.h" #import "FIRTransactionResult.h" #endif /* FirebaseDatabase_h */ ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Modules/module.modulemap ================================================ framework module FirebaseDatabase { umbrella header "FirebaseDatabase.h" export * module * { export * } link framework "CFNetwork" link framework "Security" link framework "SystemConfiguration" link "c++" link "icucore" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/NOTICE ================================================ Google LevelDB Copyright (c) 2011 The LevelDB Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- Square Socket Rocket Copyright 2012 Square Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- APLevelDB Created by Adam Preble on 1/23/12. Copyright (c) 2012 Adam Preble. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseInstanceID/CHANGELOG.md ================================================ # 2017-01-31 -- v1.0.9 - Removed an error being mistakenly logged to the console. # 2016-07-06 -- v1.0.8 - Don't store InstanceID plists in Documents folder. # 2016-06-19 -- v1.0.7 - Fix remote-notifications warning on app submission. # 2016-05-16 -- v1.0.6 - Fix CocoaPod linter issues for InstanceID pod. # 2016-05-13 -- v1.0.5 - Fix Authorization errors for InstanceID tokens. # 2016-05-11 -- v1.0.4 - Reduce wait for InstanceID token during parallel requests. # 2016-04-18 -- v1.0.3 - Change flag to disable swizzling to *FirebaseAppDelegateProxyEnabled*. - Fix incessant Keychain errors while accessing InstanceID. - Fix max retries for fetching IID token. # 2016-04-18 -- v1.0.2 - Register for remote notifications on iOS8+ in the SDK itself. ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h ================================================ #import /** * @memberof FIRInstanceID * * The scope to be used when fetching/deleting a token for Firebase Messaging. */ FOUNDATION_EXPORT NSString * __nonnull const kFIRInstanceIDScopeFirebaseMessaging; /** * Called when the system determines that tokens need to be refreshed. * This method is also called if Instance ID has been reset in which * case, tokens and FCM topic subscriptions also need to be refreshed. * * Instance ID service will throttle the refresh event across all devices * to control the rate of token updates on application servers. */ FOUNDATION_EXPORT NSString * __nonnull const kFIRInstanceIDTokenRefreshNotification; /** * @related FIRInstanceID * * The completion handler invoked when the InstanceID token returns. If * the call fails we return the appropriate `error code` as described below. * * @param token The valid token as returned by InstanceID backend. * * @param error The error describing why generating a new token * failed. See the error codes below for a more detailed * description. */ typedef void(^FIRInstanceIDTokenHandler)( NSString * __nullable token, NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the InstanceID `deleteToken` returns. If * the call fails we return the appropriate `error code` as described below * * @param error The error describing why deleting the token failed. * See the error codes below for a more detailed description. */ typedef void(^FIRInstanceIDDeleteTokenHandler)(NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the app identity is created. If the * identity wasn't created for some reason we return the appropriate error code. * * @param identity A valid identity for the app instance, nil if there was an error * while creating an identity. * @param error The error if fetching the identity fails else nil. */ typedef void(^FIRInstanceIDHandler)(NSString * __nullable identity, NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the app identity and all the tokens associated * with it are deleted. Returns a valid error object in case of failure else nil. * * @param error The error if deleting the identity and all the tokens associated with * it fails else nil. */ typedef void(^FIRInstanceIDDeleteHandler)(NSError * __nullable error); /** * @enum FIRInstanceIDError */ typedef NS_ENUM(NSUInteger, FIRInstanceIDError) { // Http related errors. /// Unknown error. FIRInstanceIDErrorUnknown = 0, /// Auth Error -- GCM couldn't validate request from this client. FIRInstanceIDErrorAuthentication = 1, /// NoAccess -- InstanceID service cannot be accessed. FIRInstanceIDErrorNoAccess = 2, /// Timeout -- Request to InstanceID backend timed out. FIRInstanceIDErrorTimeout = 3, /// Network -- No network available to reach the servers. FIRInstanceIDErrorNetwork = 4, /// OperationInProgress -- Another similar operation in progress, /// bailing this one. FIRInstanceIDErrorOperationInProgress = 5, /// InvalidRequest -- Some parameters of the request were invalid. FIRInstanceIDErrorInvalidRequest = 7, }; /** * The APNS token type for the app. If the token type is set to `UNKNOWN` * InstanceID will implicitly try to figure out what the actual token type * is from the provisioning profile. */ typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) { /// Unknown token type. FIRInstanceIDAPNSTokenTypeUnknown, /// Sandbox token type. FIRInstanceIDAPNSTokenTypeSandbox, /// Production token type. FIRInstanceIDAPNSTokenTypeProd, }; /** * Instance ID provides a unique identifier for each app instance and a mechanism * to authenticate and authorize actions (for example, sending a GCM message). * * Instance ID is long lived but, may be reset if the device is not used for * a long time or the Instance ID service detects a problem. * If Instance ID is reset, the app will be notified via * `kFIRInstanceIDTokenRefreshNotification`. * * If the Instance ID has become invalid, the app can request a new one and * send it to the app server. * To prove ownership of Instance ID and to allow servers to access data or * services associated with the app, call * `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. */ @interface FIRInstanceID : NSObject /** * FIRInstanceID. * * @return A shared instance of FIRInstanceID. */ + (nonnull instancetype)instanceID NS_SWIFT_NAME(instanceID()); /** * Unavailable. Use +instanceID instead. */ - (nonnull instancetype)init __attribute__((unavailable("Use +instanceID instead."))); /** * Set APNS token for the application. This APNS token will be used to register * with Firebase Messaging using `token` or * `tokenWithAuthorizedEntity:scope:options:handler`. If the token type is set to * `FIRInstanceIDAPNSTokenTypeUnknown` InstanceID will read the provisioning profile * to find out the token type. * * @param token The APNS token for the application. * @param type The APNS token type for the above token. */ - (void)setAPNSToken:(nonnull NSData *)token type:(FIRInstanceIDAPNSTokenType)type; #pragma mark - Tokens /** * Returns a Firebase Messaging scoped token for the firebase app. * * @return Null Returns null if the device has not yet been registerd with * Firebase Message else returns a valid token. */ - (nullable NSString *)token; /** * Returns a token that authorizes an Entity (example: cloud service) to perform * an action on behalf of the application identified by Instance ID. * * This is similar to an OAuth2 token except, it applies to the * application instance instead of a user. * * This is an asynchronous call. If the token fetching fails for some reason * we invoke the completion callback with nil `token` and the appropriate * error. * * Note, you can only have one `token` or `deleteToken` call for a given * authorizedEntity and scope at any point of time. Making another such call with the * same authorizedEntity and scope before the last one finishes will result in an * error with code `OperationInProgress`. * * @see FIRInstanceID deleteTokenWithAuthorizedEntity:scope:handler: * * @param authorizedEntity Entity authorized by the token. * @param scope Action authorized for authorizedEntity. * @param options The extra options to be sent with your token request. The * value for the `apns_token` should be the NSData object * passed to UIApplication's * `didRegisterForRemoteNotificationsWithDeviceToken` method. * All other keys and values in the options dict need to be * instances of NSString or else they will be discarded. Bundle * keys starting with 'GCM.' and 'GOOGLE.' are reserved. * @param handler The callback handler which is invoked when the token is * successfully fetched. In case of success a valid `token` and * `nil` error are returned. In case of any error the `token` * is nil and a valid `error` is returned. The valid error * codes have been documented above. */ - (void)tokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity scope:(nonnull NSString *)scope options:(nullable NSDictionary *)options handler:(nonnull FIRInstanceIDTokenHandler)handler; /** * Revokes access to a scope (action) for an entity previously * authorized by `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. * * This is an asynchronous call. Call this on the main thread since InstanceID lib * is not thread safe. In case token deletion fails for some reason we invoke the * `handler` callback passed in with the appropriate error code. * * Note, you can only have one `token` or `deleteToken` call for a given * authorizedEntity and scope at a point of time. Making another such call with the * same authorizedEntity and scope before the last one finishes will result in an error * with code `OperationInProgress`. * * @param authorizedEntity Entity that must no longer have access. * @param scope Action that entity is no longer authorized to perform. * @param handler The handler that is invoked once the unsubscribe call ends. * In case of error an appropriate error object is returned * else error is nil. */ - (void)deleteTokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity scope:(nonnull NSString *)scope handler:(nonnull FIRInstanceIDDeleteTokenHandler)handler; #pragma mark - Identity /** * Asynchronously fetch a stable identifier that uniquely identifies the app * instance. If the identifier has been revoked or has expired, this method will * return a new identifier. * * * @param handler The handler to invoke once the identifier has been fetched. * In case of error an appropriate error object is returned else * a valid identifier is returned and a valid identifier for the * application instance. */ - (void)getIDWithHandler:(nonnull FIRInstanceIDHandler)handler; /** * Resets Instance ID and revokes all tokens. */ - (void)deleteIDWithHandler:(nonnull FIRInstanceIDDeleteHandler)handler; @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h ================================================ #import "FIRInstanceID.h" ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap ================================================ framework module FirebaseInstanceID { umbrella header "FirebaseInstanceID.h" export * module * { export *} link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseInstanceID/README.md ================================================ # InstanceID SDK for iOS Instance ID provides a unique ID per instance of your apps and also provides a mechanism to authenticate and authorize actions, like sending messages via Firebase Cloud Messaging (FCM). Please visit [our developer site](https://developers.google.com/instance-id/) for integration instructions, documentation, support information, and terms of service. ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorage.h ================================================ // clang-format off /** @file FIRStorage.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorageConstants.h" @class FIRApp; @class FIRStorageReference; NS_ASSUME_NONNULL_BEGIN /** Project version string for FirebaseStorage. */ FOUNDATION_EXPORT const unsigned char *const FirebaseStorageVersionString; /** * FirebaseStorage is a service that supports uploading and downloading binary objects, * such as images, videos, and other files to Google Cloud Storage. * * If you call [FIRStorage storage], the instance will initialize with the default FIRApp, * [FIRApp defaultApp], and the storage location will come from the provided * GoogleService-Info.plist. * * If you call [FIRStorage storageForApp:] and provide a custom instance of FIRApp, * the storage location will be specified via the FIROptions#storageBucket property. */ @interface FIRStorage : NSObject /** * Creates an instance of FIRStorage, configured with the default FIRApp. * @return the FIRStorage instance, initialized with the default FIRApp. */ + (instancetype)storage NS_SWIFT_NAME(storage()); /** * Creates an instance of FIRStorage, configured with the custom FIRApp @a app. * @param app The custom FIRApp used for initialization. * @return the FIRStorage instance, initialized with the custom FIRApp. */ + (instancetype)storageForApp:(FIRApp *)app NS_SWIFT_NAME(storage(app:)); /** * The Firebase App associated with this Firebase Storage instance. */ @property(strong, nonatomic, readonly) FIRApp *app; /** * Maximum time in seconds to retry an upload if a failure occurs. * Defaults to 10 minutes (600 seconds). */ @property NSTimeInterval maxUploadRetryTime; /** * Maximum time in seconds to retry a download if a failure occurs. * Defaults to 10 minutes (600 seconds). */ @property NSTimeInterval maxDownloadRetryTime; /** * Maximum time in seconds to retry operations other than upload and download if a failure occurs. * Defaults to 2 minutes (120 seconds). */ @property NSTimeInterval maxOperationRetryTime; /** * Queue that all developer callbacks are fired on. Defaults to the main queue. */ @property(strong, nonatomic) dispatch_queue_t callbackQueue; /** * Creates a FIRStorageReference initialized at the root Firebase Storage location. * @return An instance of FIRStorageReference initialized at the root. */ - (FIRStorageReference *)reference; /** * Creates a FIRStorageReference given a gs:// or https:// URL pointing to a Firebase Storage * location. For example, you can pass in an https:// download URL retrieved from * [FIRStorageReference downloadURLWithCompletion] or the gs:// URI from * [FIRStorageReference description]. * @param string A gs:// or https:// URL to initialize the reference with. * @return An instance of FIRStorageReference at the given child path. * @throws Throws an exception if passed in URL is not associated with the FIRApp used to initialize * this FIRStorage. */ - (FIRStorageReference *)referenceForURL:(NSString *)string; /** * Creates a FIRStorageReference initialized at a child Firebase Storage location. * @param string A relative path from the root to initialize the reference with, * for instance @"path/to/object". * @return An instance of FIRStorageReference at the given child path. */ - (FIRStorageReference *)referenceWithPath:(NSString *)string; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageConstants.h ================================================ // clang-format off /** @file FIRStorageConstants.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import @class FIRStorageDownloadTask; @class FIRStorageMetadata; @class FIRStorageTaskSnapshot; @class FIRStorageUploadTask; NS_ASSUME_NONNULL_BEGIN /** * NSString typedef representing a task listener handle. */ typedef NSString *FIRStorageHandle; /** * Block typedef typically used when downloading data. * @param data The data returned by the download, or nil if no data available or download failed. * @param error The error describing failure, if one occurred. */ typedef void (^FIRStorageVoidDataError)(NSData *_Nullable data, NSError *_Nullable error); /** * Block typedef typically used when performing "binary" async operations such as delete, * where the operation either succeeds without an error or fails with an error. * @param error The error describing failure, if one occurred. */ typedef void (^FIRStorageVoidError)(NSError *_Nullable error); /** * Block typedef typically used when retrieving metadata. * @param metadata The metadata returned by the operation, if metadata exists. */ typedef void (^FIRStorageVoidMetadata)(FIRStorageMetadata *_Nullable metadata); /** * Block typedef typically used when retrieving metadata with the possibility of an error. * @param metadata The metadata returned by the operation, if metadata exists. * @param error The error describing failure, if one occurred. */ typedef void (^FIRStorageVoidMetadataError)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error); /** * Block typedef typically used to asynchronously return a storage task snapshot. * @param snapshot The returned task snapshot. */ typedef void (^FIRStorageVoidSnapshot)(FIRStorageTaskSnapshot *snapshot); /** * Block typedef typically used when retrieving a download URL. * @param URL The download URL associated with the operation. * @param error The error describing failure, if one occurred. */ typedef void (^FIRStorageVoidURLError)(NSURL *_Nullable URL, NSError *_Nullable error); /** * Enum representing the upload and download task status. */ typedef NS_ENUM(NSInteger, FIRStorageTaskStatus) { /** * Unknown task status. */ FIRStorageTaskStatusUnknown, /** * Task is being resumed. */ FIRStorageTaskStatusResume, /** * Task reported a progress event. */ FIRStorageTaskStatusProgress, /** * Task is paused. */ FIRStorageTaskStatusPause, /** * Task has completed successfully. */ FIRStorageTaskStatusSuccess, /** * Task has failed and is unrecoverable. */ FIRStorageTaskStatusFailure }; /** * Firebase Storage error domain. */ FOUNDATION_EXPORT NSString *const FIRStorageErrorDomain; /** * Enum representing the errors raised by Firebase Storage. */ typedef NS_ENUM(NSInteger, FIRStorageErrorCode) { /** An unknown error occurred. */ FIRStorageErrorCodeUnknown = -13000, /** No object exists at the desired reference. */ FIRStorageErrorCodeObjectNotFound = -13010, /** No bucket is configured for Firebase Storage. */ FIRStorageErrorCodeBucketNotFound = -13011, /** No project is configured for Firebase Storage. */ FIRStorageErrorCodeProjectNotFound = -13012, /** * Quota on your Firebase Storage bucket has been exceeded. * If you're on the free tier, upgrade to a paid plan. * If you're on a paid plan, reach out to Firebase support. */ FIRStorageErrorCodeQuotaExceeded = -13013, /** User is unauthenticated. Authenticate and try again. */ FIRStorageErrorCodeUnauthenticated = -13020, /** * User is not authorized to perform the desired action. * Check your rules to ensure they are correct. */ FIRStorageErrorCodeUnauthorized = -13021, /** * The maximum time limit on an operation (upload, download, delete, etc.) has been exceeded. * Try uploading again. */ FIRStorageErrorCodeRetryLimitExceeded = -13030, /** * File on the client does not match the checksum of the file received by the server. * Try uploading again. */ FIRStorageErrorCodeNonMatchingChecksum = -13031, /** * Size of the downloaded file exceeds the amount of memory allocated for the download. * Increase memory cap and try downloading again. */ FIRStorageErrorCodeDownloadSizeExceeded = -13032, /** User cancelled the operation. */ FIRStorageErrorCodeCancelled = -13040 }; NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageDownloadTask.h ================================================ // clang-format off /** @file FIRStorageDownloadTask.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorageObservableTask.h" NS_ASSUME_NONNULL_BEGIN /** * FIRStorageDownloadTask implements resumable downloads from an object in Firebase Storage. * Downloads can be returned on completion with a completion handler, and can be monitored * by attaching observers, or controlled by calling FIRStorageTask#pause, FIRStorageTask#resume, * or FIRStorageTask#cancel. * Downloads can currently be returned as NSData in memory, or as an NSURL to a file on disk. * Downloads are performed on a background queue, and callbacks are raised on the developer * specified callbackQueue in FIRStorage, or the main queue if left unspecified. * Currently all uploads must be initiated and managed on the main queue. */ @interface FIRStorageDownloadTask : FIRStorageObservableTask @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageMetadata.h ================================================ // clang-format off /** @file FIRStorageMetadata.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import @class FIRStorageReference; NS_ASSUME_NONNULL_BEGIN /** * Class which represents the metadata on an object in Firebase Storage. This metadata is * returned on successful operations, and can be used to retrieve download URLs, content types, * and a FIRStorage reference to the object in question. Full documentation can be found at the GCS * Objects#resource docs. * @see https://cloud.google.com/storage/docs/json_api/v1/objects#resource */ @interface FIRStorageMetadata : NSObject /** * The name of the bucket containing this object. */ @property(copy, nonatomic, readonly) NSString *bucket; /** * Cache-Control directive for the object data. */ @property(copy, nonatomic, nullable) NSString *cacheControl; /** * Content-Disposition of the object data. */ @property(copy, nonatomic, nullable) NSString *contentDisposition; /** * Content-Encoding of the object data. */ @property(copy, nonatomic, nullable) NSString *contentEncoding; /** * Content-Language of the object data. */ @property(copy, nonatomic, nullable) NSString *contentLanguage; /** * Content-Type of the object data. */ @property(copy, nonatomic, nullable) NSString *contentType; /** * The content generation of this object. Used for object versioning. */ @property(readonly) int64_t generation; /** * User-provided metadata, in key/value pairs. */ @property(copy, nonatomic, nullable) NSDictionary *customMetadata; /** * The version of the metadata for this object at this generation. Used * for preconditions and for detecting changes in metadata. A metageneration number is only * meaningful in the context of a particular generation of a particular object. */ @property(readonly) int64_t metageneration; /** * The name of this object, in gs://bucket/path/to/object.txt, this is object.txt. */ @property(copy, nonatomic, readonly, nullable) NSString *name; /** * The full path of this object, in gs://bucket/path/to/object.txt, this is path/to/object.txt. */ @property(copy, nonatomic, readonly, nullable) NSString *path; /** * Content-Length of the data in bytes. */ @property(readonly) int64_t size; /** * The creation time of the object in RFC 3339 format. */ @property(copy, nonatomic, readonly, nullable) NSDate *timeCreated; /** * The modification time of the object metadata in RFC 3339 format. */ @property(copy, nonatomic, readonly, nullable) NSDate *updated; /** * A reference to the object in Firebase Storage. */ @property(strong, nonatomic, readonly, nullable) FIRStorageReference *storageReference; /** * An array containing all download URLs available for the object. */ @property(strong, nonatomic, readonly, nullable) NSArray *downloadURLs; /** * Creates an instanece of FIRStorageMetadata from the contents of a dictionary. * @return An instance of FIRStorageMetadata that represents the contents of a dictionary. */ - (nullable instancetype)initWithDictionary:(NSDictionary *)dictionary NS_DESIGNATED_INITIALIZER; /** * Creates an NSDictionary from the contents of the metadata. * @return An NSDictionary that represents the contents of the metadata. */ - (NSDictionary *)dictionaryRepresentation; /** * Determines if the current metadata represents a "file". */ @property(readonly, getter=isFile) BOOL file; /** * Determines if the current metadata represents a "folder". */ @property(readonly, getter=isFolder) BOOL folder; /** * Retrieves a download URL for the given object, or nil if none exist. * Note that if there are many valid download tokens, this will always return the first * valid token created. */ - (nullable NSURL *)downloadURL; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageObservableTask.h ================================================ // clang-format off /** @file FIRStorageObservableTask.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import "FIRStorageTask.h" NS_ASSUME_NONNULL_BEGIN @class FIRStorageReference; @class FIRStorageTaskSnapshot; /** * Extends FIRStorageTask to provide observable semantics such as adding and removing observers. * Observers produce a FIRStorageHandle, which is used to keep track of and remove specific * observers at a later date. * This class is currently not thread safe and can only be called on the main thread. */ @interface FIRStorageObservableTask : FIRStorageTask /** * Observes changes in the upload status: Resume, Pause, Progress, Success, and Failure. * @param status The FIRStorageTaskStatus change to observe. * @param handler A callback that fires every time the status event occurs, * returns a FIRStorageTaskSnapshot containing the state of the task. * @return A task handle that can be used to remove the observer at a later date. */ - (FIRStorageHandle)observeStatus:(FIRStorageTaskStatus)status handler:(void (^)(FIRStorageTaskSnapshot *snapshot))handler; /** * Removes the single observer with the provided handle. * @param handle The handle of the task to remove. */ - (void)removeObserverWithHandle:(FIRStorageHandle)handle; /** * Removes all observers for a single status. * @param status A FIRStorageTaskStatus to remove listeners for. */ - (void)removeAllObserversForStatus:(FIRStorageTaskStatus)status; /** * Removes all observers. */ - (void)removeAllObservers; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageReference.h ================================================ // clang-format off /** @file FIRStorageReference.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorage.h" #import "FIRStorageConstants.h" #import "FIRStorageDownloadTask.h" #import "FIRStorageMetadata.h" #import "FIRStorageTask.h" #import "FIRStorageUploadTask.h" NS_ASSUME_NONNULL_BEGIN /** * FIRStorageReference represents a reference to a Google Cloud Storage object. Developers can * upload and download objects, as well as get/set object metadata, and delete an object at the * path. * @see https://cloud.google.com/storage/ */ @interface FIRStorageReference : NSObject /** * The FIRStorage service object which created this reference. */ @property(nonatomic, readonly) FIRStorage *storage; /** * The name of the Google Cloud Storage bucket associated with this reference, * in gs://bucket/path/to/object.txt, the bucket would be: 'bucket' */ @property(nonatomic, readonly) NSString *bucket; /** * The full path to this object, not including the Google Cloud Storage bucket. * In gs://bucket/path/to/object.txt, the full path would be: 'path/to/object.txt' */ @property(nonatomic, readonly) NSString *fullPath; /** * The short name of the object associated with this reference, * in gs://bucket/path/to/object.txt, the name of the object would be: 'object.txt' */ @property(nonatomic, readonly) NSString *name; #pragma mark - Path Operations /** * Creates a new FIRStorageReference pointing to the root object. * @return A new FIRStorageReference pointing to the root object. */ - (FIRStorageReference *)root; /** * Creates a new FIRStorageReference pointing to the parent of the current reference * or nil if this instance references the root location. * For example: * path = foo/bar/baz parent = foo/bar * path = foo parent = (root) * path = (root) parent = nil * @return A new FIRStorageReference pointing to the parent of the current reference. */ - (nullable FIRStorageReference *)parent; /** * Creates a new FIRStorageReference pointing to a child object of the current reference. * path = foo child = bar newPath = foo/bar * path = foo/bar child = baz newPath = foo/bar/baz * All leading and trailing slashes will be removed, and consecutive slashes will be * compressed to single slashes. For example: * child = /foo/bar newPath = foo/bar * child = foo/bar/ newPath = foo/bar * child = foo///bar newPath = foo/bar * @param path Path to append to the current path. * @return A new FIRStorageReference pointing to a child location of the current reference. */ - (FIRStorageReference *)child:(NSString *)path; #pragma mark - Uploads /** * Asynchronously uploads data to the currently specified FIRStorageReference, * without additional metadata. * This is not recommended for large files, and one should instead upload a file from disk. * @param uploadData The NSData to upload. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putData:(NSData *)uploadData; /** * Asynchronously uploads data to the currently specified FIRStorageReference. * This is not recommended for large files, and one should instead upload a file from disk. * @param uploadData The NSData to upload. * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) * about the object being uploaded. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putData:(NSData *)uploadData metadata:(nullable FIRStorageMetadata *)metadata; /** * Asynchronously uploads data to the currently specified FIRStorageReference. * This is not recommended for large files, and one should instead upload a file from disk. * @param uploadData The NSData to upload. * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) * about the object being uploaded. * @param completion A completion block that either returns the object metadata on success, * or an error on failure. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putData:(NSData *)uploadData metadata:(nullable FIRStorageMetadata *)metadata completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error))completion; /** * Asynchronously uploads a file to the currently specified FIRStorageReference, * without additional metadata. * @param fileURL A URL representing the system file path of the object to be uploaded. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putFile:(NSURL *)fileURL; /** * Asynchronously uploads a file to the currently specified FIRStorageReference. * @param fileURL A URL representing the system file path of the object to be uploaded. * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) * about the object being uploaded. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putFile:(NSURL *)fileURL metadata:(nullable FIRStorageMetadata *)metadata; /** * Asynchronously uploads a file to the currently specified FIRStorageReference. * @param fileURL A URL representing the system file path of the object to be uploaded. * @param metadata FIRStorageMetadata containing additional information (MIME type, etc.) * about the object being uploaded. * @param completion A completion block that either returns the object metadata on success, * or an error on failure. * @return An instance of FIRStorageUploadTask, which can be used to monitor or manage the upload. */ - (FIRStorageUploadTask *)putFile:(NSURL *)fileURL metadata:(nullable FIRStorageMetadata *)metadata completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error))completion; #pragma mark - Downloads /** * Asynchronously downloads the object at the FIRStorageReference to an NSData object in memory. * An NSData of the provided max size will be allocated, so ensure that the device has enough free * memory to complete the download. For downloading large files, writeToFile may be a better option. * @param size The maximum size in bytes to download. If the download exceeds this size * the task will be cancelled and an error will be returned. * @param completion A completion block that either returns the object data on success, * or an error on failure. * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. */ - (FIRStorageDownloadTask *)dataWithMaxSize:(int64_t)size completion:(void (^)(NSData *_Nullable data, NSError *_Nullable error))completion; /** * Asynchronously retrieves a long lived download URL with a revokable token. * This can be used to share the file with others, but can be revoked by a developer * in the Firebase Console if desired. * @param completion A completion block that either returns the URL on success, * or an error on failure. */ - (void)downloadURLWithCompletion:(void (^)(NSURL *_Nullable URL, NSError *_Nullable error))completion; /** * Asynchronously downloads the object at the current path to a specified system filepath. * @param fileURL A file system URL representing the path the object should be downloaded to. * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. */ - (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL; /** * Asynchronously downloads the object at the current path to a specified system filepath. * @param fileURL A file system URL representing the path the object should be downloaded to. * @param completion A completion block that fires when the file download completes. * Returns an NSURL pointing to the file path of the downloaded file on success, * or an error on failure. * @return An FIRStorageDownloadTask that can be used to monitor or manage the download. */ - (FIRStorageDownloadTask *)writeToFile:(NSURL *)fileURL completion:(nullable void (^)(NSURL *_Nullable URL, NSError *_Nullable error))completion; #pragma mark - Metadata Operations /** * Retrieves metadata associated with an object at the current path. * @param completion A completion block which returns the object metadata on success, * or an error on failure. */ - (void)metadataWithCompletion:(void (^)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error))completion; /** * Updates the metadata associated with an object at the current path. * @param metadata An FIRStorageMetadata object with the metadata to update. * @param completion A completion block which returns the FIRStorageMetadata on success, * or an error on failure. */ - (void)updateMetadata:(FIRStorageMetadata *)metadata completion:(nullable void (^)(FIRStorageMetadata *_Nullable metadata, NSError *_Nullable error))completion; #pragma mark - Delete /** * Deletes the object at the current path. * @param completion A completion block which returns nil on success, or an error on failure. */ - (void)deleteWithCompletion:(nullable void (^)(NSError *_Nullable error))completion; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTask.h ================================================ // clang-format off /** @file FIRStorageTask.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorageConstants.h" #import "FIRStorageMetadata.h" NS_ASSUME_NONNULL_BEGIN /** * A superclass to all FIRStorage*Tasks, including FIRStorageUploadTask * and FIRStorageDownloadTask, to provide state transitions, event raising, and common storage * or metadata and errors. * Callbacks are always fired on the developer specified callback queue. * If no queue is specified by the developer, it defaults to the main queue. * Currently not thread safe, so only call methods on the main thread. */ @interface FIRStorageTask : NSObject /** * An immutable view of the task and associated metadata, progress, error, etc. */ @property(strong, readonly, nonatomic, nonnull) FIRStorageTaskSnapshot *snapshot; @end /** * Defines task operations such as pause, resume, cancel, and enqueue for all tasks. * All tasks are required to implement enqueue, which begins the task, and may optionally * implement pause, resume, and cancel, which operate on the task to pause, resume, and cancel * operations. */ @protocol FIRStorageTaskManagement @required /** * Prepares a task and begins execution. */ - (void)enqueue; @optional /** * Pauses a task currently in progress. */ - (void)pause; /** * Cancels a task currently in progress. */ - (void)cancel; /** * Resumes a task that is paused. */ - (void)resume; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageTaskSnapshot.h ================================================ // clang-format off /** @file FIRStorageTaskSnapshot.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorageConstants.h" NS_ASSUME_NONNULL_BEGIN @class FIRStorageMetadata; @class FIRStorageReference; @class FIRStorageTask; /** * FIRStorageTaskSnapshot represents an immutable view of a task. * A Snapshot contains a task, storage reference, metadata (if it exists), * progress, and an error (if one occurred). */ @interface FIRStorageTaskSnapshot : NSObject /** * Subclass of FIRStorageTask this snapshot represents. */ @property(readonly, copy, nonatomic) __kindof FIRStorageTask *task; /** * Metadata returned by the task, or nil if no metadata returned. */ @property(readonly, copy, nonatomic, nullable) FIRStorageMetadata *metadata; /** * FIRStorageReference this task is operates on. */ @property(readonly, copy, nonatomic) FIRStorageReference *reference; /** * NSProgress object which tracks the progess of an upload or download. */ @property(readonly, strong, nonatomic, nullable) NSProgress *progress; /** * Error during task execution, or nil if no error occurred. */ @property(readonly, copy, nonatomic, nullable) NSError *error; /** * Status of the task. */ @property(readonly, nonatomic) FIRStorageTaskStatus status; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FIRStorageUploadTask.h ================================================ // clang-format off /** @file FIRStorageUploadTask.h @brief Firebase SDK @copyright Copyright 2016 Google Inc. @remarks Use of this SDK is subject to the Google APIs Terms of Service: https://developers.google.com/terms/ */ // clang-format on #import #import "FIRStorageObservableTask.h" NS_ASSUME_NONNULL_BEGIN /** * FIRStorageUploadTask implements resumable uploads to a file in Firebase Storage. * Uploads can be returned on completion with a completion callback, and can be monitored * by attaching observers, or controlled by calling FIRStorageTask#pause, FIRStorageTask#resume, * or FIRStorageTask#cancel. * Uploads can take NSData in memory, or an NSURL to a file on disk. * Uploads are performed on a background queue, and callbacks are raised on the developer * specified callbackQueue in FIRStorage, or the main queue if left unspecified. * Currently all uploads must be initiated and managed on the main queue. */ @interface FIRStorageUploadTask : FIRStorageObservableTask @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Headers/FirebaseStorage.h ================================================ #import "FIRStorage.h" #import "FIRStorageConstants.h" #import "FIRStorageDownloadTask.h" #import "FIRStorageMetadata.h" #import "FIRStorageObservableTask.h" #import "FIRStorageReference.h" #import "FIRStorageTask.h" #import "FIRStorageTaskSnapshot.h" #import "FIRStorageUploadTask.h" ================================================ FILE: iOS/Manager/EZShopManager/Pods/FirebaseStorage/Frameworks/FirebaseStorage.framework/Modules/module.modulemap ================================================ framework module FirebaseStorage { umbrella header "FirebaseStorage.h" export * module * { export *} link "z" link framework "CoreGraphics" link framework "Foundation" link framework "MobileCoreServices" link framework "Security" link framework "UIKit" } ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/README.md ================================================ # Google Toolbox for Mac - Session Fetcher # **Project site**
**Discussion group** [![Build Status](https://travis-ci.org/google/gtm-session-fetcher.svg?branch=master)](https://travis-ci.org/google/gtm-session-fetcher) `GTMSessionFetcher` makes it easy for Cocoa applications to perform http operations. The fetcher is implemented as a wrapper on `NSURLSession`, so its behavior is asynchronous and uses operating-system settings on iOS and Mac OS X. Features include: - Simple to build; only one source/header file pair is required - Simple to use: takes just two lines of code to fetch a request - Supports upload and download sessions - Flexible cookie storage - Automatic retry on errors, with exponential backoff - Support for generating multipart MIME upload streams - Easy, convenient logging of http requests and responses - Supports plug-in authentication such as with GTMAppAuth - Easily testable; self-mocking - Automatic rate limiting when created by the `GTMSessionFetcherService` factory class - Fully independent of other projects ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // GTMSessionFetcher is a wrapper around NSURLSession for http operations. // // What does this offer on top of of NSURLSession? // // - Block-style callbacks for useful functionality like progress rather // than delegate methods. // - Out-of-process uploads and downloads using NSURLSession, including // management of fetches after relaunch. // - Integration with GTMAppAuth for invisible management and refresh of // authorization tokens. // - Pretty-printed http logging. // - Cookies handling that does not interfere with or get interfered with // by WebKit cookies or on Mac by Safari and other apps. // - Credentials handling for the http operation. // - Rate-limiting and cookie grouping when fetchers are created with // GTMSessionFetcherService. // // If the bodyData or bodyFileURL property is set, then a POST request is assumed. // // Each fetcher is assumed to be for a one-shot fetch request; don't reuse the object // for a second fetch. // // The fetcher will be self-retained as long as a connection is pending. // // To keep user activity private, URLs must have an https scheme (unless the property // allowedInsecureSchemes is set to permit the scheme.) // // Callbacks will be released when the fetch completes or is stopped, so there is no need // to use weak self references in the callback blocks. // // Sample usage: // // _fetcherService = [[GTMSessionFetcherService alloc] init]; // // GTMSessionFetcher *myFetcher = [_fetcherService fetcherWithURLString:myURLString]; // myFetcher.retryEnabled = YES; // myFetcher.comment = @"First profile image"; // // // Optionally specify a file URL or NSData for the request body to upload. // myFetcher.bodyData = [postString dataUsingEncoding:NSUTF8StringEncoding]; // // [myFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { // if (error != nil) { // // Server status code or network error. // // // // If the domain is kGTMSessionFetcherStatusDomain then the error code // // is a failure status from the server. // } else { // // Fetch succeeded. // } // }]; // // There is also a beginFetch call that takes a pointer and selector for the completion handler; // a pointer and selector is a better style when the callback is a substantial, separate method. // // NOTE: Fetches may retrieve data from the server even though the server // returned an error, so the criteria for success is a non-nil error. // The completion handler is called when the server status is >= 300 with an NSError // having domain kGTMSessionFetcherStatusDomain and code set to the server status. // // Status codes are at // // // Background session support: // // Out-of-process uploads and downloads may be created by setting the fetcher's // useBackgroundSession property. Data to be uploaded should be provided via // the uploadFileURL property; the download destination should be specified with // the destinationFileURL. NOTE: Background upload files should be in a location // that will be valid even after the device is restarted, so the file should not // be uploaded from a system temporary or cache directory. // // Background session transfers are slower, and should typically be used only // for very large downloads or uploads (hundreds of megabytes). // // When background sessions are used in iOS apps, the application delegate must // pass through the parameters from UIApplicationDelegate's // application:handleEventsForBackgroundURLSession:completionHandler: to the // fetcher class. // // When the application has been relaunched, it may also create a new fetcher // instance to handle completion of the transfers. // // - (void)application:(UIApplication *)application // handleEventsForBackgroundURLSession:(NSString *)identifier // completionHandler:(void (^)())completionHandler { // // Application was re-launched on completing an out-of-process download. // // // Pass the URLSession info related to this re-launch to the fetcher class. // [GTMSessionFetcher application:application // handleEventsForBackgroundURLSession:identifier // completionHandler:completionHandler]; // // // Get a fetcher related to this re-launch and re-hook up a completionHandler to it. // GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithSessionIdentifier:identifier]; // NSURL *destinationFileURL = fetcher.destinationFileURL; // fetcher.completionHandler = ^(NSData *data, NSError *error) { // [self downloadCompletedToFile:destinationFileURL error:error]; // }; // } // // // Threading and queue support: // // Networking always happens on a background thread; there is no advantage to // changing thread or queue to create or start a fetcher. // // Callbacks are run on the main thread; alternatively, the app may set the // fetcher's callbackQueue to a dispatch queue. // // Once the fetcher's beginFetch method has been called, the fetcher's methods and // properties may be accessed from any thread. // // Downloading to disk: // // To have downloaded data saved directly to disk, specify a file URL for the // destinationFileURL property. // // HTTP methods and headers: // // Alternative HTTP methods, like PUT, and custom headers can be specified by // creating the fetcher with an appropriate NSMutableURLRequest. // // // Caching: // // The fetcher avoids caching. That is best for API requests, but may hurt // repeat fetches of static data. Apps may enable a persistent disk cache by // customizing the config: // // fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, // NSURLSessionConfiguration *config) { // config.URLCache = [NSURLCache sharedURLCache]; // }; // // Or use the standard system config to share cookie storage with web views // and to enable disk caching: // // fetcher.configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; // // // Cookies: // // There are three supported mechanisms for remembering cookies between fetches. // // By default, a standalone GTMSessionFetcher uses a mutable array held // statically to track cookies for all instantiated fetchers. This avoids // cookies being set by servers for the application from interfering with // Safari and WebKit cookie settings, and vice versa. // The fetcher cookies are lost when the application quits. // // To rely instead on WebKit's global NSHTTPCookieStorage, set the fetcher's // cookieStorage property: // myFetcher.cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; // // To share cookies with other apps, use the method introduced in iOS 9/OS X 10.11: // myFetcher.cookieStorage = // [NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:kMyCompanyContainedID]; // // To ignore existing cookies and only have cookies related to the single fetch // be applied, make a temporary cookie storage object: // myFetcher.cookieStorage = [[GTMSessionCookieStorage alloc] init]; // // Note: cookies set while following redirects will be sent to the server, as // the redirects are followed by the fetcher. // // To completely disable cookies, similar to setting cookieStorageMethod to // kGTMHTTPFetcherCookieStorageMethodNone, adjust the session configuration // appropriately in the fetcher or fetcher service: // fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, // NSURLSessionConfiguration *config) { // config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; // config.HTTPShouldSetCookies = NO; // }; // // If the fetcher is created from a GTMSessionFetcherService object // then the cookie storage mechanism is set to use the cookie storage in the // service object rather than the static storage. Disabling cookies in the // session configuration set on a service object will disable cookies for all // fetchers created from that GTMSessionFetcherService object, since the session // configuration is propagated to the fetcher. // // // Monitoring data transfers. // // The fetcher supports a variety of properties for progress monitoring // progress with callback blocks. // GTMSessionFetcherSendProgressBlock sendProgressBlock // GTMSessionFetcherReceivedProgressBlock receivedProgressBlock // GTMSessionFetcherDownloadProgressBlock downloadProgressBlock // // If supplied by the server, the anticipated total download size is available // as [[myFetcher response] expectedContentLength] (and may be -1 for unknown // download sizes.) // // // Automatic retrying of fetches // // The fetcher can optionally create a timer and reattempt certain kinds of // fetch failures (status codes 408, request timeout; 502, gateway failure; // 503, service unavailable; 504, gateway timeout; networking errors // NSURLErrorTimedOut and NSURLErrorNetworkConnectionLost.) The user may // set a retry selector to customize the type of errors which will be retried. // // Retries are done in an exponential-backoff fashion (that is, after 1 second, // 2, 4, 8, and so on.) // // Enabling automatic retries looks like this: // myFetcher.retryEnabled = YES; // // With retries enabled, the completion callbacks are called only // when no more retries will be attempted. Calling the fetcher's stopFetching // method will terminate the retry timer, without the finished or failure // selectors being invoked. // // Optionally, the client may set the maximum retry interval: // myFetcher.maxRetryInterval = 60.0; // in seconds; default is 60 seconds // // for downloads, 600 for uploads // // Servers should never send a 400 or 500 status for errors that are retryable // by clients, as those values indicate permanent failures. In nearly all // cases, the default standard retry behavior is correct for clients, and no // custom client retry behavior is needed or appropriate. Servers that send // non-retryable status codes and expect the client to retry the request are // faulty. // // Still, the client may provide a block to determine if a status code or other // error should be retried. The block returns YES to set the retry timer or NO // to fail without additional fetch attempts. // // The retry method may return the |suggestedWillRetry| argument to get the // default retry behavior. Server status codes are present in the // error argument, and have the domain kGTMSessionFetcherStatusDomain. The // user's method may look something like this: // // myFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error, // GTMSessionFetcherRetryResponse response) { // // Perhaps examine error.domain and error.code, or fetcher.retryCount // // // // Respond with YES to start the retry timer, NO to proceed to the failure // // callback, or suggestedWillRetry to get default behavior for the // // current error domain and code values. // response(suggestedWillRetry); // }; #import #if TARGET_OS_IPHONE #import #endif #if TARGET_OS_WATCH #import #endif // By default it is stripped from non DEBUG builds. Developers can override // this in their project settings. #ifndef STRIP_GTM_FETCH_LOGGING #if !DEBUG #define STRIP_GTM_FETCH_LOGGING 1 #else #define STRIP_GTM_FETCH_LOGGING 0 #endif #endif // Logs in debug builds. #ifndef GTMSESSION_LOG_DEBUG #if DEBUG #define GTMSESSION_LOG_DEBUG(...) NSLog(__VA_ARGS__) #else #define GTMSESSION_LOG_DEBUG(...) do { } while (0) #endif #endif // Asserts in debug builds (or logs in debug builds if GTMSESSION_ASSERT_AS_LOG // or NS_BLOCK_ASSERTIONS are defined.) #ifndef GTMSESSION_ASSERT_DEBUG #if DEBUG && !defined(NS_BLOCK_ASSERTIONS) && !GTMSESSION_ASSERT_AS_LOG #undef GTMSESSION_ASSERT_AS_LOG #define GTMSESSION_ASSERT_AS_LOG 1 #endif #if DEBUG && !GTMSESSION_ASSERT_AS_LOG #define GTMSESSION_ASSERT_DEBUG(...) NSAssert(__VA_ARGS__) #elif DEBUG #define GTMSESSION_ASSERT_DEBUG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } #else #define GTMSESSION_ASSERT_DEBUG(pred, ...) do { } while (0) #endif #endif // Asserts in debug builds, logs in release builds (or logs in debug builds if // GTMSESSION_ASSERT_AS_LOG is defined.) #ifndef GTMSESSION_ASSERT_DEBUG_OR_LOG #if DEBUG && !GTMSESSION_ASSERT_AS_LOG #define GTMSESSION_ASSERT_DEBUG_OR_LOG(...) NSAssert(__VA_ARGS__) #else #define GTMSESSION_ASSERT_DEBUG_OR_LOG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } #endif #endif // Macro useful for examining messages from NSURLSession during debugging. #if 0 #define GTM_LOG_SESSION_DELEGATE(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) #else #define GTM_LOG_SESSION_DELEGATE(...) #endif #ifndef GTM_NULLABLE #if __has_feature(nullability) // Available starting in Xcode 6.3 #define GTM_NULLABLE_TYPE __nullable #define GTM_NONNULL_TYPE __nonnull #define GTM_NULLABLE nullable #define GTM_NONNULL_DECL nonnull // GTM_NONNULL is used by GTMDefines.h #define GTM_NULL_RESETTABLE null_resettable #define GTM_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN #define GTM_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END #else #define GTM_NULLABLE_TYPE #define GTM_NONNULL_TYPE #define GTM_NULLABLE #define GTM_NONNULL_DECL #define GTM_NULL_RESETTABLE #define GTM_ASSUME_NONNULL_BEGIN #define GTM_ASSUME_NONNULL_END #endif // __has_feature(nullability) #endif // GTM_NULLABLE #if (TARGET_OS_TV \ || TARGET_OS_WATCH \ || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12) \ || (TARGET_OS_IPHONE && defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0)) #define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) __attribute__((deprecated("" _MSG))) #else #define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) #endif #ifndef GTM_DECLARE_GENERICS #if __has_feature(objc_generics) #define GTM_DECLARE_GENERICS 1 #else #define GTM_DECLARE_GENERICS 0 #endif #endif #ifndef GTM_NSArrayOf #if GTM_DECLARE_GENERICS #define GTM_NSArrayOf(value) NSArray #define GTM_NSDictionaryOf(key, value) NSDictionary #else #define GTM_NSArrayOf(value) NSArray #define GTM_NSDictionaryOf(key, value) NSDictionary #endif // __has_feature(objc_generics) #endif // GTM_NSArrayOf // For iOS, the fetcher can declare itself a background task to allow fetches // to finish when the app leaves the foreground. // // (This is unrelated to providing a background configuration, which allows // out-of-process uploads and downloads.) // // To disallow use of background tasks during fetches, the target should define // GTM_BACKGROUND_TASK_FETCHING to 0, or alternatively may set the // skipBackgroundTask property to YES. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH && !defined(GTM_BACKGROUND_TASK_FETCHING) #define GTM_BACKGROUND_TASK_FETCHING 1 #endif // If GTM_BACKGROUND_TASK_FETCHING is enabled and GTMUIApplicationProtocol is not used, // GTM_BACKGROUND_UIAPPLICATION will allow defaulting to UIApplication. To avoid references to // UIApplication (e.g. for extensions), set GTM_BACKGROUND_UIAPPLICATION to 0. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH && !defined(GTM_BACKGROUND_UIAPPLICATION) #define GTM_BACKGROUND_UIAPPLICATION 1 #endif #ifdef __cplusplus extern "C" { #endif #if (TARGET_OS_TV \ || TARGET_OS_WATCH \ || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) #ifndef GTM_USE_SESSION_FETCHER #define GTM_USE_SESSION_FETCHER 1 #endif #endif #if !defined(GTMBridgeFetcher) // These bridge macros should be identical in GTMHTTPFetcher.h and GTMSessionFetcher.h #if GTM_USE_SESSION_FETCHER // Macros to new fetcher class. #define GTMBridgeFetcher GTMSessionFetcher #define GTMBridgeFetcherService GTMSessionFetcherService #define GTMBridgeFetcherServiceProtocol GTMSessionFetcherServiceProtocol #define GTMBridgeAssertValidSelector GTMSessionFetcherAssertValidSelector #define GTMBridgeCookieStorage GTMSessionCookieStorage #define GTMBridgeCleanedUserAgentString GTMFetcherCleanedUserAgentString #define GTMBridgeSystemVersionString GTMFetcherSystemVersionString #define GTMBridgeApplicationIdentifier GTMFetcherApplicationIdentifier #define kGTMBridgeFetcherStatusDomain kGTMSessionFetcherStatusDomain #define kGTMBridgeFetcherStatusBadRequest GTMSessionFetcherStatusBadRequest #else // Macros to old fetcher class. #define GTMBridgeFetcher GTMHTTPFetcher #define GTMBridgeFetcherService GTMHTTPFetcherService #define GTMBridgeFetcherServiceProtocol GTMHTTPFetcherServiceProtocol #define GTMBridgeAssertValidSelector GTMAssertSelectorNilOrImplementedWithArgs #define GTMBridgeCookieStorage GTMCookieStorage #define GTMBridgeCleanedUserAgentString GTMCleanedUserAgentString #define GTMBridgeSystemVersionString GTMSystemVersionString #define GTMBridgeApplicationIdentifier GTMApplicationIdentifier #define kGTMBridgeFetcherStatusDomain kGTMHTTPFetcherStatusDomain #define kGTMBridgeFetcherStatusBadRequest kGTMHTTPFetcherStatusBadRequest #endif // GTM_USE_SESSION_FETCHER #endif GTM_ASSUME_NONNULL_BEGIN // Notifications // // Fetch started and stopped, and fetch retry delay started and stopped. extern NSString *const kGTMSessionFetcherStartedNotification; extern NSString *const kGTMSessionFetcherStoppedNotification; extern NSString *const kGTMSessionFetcherRetryDelayStartedNotification; extern NSString *const kGTMSessionFetcherRetryDelayStoppedNotification; // Completion handler notification. This is intended for use by code capturing // and replaying fetch requests and results for testing. For fetches where // destinationFileURL or accumulateDataBlock is set for the fetcher, the data // will be nil for successful fetches. // // This notification is posted on the main thread. extern NSString *const kGTMSessionFetcherCompletionInvokedNotification; extern NSString *const kGTMSessionFetcherCompletionDataKey; extern NSString *const kGTMSessionFetcherCompletionErrorKey; // Constants for NSErrors created by the fetcher (excluding server status errors, // and error objects originating in the OS.) extern NSString *const kGTMSessionFetcherErrorDomain; // The fetcher turns server error status values (3XX, 4XX, 5XX) into NSErrors // with domain kGTMSessionFetcherStatusDomain. // // Any server response body data accompanying the status error is added to the // userInfo dictionary with key kGTMSessionFetcherStatusDataKey. extern NSString *const kGTMSessionFetcherStatusDomain; extern NSString *const kGTMSessionFetcherStatusDataKey; // When a fetch fails with an error, these keys are included in the error userInfo // dictionary if retries were attempted. extern NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey; extern NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey; // Background session support requires access to NSUserDefaults. // If [NSUserDefaults standardUserDefaults] doesn't yield the correct NSUserDefaults for your usage, // ie for an App Extension, then implement this class/method to return the correct NSUserDefaults. // https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6 @interface GTMSessionFetcherUserDefaultsFactory : NSObject + (NSUserDefaults *)fetcherUserDefaults; @end #ifdef __cplusplus } #endif typedef NS_ENUM(NSInteger, GTMSessionFetcherError) { GTMSessionFetcherErrorDownloadFailed = -1, GTMSessionFetcherErrorUploadChunkUnavailable = -2, GTMSessionFetcherErrorBackgroundExpiration = -3, GTMSessionFetcherErrorBackgroundFetchFailed = -4, GTMSessionFetcherErrorInsecureRequest = -5, GTMSessionFetcherErrorTaskCreationFailed = -6, }; typedef NS_ENUM(NSInteger, GTMSessionFetcherStatus) { // Standard http status codes. GTMSessionFetcherStatusNotModified = 304, GTMSessionFetcherStatusBadRequest = 400, GTMSessionFetcherStatusUnauthorized = 401, GTMSessionFetcherStatusForbidden = 403, GTMSessionFetcherStatusPreconditionFailed = 412 }; #ifdef __cplusplus extern "C" { #endif @class GTMSessionCookieStorage; @class GTMSessionFetcher; // The configuration block is for modifying the NSURLSessionConfiguration only. // DO NOT change any fetcher properties in the configuration block. typedef void (^GTMSessionFetcherConfigurationBlock)(GTMSessionFetcher *fetcher, NSURLSessionConfiguration *configuration); typedef void (^GTMSessionFetcherSystemCompletionHandler)(void); typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data, NSError * GTM_NULLABLE_TYPE error); typedef void (^GTMSessionFetcherBodyStreamProviderResponse)(NSInputStream *bodyStream); typedef void (^GTMSessionFetcherBodyStreamProvider)(GTMSessionFetcherBodyStreamProviderResponse response); typedef void (^GTMSessionFetcherDidReceiveResponseDispositionBlock)(NSURLSessionResponseDisposition disposition); typedef void (^GTMSessionFetcherDidReceiveResponseBlock)(NSURLResponse *response, GTMSessionFetcherDidReceiveResponseDispositionBlock dispositionBlock); typedef void (^GTMSessionFetcherChallengeDispositionBlock)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * GTM_NULLABLE_TYPE credential); typedef void (^GTMSessionFetcherChallengeBlock)(GTMSessionFetcher *fetcher, NSURLAuthenticationChallenge *challenge, GTMSessionFetcherChallengeDispositionBlock dispositionBlock); typedef void (^GTMSessionFetcherWillRedirectResponse)(NSURLRequest * GTM_NULLABLE_TYPE redirectedRequest); typedef void (^GTMSessionFetcherWillRedirectBlock)(NSHTTPURLResponse *redirectResponse, NSURLRequest *redirectRequest, GTMSessionFetcherWillRedirectResponse response); typedef void (^GTMSessionFetcherAccumulateDataBlock)(NSData * GTM_NULLABLE_TYPE buffer); typedef void (^GTMSessionFetcherReceivedProgressBlock)(int64_t bytesWritten, int64_t totalBytesWritten); typedef void (^GTMSessionFetcherDownloadProgressBlock)(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); typedef void (^GTMSessionFetcherSendProgressBlock)(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); typedef void (^GTMSessionFetcherWillCacheURLResponseResponse)(NSCachedURLResponse * GTM_NULLABLE_TYPE cachedResponse); typedef void (^GTMSessionFetcherWillCacheURLResponseBlock)(NSCachedURLResponse *proposedResponse, GTMSessionFetcherWillCacheURLResponseResponse responseBlock); typedef void (^GTMSessionFetcherRetryResponse)(BOOL shouldRetry); typedef void (^GTMSessionFetcherRetryBlock)(BOOL suggestedWillRetry, NSError * GTM_NULLABLE_TYPE error, GTMSessionFetcherRetryResponse response); typedef void (^GTMSessionFetcherTestResponse)(NSHTTPURLResponse * GTM_NULLABLE_TYPE response, NSData * GTM_NULLABLE_TYPE data, NSError * GTM_NULLABLE_TYPE error); typedef void (^GTMSessionFetcherTestBlock)(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse); void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...); // Utility functions for applications self-identifying to servers via a // user-agent header // The "standard" user agent includes the application identifier, taken from the bundle, // followed by a space and the system version string. Pass nil to use +mainBundle as the source // of the bundle identifier. // // Applications may use this as a starting point for their own user agent strings, perhaps // with additional sections appended. Use GTMFetcherCleanedUserAgentString() below to // clean up any string being added to the user agent. NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle); // Make a generic name and version for the current application, like // com.example.MyApp/1.2.3 relying on the bundle identifier and the // CFBundleShortVersionString or CFBundleVersion. // // The bundle ID may be overridden as the base identifier string by // adding to the bundle's Info.plist a "GTMUserAgentID" key. // // If no bundle ID or override is available, the process name preceded // by "proc_" is used. NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle); // Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1" NSString *GTMFetcherSystemVersionString(void); // Make a parseable user-agent identifier from the given string, replacing whitespace // and commas with underscores, and removing other characters that may interfere // with parsing of the full user-agent string. // // For example, @"[My App]" would become @"My_App" NSString *GTMFetcherCleanedUserAgentString(NSString *str); // Grab the data from an input stream. Since streams cannot be assumed to be rewindable, // this may be destructive; the caller can try to rewind the stream (by setting the // NSStreamFileCurrentOffsetKey property) or can just use the NSData to make a new // NSInputStream. This function is intended to facilitate testing rather than be used in // production. // // This function operates synchronously on the current thread. Depending on how the // input stream is implemented, it may be appropriate to dispatch to a different // queue before calling this function. // // Failure is indicated by a returned data value of nil. NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError); #ifdef __cplusplus } // extern "C" #endif #if !GTM_USE_SESSION_FETCHER @protocol GTMHTTPFetcherServiceProtocol; #endif // This protocol allows abstract references to the fetcher service, primarily for // fetchers (which may be compiled without the fetcher service class present.) // // Apps should not need to use this protocol. @protocol GTMSessionFetcherServiceProtocol // This protocol allows us to call into the service without requiring // GTMSessionFetcherService sources in this project @property(atomic, strong) dispatch_queue_t callbackQueue; - (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher; - (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher; - (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher; - (void)fetcherDidStop:(GTMSessionFetcher *)fetcher; - (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; - (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; @property(atomic, assign) BOOL reuseSession; - (GTM_NULLABLE NSURLSession *)session; - (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; - (GTM_NULLABLE id)sessionDelegate; - (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; // Methods for compatibility with the old GTMHTTPFetcher. @property(readonly, strong, GTM_NULLABLE) NSOperationQueue *delegateQueue; @end // @protocol GTMSessionFetcherServiceProtocol #ifndef GTM_FETCHER_AUTHORIZATION_PROTOCOL #define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1 @protocol GTMFetcherAuthorizationProtocol @required // This protocol allows us to call the authorizer without requiring its sources // in this project. - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request delegate:(id)delegate didFinishSelector:(SEL)sel; - (void)stopAuthorization; - (void)stopAuthorizationForRequest:(NSURLRequest *)request; - (BOOL)isAuthorizingRequest:(NSURLRequest *)request; - (BOOL)isAuthorizedRequest:(NSURLRequest *)request; @property(strong, readonly, GTM_NULLABLE) NSString *userEmail; @optional // Indicate if authorization may be attempted. Even if this succeeds, // authorization may fail if the user's permissions have been revoked. @property(readonly) BOOL canAuthorize; // For development only, allow authorization of non-SSL requests, allowing // transmission of the bearer token unencrypted. @property(assign) BOOL shouldAuthorizeAllRequests; - (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request completionHandler:(void (^)(NSError * GTM_NULLABLE_TYPE error))handler; #if GTM_USE_SESSION_FETCHER @property (weak, GTM_NULLABLE) id fetcherService; #else @property (weak, GTM_NULLABLE) id fetcherService; #endif - (BOOL)primeForRefresh; @end #endif // GTM_FETCHER_AUTHORIZATION_PROTOCOL #if TARGET_OS_IPHONE // A protocol for an alternative target for messages from GTMSessionFetcher to UIApplication. // Set the target using +[GTMSessionFetcher setSubstituteUIApplication:] @protocol GTMUIApplicationProtocol - (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName expirationHandler:(void(^ __nullable)(void))handler; - (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier; @end #endif #pragma mark - // GTMSessionFetcher objects are used for async retrieval of an http get or post // // See additional comments at the beginning of this file @interface GTMSessionFetcher : NSObject // Create a fetcher // // fetcherWithRequest will return an autoreleased fetcher, but if // the connection is successfully created, the connection should retain the // fetcher for the life of the connection as well. So the caller doesn't have // to retain the fetcher explicitly unless they want to be able to cancel it. + (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request; // Convenience methods that make a request, like +fetcherWithRequest + (instancetype)fetcherWithURL:(NSURL *)requestURL; + (instancetype)fetcherWithURLString:(NSString *)requestURLString; // Methods for creating fetchers to continue previous fetches. + (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData; + (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier; // Returns an array of currently active fetchers for background sessions, // both restarted and newly created ones. + (GTM_NSArrayOf(GTMSessionFetcher *) *)fetchersForBackgroundSessions; // Designated initializer. // // Applications should create fetchers with a "fetcherWith..." method on a fetcher // service or a class method, not with this initializer. // // The configuration should typically be nil. Applications needing to customize // the configuration may do so by setting the configurationBlock property. - (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration; // The fetcher's request. This may not be set after beginFetch has been invoked. The request // may change due to redirects. @property(strong, GTM_NULLABLE) NSURLRequest *request; // Set a header field value on the request. Header field value changes will not // affect a fetch after the fetch has begun. - (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field; // The fetcher's request (deprecated.) // // Exposing a mutable object in the interface was convenient but a bad design decision due // to thread-safety requirements. Clients should use the request property and // setRequestValue:forHTTPHeaderField: instead. @property(atomic, readonly, GTM_NULLABLE) NSMutableURLRequest *mutableRequest GTMSESSION_DEPRECATE_ON_2016_SDKS("use 'request' or '-setRequestValue:forHTTPHeaderField:'"); // Data used for resuming a download task. @property(atomic, readonly, GTM_NULLABLE) NSData *downloadResumeData; // The configuration; this must be set before the fetch begins. If no configuration is // set or inherited from the fetcher service, then the fetcher uses an ephemeral config. // // NOTE: This property should typically be nil. Applications needing to customize // the configuration should do so by setting the configurationBlock property. // That allows the fetcher to pick an appropriate base configuration, with the // application setting only the configuration properties it needs to customize. @property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; // A block the client may use to customize the configuration used to create the session. // // This is called synchronously, either on the thread that begins the fetch or, during a retry, // on the main thread. The configuration block may be called repeatedly if multiple fetchers are // created. // // The configuration block is for modifying the NSURLSessionConfiguration only. // DO NOT change any fetcher properties in the configuration block. Fetcher properties // may be set in the fetcher service prior to fetcher creation, or on the fetcher prior // to invoking beginFetch. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; // A session is created as needed by the fetcher. A fetcher service object // may maintain sessions for multiple fetches to the same host. @property(atomic, strong, GTM_NULLABLE) NSURLSession *session; // The task in flight. @property(atomic, readonly, GTM_NULLABLE) NSURLSessionTask *sessionTask; // The background session identifier. @property(atomic, readonly, GTM_NULLABLE) NSString *sessionIdentifier; // Indicates a fetcher created to finish a background session task. @property(atomic, readonly) BOOL wasCreatedFromBackgroundSession; // Additional user-supplied data to encode into the session identifier. Since session identifier // length limits are unspecified, this should be kept small. Key names beginning with an underscore // are reserved for use by the fetcher. @property(atomic, strong, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *sessionUserInfo; // The human-readable description to be assigned to the task. @property(atomic, copy, GTM_NULLABLE) NSString *taskDescription; // The priority assigned to the task, if any. Use NSURLSessionTaskPriorityLow, // NSURLSessionTaskPriorityDefault, or NSURLSessionTaskPriorityHigh. @property(atomic, assign) float taskPriority; // The fetcher encodes information used to resume a session in the session identifier. // This method, intended for internal use returns the encoded information. The sessionUserInfo // dictionary is stored as identifier metadata. - (GTM_NULLABLE GTM_NSDictionaryOf(NSString *, NSString *) *)sessionIdentifierMetadata; #if TARGET_OS_IPHONE // The app should pass to this method the completion handler passed in the app delegate method // application:handleEventsForBackgroundURLSession:completionHandler: + (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler; #endif // Indicate that a newly created session should be a background session. // A new session identifier will be created by the fetcher. // // Warning: The only thing background sessions are for is rare download // of huge, batched files of data. And even just for those, there's a lot // of pain and hackery needed to get transfers to actually happen reliably // with background sessions. // // Don't try to upload or download in many background sessions, since the system // will impose an exponentially increasing time penalty to prevent the app from // getting too much background execution time. // // References: // // "Moving to Fewer, Larger Transfers" // https://forums.developer.apple.com/thread/14853 // // "NSURLSession’s Resume Rate Limiter" // https://forums.developer.apple.com/thread/14854 // // "Background Session Task state persistence" // https://forums.developer.apple.com/thread/11554 // @property(assign) BOOL useBackgroundSession; // Indicates if the fetcher was started using a background session. @property(atomic, readonly, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; // Indicates if uploads should use an upload task. This is always set for file or stream-provider // bodies, but may be set explicitly for NSData bodies. @property(atomic, assign) BOOL useUploadTask; // Indicates that the fetcher is using a session that may be shared with other fetchers. @property(atomic, readonly) BOOL canShareSession; // By default, the fetcher allows only secure (https) schemes unless this // property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. // // For example, during debugging when fetching from a development server that lacks SSL support, // this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files, // this may be set to @[ @"file" ]. // // This should be left as nil for release builds to avoid creating the opportunity for // leaking private user behavior and data. If a server is providing insecure URLs // for fetching by the client app, report the problem as server security & privacy bug. // // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. @property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; // By default, the fetcher prohibits localhost requests unless this property is set, // or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. // // For localhost requests, the URL scheme is not checked when this property is set. // // For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when // the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. @property(atomic, assign) BOOL allowLocalhostRequest; // By default, the fetcher requires valid server certs. This may be bypassed // temporarily for development against a test server with an invalid cert. @property(atomic, assign) BOOL allowInvalidServerCertificates; // Cookie storage object for this fetcher. If nil, the fetcher will use a static cookie // storage instance shared among fetchers. If this fetcher was created by a fetcher service // object, it will be set to use the service object's cookie storage. See Cookies section above for // the full discussion. // // Because as of Jan 2014 standalone instances of NSHTTPCookieStorage do not actually // store any cookies (Radar 15735276) we use our own subclass, GTMSessionCookieStorage, // to hold cookies in memory. @property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; // Setting the credential is optional; it is used if the connection receives // an authentication challenge. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; // Setting the proxy credential is optional; it is used if the connection // receives an authentication challenge from a proxy. @property(atomic, strong, GTM_NULLABLE) NSURLCredential *proxyCredential; // If body data, body file URL, or body stream provider is not set, then a GET request // method is assumed. @property(atomic, strong, GTM_NULLABLE) NSData *bodyData; // File to use as the request body. This forces use of an upload task. @property(atomic, strong, GTM_NULLABLE) NSURL *bodyFileURL; // Length of body to send, expected or actual. @property(atomic, readonly) int64_t bodyLength; // The body stream provider may be called repeatedly to provide a body. // Setting a body stream provider forces use of an upload task. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherBodyStreamProvider bodyStreamProvider; // Object to add authorization to the request, if needed. // // This may not be changed once beginFetch has been invoked. @property(atomic, strong, GTM_NULLABLE) id authorizer; // The service object that created and monitors this fetcher, if any. @property(atomic, strong) id service; // The host, if any, used to classify this fetcher in the fetcher service. @property(atomic, copy, GTM_NULLABLE) NSString *serviceHost; // The priority, if any, used for starting fetchers in the fetcher service. // // Lower values are higher priority; the default is 0, and values may // be negative or positive. This priority affects only the start order of // fetchers that are being delayed by a fetcher service when the running fetchers // exceeds the service's maxRunningFetchersPerHost. A priority of NSIntegerMin will // exempt this fetcher from delay. @property(atomic, assign) NSInteger servicePriority; // The delegate's optional didReceiveResponse block may be used to inspect or alter // the session task response. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock; // The delegate's optional challenge block may be used to inspect or alter // the session task challenge. // // If this block is not set, the fetcher's default behavior for the NSURLSessionTask // didReceiveChallenge: delegate method is to use the fetcher's respondToChallenge: method // which relies on the fetcher's credential and proxyCredential properties. // // Warning: This may be called repeatedly if the challenge fails. Check // challenge.previousFailureCount to identify repeated invocations. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; // The delegate's optional willRedirect block may be used to inspect or alter // the redirection. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillRedirectBlock willRedirectBlock; // The optional send progress block reports body bytes uploaded. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherSendProgressBlock sendProgressBlock; // The optional accumulate block may be set by clients wishing to accumulate data // themselves rather than let the fetcher append each buffer to an NSData. // // When this is called with nil data (such as on redirect) the client // should empty its accumulation buffer. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherAccumulateDataBlock accumulateDataBlock; // The optional received progress block may be used to monitor data // received from a data task. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherReceivedProgressBlock receivedProgressBlock; // The delegate's optional downloadProgress block may be used to monitor download // progress in writing to disk. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDownloadProgressBlock downloadProgressBlock; // The delegate's optional willCacheURLResponse block may be used to alter the cached // NSURLResponse. The user may prevent caching by passing nil to the block's response. // // This is called on the callback queue. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock; // Enable retrying; see comments at the top of this file. Setting // retryEnabled=YES resets the min and max retry intervals. @property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; // Retry block is optional for retries. // // If present, this block should call the response block with YES to cause a retry or NO to end the // fetch. // See comments at the top of this file. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; // Retry intervals must be strictly less than maxRetryInterval, else // they will be limited to maxRetryInterval and no further retries will // be attempted. Setting maxRetryInterval to 0.0 will reset it to the // default value, 60 seconds for downloads and 600 seconds for uploads. @property(atomic, assign) NSTimeInterval maxRetryInterval; // Starting retry interval. Setting minRetryInterval to 0.0 will reset it // to a random value between 1.0 and 2.0 seconds. Clients should normally not // set this except for unit testing. @property(atomic, assign) NSTimeInterval minRetryInterval; // Multiplier used to increase the interval between retries, typically 2.0. // Clients should not need to set this. @property(atomic, assign) double retryFactor; // Number of retries attempted. @property(atomic, readonly) NSUInteger retryCount; // Interval delay to precede next retry. @property(atomic, readonly) NSTimeInterval nextRetryInterval; #if GTM_BACKGROUND_TASK_FETCHING // Skip use of a UIBackgroundTask, thus requiring fetches to complete when the app is in the // foreground. // // Targets should define GTM_BACKGROUND_TASK_FETCHING to 0 to avoid use of a UIBackgroundTask // on iOS to allow fetches to complete in the background. This property is available when // it's not practical to set the preprocessor define. @property(atomic, assign) BOOL skipBackgroundTask; #endif // GTM_BACKGROUND_TASK_FETCHING // Begin fetching the request // // The delegate may optionally implement the callback or pass nil for the selector or handler. // // The delegate and all callback blocks are retained between the beginFetch call until after the // finish callback, or until the fetch is stopped. // // An error is passed to the callback for server statuses 300 or // higher, with the status stored as the error object's code. // // finishedSEL has a signature like: // - (void)fetcher:(GTMSessionFetcher *)fetcher // finishedWithData:(NSData *)data // error:(NSError *)error; // // If the application has specified a destinationFileURL or an accumulateDataBlock // for the fetcher, the data parameter passed to the callback will be nil. - (void)beginFetchWithDelegate:(GTM_NULLABLE id)delegate didFinishSelector:(GTM_NULLABLE SEL)finishedSEL; - (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler; // Returns YES if this fetcher is in the process of fetching a URL. @property(atomic, readonly, getter=isFetching) BOOL fetching; // Cancel the fetch of the request that's currently in progress. The completion handler // will not be called. - (void)stopFetching; // A block to be called when the fetch completes. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherCompletionHandler completionHandler; // A block to be called if download resume data becomes available. @property(atomic, strong, GTM_NULLABLE) void (^resumeDataBlock)(NSData *); // Return the status code from the server response. @property(atomic, readonly) NSInteger statusCode; // Return the http headers from the response. @property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *responseHeaders; // The response, once it's been received. @property(atomic, strong, readonly, GTM_NULLABLE) NSURLResponse *response; // Bytes downloaded so far. @property(atomic, readonly) int64_t downloadedLength; // Buffer of currently-downloaded data, if available. @property(atomic, readonly, strong, GTM_NULLABLE) NSData *downloadedData; // Local path to which the downloaded file will be moved. // // If a file already exists at the path, it will be overwritten. // Will create the enclosing folders if they are not present. @property(atomic, strong, GTM_NULLABLE) NSURL *destinationFileURL; // The time this fetcher originally began fetching. This is useful as a time // barrier for ignoring irrelevant fetch notifications or callbacks. @property(atomic, strong, readonly, GTM_NULLABLE) NSDate *initialBeginFetchDate; // userData is retained solely for the convenience of the client. @property(atomic, strong, GTM_NULLABLE) id userData; // Stored property values are retained solely for the convenience of the client. @property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; - (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key; // Pass nil for obj to remove the property. - (GTM_NULLABLE id)propertyForKey:(NSString *)key; - (void)addPropertiesFromDictionary:(GTM_NSDictionaryOf(NSString *, id) *)dict; // Comments are useful for logging, so are strongly recommended for each fetcher. @property(atomic, copy, GTM_NULLABLE) NSString *comment; - (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2); // Log of request and response, if logging is enabled @property(atomic, copy, GTM_NULLABLE) NSString *log; // Callbacks are run on this queue. If none is supplied, the main queue is used. @property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; // The queue used internally by the session to invoke its delegate methods in the fetcher. // // Application callbacks are always called by the fetcher on the callbackQueue above, // not on this queue. Apps should generally not change this queue. // // The default delegate queue is the main queue. // // This value is ignored after the session has been created, so this // property should be set in the fetcher service rather in the fetcher as it applies // to a shared session. @property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; // Spin the run loop or sleep the thread, discarding events, until the fetch has completed. // // This is only for use in testing or in tools without a user interface. // // Note: Synchronous fetches should never be used by shipping apps; they are // sufficient reason for rejection from the app store. // // Returns NO if timed out. - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds; // Test block is optional for testing. // // If present, this block will cause the fetcher to skip starting the session, and instead // use the test block response values when calling the completion handler and delegate code. // // Test code can set this on the fetcher or on the fetcher service. For testing libraries // that use a fetcher without exposing either the fetcher or the fetcher service, the global // method setGlobalTestBlock: will set the block for all fetchers that do not have a test // block set. // // The test code can pass nil for all response parameters to indicate that the fetch // should proceed. // // Applications can exclude test block support by setting GTM_DISABLE_FETCHER_TEST_BLOCK. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; + (void)setGlobalTestBlock:(GTM_NULLABLE GTMSessionFetcherTestBlock)block; #if TARGET_OS_IPHONE // For testing or to override UIApplication invocations, apps may specify an alternative // target for messages to UIApplication. + (void)setSubstituteUIApplication:(nullable id)substituteUIApplication; + (nullable id)substituteUIApplication; #endif // TARGET_OS_IPHONE // Exposed for testing. + (GTMSessionCookieStorage *)staticCookieStorage; + (BOOL)appAllowsInsecureRequests; #if STRIP_GTM_FETCH_LOGGING // If logging is stripped, provide a stub for the main method // for controlling logging. + (void)setLoggingEnabled:(BOOL)flag; + (BOOL)isLoggingEnabled; #else // These methods let an application log specific body text, such as the text description of a binary // request or response. The application should set the fetcher to defer response body logging until // the response has been received and the log response body has been set by the app. For example: // // fetcher.logRequestBody = [binaryObject stringDescription]; // fetcher.deferResponseBodyLogging = YES; // [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { // if (error == nil) { // fetcher.logResponseBody = [[[MyThing alloc] initWithData:data] stringDescription]; // } // fetcher.deferResponseBodyLogging = NO; // }]; @property(atomic, copy, GTM_NULLABLE) NSString *logRequestBody; @property(atomic, assign) BOOL deferResponseBodyLogging; @property(atomic, copy, GTM_NULLABLE) NSString *logResponseBody; // Internal logging support. @property(atomic, readonly) NSData *loggedStreamData; @property(atomic, assign) BOOL hasLoggedError; @property(atomic, strong, GTM_NULLABLE) NSURL *redirectedFromURL; - (void)appendLoggedStreamData:(NSData *)dataToAdd; - (void)clearLoggedStreamData; #endif // STRIP_GTM_FETCH_LOGGING @end @interface GTMSessionFetcher (BackwardsCompatibilityOnly) // Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. // This method is just for compatibility with the old GTMHTTPFetcher class. - (void)setCookieStorageMethod:(NSInteger)method; @end // Until we can just instantiate NSHTTPCookieStorage for local use, we'll // implement all the public methods ourselves. This stores cookies only in // memory. Additional methods are provided for testing. // // iOS 9/OS X 10.11 added +[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:] // which may also be used to create cookie storage. @interface GTMSessionCookieStorage : NSHTTPCookieStorage // Add the array off cookies to the storage, replacing duplicates. // Also removes expired cookies from the storage. - (void)setCookies:(GTM_NULLABLE GTM_NSArrayOf(NSHTTPCookie *) *)cookies; - (void)removeAllCookies; @end // Macros to monitor synchronization blocks in debug builds. // These report problems using GTMSessionCheckDebug. // // GTMSessionMonitorSynchronized Start monitoring a top-level-only // @sync scope. // GTMSessionMonitorRecursiveSynchronized Start monitoring a top-level or // recursive @sync scope. // GTMSessionCheckSynchronized Verify that the current execution // is inside a @sync scope. // GTMSessionCheckNotSynchronized Verify that the current execution // is not inside a @sync scope. // // Example usage: // // - (void)myExternalMethod { // @synchronized(self) { // GTMSessionMonitorSynchronized(self) // // - (void)myInternalMethod { // GTMSessionCheckSynchronized(self); // // - (void)callMyCallbacks { // GTMSessionCheckNotSynchronized(self); // // GTMSessionCheckNotSynchronized is available for verifying the code isn't // in a deadlockable @sync state when posting notifications and invoking // callbacks. Don't use GTMSessionCheckNotSynchronized immediately before a // @sync scope; the normal recursiveness check of GTMSessionMonitorSynchronized // can catch those. #ifdef __OBJC__ #if DEBUG #define __GTMSessionMonitorSynchronizedVariableInner(varname, counter) \ varname ## counter #define __GTMSessionMonitorSynchronizedVariable(varname, counter) \ __GTMSessionMonitorSynchronizedVariableInner(varname, counter) #define GTMSessionMonitorSynchronized(obj) \ NS_VALID_UNTIL_END_OF_SCOPE id \ __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ allowRecursive:NO \ functionName:__func__] #define GTMSessionMonitorRecursiveSynchronized(obj) \ NS_VALID_UNTIL_END_OF_SCOPE id \ __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ allowRecursive:YES \ functionName:__func__] #define GTMSessionCheckSynchronized(obj) { \ GTMSESSION_ASSERT_DEBUG( \ [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ @"GTMSessionCheckSynchronized(" #obj ") failed: not sync'd" \ @" on " #obj " in %s. Call stack:\n%@", \ __func__, [NSThread callStackSymbols]); \ } #define GTMSessionCheckNotSynchronized(obj) { \ GTMSESSION_ASSERT_DEBUG( \ ![GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ @"GTMSessionCheckNotSynchronized(" #obj ") failed: was sync'd" \ @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \ [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ [NSThread callStackSymbols]); \ } // GTMSessionSyncMonitorInternal is a private class that keeps track of the // beginning and end of synchronized scopes. // // This class should not be used directly, but only via the // GTMSessionMonitorSynchronized macro. @interface GTMSessionSyncMonitorInternal : NSObject - (instancetype)initWithSynchronizationObject:(id)object allowRecursive:(BOOL)allowRecursive functionName:(const char *)functionName; // Return the names of the functions that hold sync on the object, or nil if none. + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object; @end #else #define GTMSessionMonitorSynchronized(obj) do { } while (0) #define GTMSessionMonitorRecursiveSynchronized(obj) do { } while (0) #define GTMSessionCheckSynchronized(obj) do { } while (0) #define GTMSessionCheckNotSynchronized(obj) do { } while (0) #endif // !DEBUG #endif // __OBJC__ GTM_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif #import "GTMSessionFetcher.h" #import #ifndef STRIP_GTM_FETCH_LOGGING #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. #endif GTM_ASSUME_NONNULL_BEGIN NSString *const kGTMSessionFetcherStartedNotification = @"kGTMSessionFetcherStartedNotification"; NSString *const kGTMSessionFetcherStoppedNotification = @"kGTMSessionFetcherStoppedNotification"; NSString *const kGTMSessionFetcherRetryDelayStartedNotification = @"kGTMSessionFetcherRetryDelayStartedNotification"; NSString *const kGTMSessionFetcherRetryDelayStoppedNotification = @"kGTMSessionFetcherRetryDelayStoppedNotification"; NSString *const kGTMSessionFetcherCompletionInvokedNotification = @"kGTMSessionFetcherCompletionInvokedNotification"; NSString *const kGTMSessionFetcherCompletionDataKey = @"data"; NSString *const kGTMSessionFetcherCompletionErrorKey = @"error"; NSString *const kGTMSessionFetcherErrorDomain = @"com.google.GTMSessionFetcher"; NSString *const kGTMSessionFetcherStatusDomain = @"com.google.HTTPStatus"; NSString *const kGTMSessionFetcherStatusDataKey = @"data"; // data returned with a kGTMSessionFetcherStatusDomain error NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey = @"kGTMSessionFetcherNumberOfRetriesDoneKey"; NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey = @"kGTMSessionFetcherElapsedIntervalWithRetriesKey"; static NSString *const kGTMSessionIdentifierPrefix = @"com.google.GTMSessionFetcher"; static NSString *const kGTMSessionIdentifierDestinationFileURLMetadataKey = @"_destURL"; static NSString *const kGTMSessionIdentifierBodyFileURLMetadataKey = @"_bodyURL"; // The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH), // 1 minute for downloads. static const NSTimeInterval kUnsetMaxRetryInterval = -1.0; static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0; static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.; #ifdef GTMSESSION_PERSISTED_DESTINATION_KEY // Projects using unique class names should also define a unique persisted destination key. static NSString * const kGTMSessionFetcherPersistedDestinationKey = GTMSESSION_PERSISTED_DESTINATION_KEY; #else static NSString * const kGTMSessionFetcherPersistedDestinationKey = @"com.google.GTMSessionFetcher.downloads"; #endif GTM_ASSUME_NONNULL_END // // GTMSessionFetcher // #if 0 #define GTM_LOG_BACKGROUND_SESSION(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) #else #define GTM_LOG_BACKGROUND_SESSION(...) #endif #ifndef GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY #if (TARGET_OS_TV \ || TARGET_OS_WATCH \ || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) #define GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY 1 #endif #endif @interface GTMSessionFetcher () @property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadedData; @property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadResumeData; #if GTM_BACKGROUND_TASK_FETCHING @property(assign, atomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier; #endif @property(atomic, readwrite, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; @end #if !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionFetcher (GTMSessionFetcherLoggingInternal) - (void)logFetchWithError:(NSError *)error; - (void)logNowWithError:(GTM_NULLABLE NSError *)error; - (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; - (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: (GTMSessionFetcherBodyStreamProvider)streamProvider; @end #endif // !GTMSESSION_BUILD_COMBINED_SOURCES GTM_ASSUME_NONNULL_BEGIN static NSTimeInterval InitialMinRetryInterval(void) { return 1.0 + ((double)(arc4random_uniform(0x0FFFF)) / (double) 0x0FFFF); } static BOOL IsLocalhost(NSString * GTM_NULLABLE_TYPE host) { // We check if there's host, and then make the comparisons. if (host == nil) return NO; return ([host caseInsensitiveCompare:@"localhost"] == NSOrderedSame || [host isEqual:@"::1"] || [host isEqual:@"127.0.0.1"]); } static GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE gGlobalTestBlock; @implementation GTMSessionFetcher { NSMutableURLRequest *_request; // after beginFetch, changed only in delegate callbacks BOOL _useUploadTask; // immutable after beginFetch NSURL *_bodyFileURL; // immutable after beginFetch GTMSessionFetcherBodyStreamProvider _bodyStreamProvider; // immutable after beginFetch NSURLSession *_session; BOOL _shouldInvalidateSession; // immutable after beginFetch NSURLSession *_sessionNeedingInvalidation; NSURLSessionConfiguration *_configuration; NSURLSessionTask *_sessionTask; NSString *_taskDescription; float _taskPriority; NSURLResponse *_response; NSString *_sessionIdentifier; BOOL _wasCreatedFromBackgroundSession; BOOL _didCreateSessionIdentifier; NSString *_sessionIdentifierUUID; BOOL _userRequestedBackgroundSession; BOOL _usingBackgroundSession; NSMutableData * GTM_NULLABLE_TYPE _downloadedData; NSError *_downloadFinishedError; NSData *_downloadResumeData; // immutable after construction NSURL *_destinationFileURL; int64_t _downloadedLength; NSURLCredential *_credential; // username & password NSURLCredential *_proxyCredential; // credential supplied to proxy servers BOOL _isStopNotificationNeeded; // set when start notification has been sent BOOL _isUsingTestBlock; // set when a test block was provided (remains set when the block is released) id _userData; // retained, if set by caller NSMutableDictionary *_properties; // more data retained for caller dispatch_queue_t _callbackQueue; dispatch_group_t _callbackGroup; // read-only after creation NSOperationQueue *_delegateQueue; // immutable after beginFetch id _authorizer; // immutable after beginFetch // The service object that created and monitors this fetcher, if any. id _service; // immutable; set by the fetcher service upon creation NSString *_serviceHost; NSInteger _servicePriority; // immutable after beginFetch BOOL _hasStoppedFetching; // counterpart to _initialBeginFetchDate BOOL _userStoppedFetching; BOOL _isRetryEnabled; // user wants auto-retry NSTimer *_retryTimer; NSUInteger _retryCount; NSTimeInterval _maxRetryInterval; // default 60 (download) or 600 (upload) seconds NSTimeInterval _minRetryInterval; // random between 1 and 2 seconds NSTimeInterval _retryFactor; // default interval multiplier is 2 NSTimeInterval _lastRetryInterval; NSDate *_initialBeginFetchDate; // date that beginFetch was first invoked; immutable after initial beginFetch NSDate *_initialRequestDate; // date of first request to the target server (ignoring auth) BOOL _hasAttemptedAuthRefresh; // accessed only in shouldRetryNowForStatus: NSString *_comment; // comment for log NSString *_log; #if !STRIP_GTM_FETCH_LOGGING NSMutableData *_loggedStreamData; NSURL *_redirectedFromURL; NSString *_logRequestBody; NSString *_logResponseBody; BOOL _hasLoggedError; BOOL _deferResponseBodyLogging; #endif } #if !GTMSESSION_UNIT_TESTING + (void)load { [self fetchersForBackgroundSessions]; } #endif + (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request { return [[self alloc] initWithRequest:request configuration:nil]; } + (instancetype)fetcherWithURL:(NSURL *)requestURL { return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; } + (instancetype)fetcherWithURLString:(NSString *)requestURLString { return [self fetcherWithURL:(NSURL *)[NSURL URLWithString:requestURLString]]; } + (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData { GTMSessionFetcher *fetcher = [self fetcherWithRequest:nil]; fetcher.comment = @"Resuming download"; fetcher.downloadResumeData = resumeData; return fetcher; } + (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier { GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; if (!fetcher && [sessionIdentifier hasPrefix:kGTMSessionIdentifierPrefix]) { fetcher = [self fetcherWithRequest:nil]; [fetcher setSessionIdentifier:sessionIdentifier]; [sessionIdentifierToFetcherMap setObject:fetcher forKey:sessionIdentifier]; fetcher->_wasCreatedFromBackgroundSession = YES; [fetcher setCommentWithFormat:@"Resuming %@", fetcher && fetcher->_sessionIdentifierUUID ? fetcher->_sessionIdentifierUUID : @"?"]; } return fetcher; } + (NSMapTable *)sessionIdentifierToFetcherMap { // TODO: What if a service is involved in creating the fetcher? Currently, when re-creating // fetchers, if a service was involved, it is not re-created. Should the service maintain a map? static NSMapTable *gSessionIdentifierToFetcherMap = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ gSessionIdentifierToFetcherMap = [NSMapTable strongToWeakObjectsMapTable]; }); return gSessionIdentifierToFetcherMap; } #if !GTM_ALLOW_INSECURE_REQUESTS + (BOOL)appAllowsInsecureRequests { // If the main bundle Info.plist key NSAppTransportSecurity is present, and it specifies // NSAllowsArbitraryLoads, then we need to explicitly enforce secure schemes. #if GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY static BOOL allowsInsecureRequests; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSBundle *mainBundle = [NSBundle mainBundle]; NSDictionary *appTransportSecurity = [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; allowsInsecureRequests = [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue]; }); return allowsInsecureRequests; #else // For builds targeting iOS 8 or 10.10 and earlier, we want to require fetcher // security checks. return YES; #endif // GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY } #else // GTM_ALLOW_INSECURE_REQUESTS + (BOOL)appAllowsInsecureRequests { return YES; } #endif // !GTM_ALLOW_INSECURE_REQUESTS - (instancetype)init { return [self initWithRequest:nil configuration:nil]; } - (instancetype)initWithRequest:(NSURLRequest *)request { return [self initWithRequest:request configuration:nil]; } - (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration { self = [super init]; if (self) { if (![NSURLSession class]) { Class oldFetcherClass = NSClassFromString(@"GTMHTTPFetcher"); if (oldFetcherClass && request) { self = [[oldFetcherClass alloc] initWithRequest:(NSURLRequest *)request]; } else { self = nil; } return self; } #if GTM_BACKGROUND_TASK_FETCHING _backgroundTaskIdentifier = UIBackgroundTaskInvalid; #endif _request = [request mutableCopy]; _configuration = configuration; NSData *bodyData = request.HTTPBody; if (bodyData) { _bodyLength = (int64_t)bodyData.length; } else { _bodyLength = NSURLSessionTransferSizeUnknown; } _callbackQueue = dispatch_get_main_queue(); _callbackGroup = dispatch_group_create(); _delegateQueue = [NSOperationQueue mainQueue]; _minRetryInterval = InitialMinRetryInterval(); _maxRetryInterval = kUnsetMaxRetryInterval; _taskPriority = -1.0f; // Valid values if set are 0.0...1.0. #if !STRIP_GTM_FETCH_LOGGING // Encourage developers to set the comment property or use // setCommentWithFormat: by providing a default string. _comment = @"(No fetcher comment set)"; #endif } return self; } - (id)copyWithZone:(NSZone *)zone { // disallow use of fetchers in a copy property [self doesNotRecognizeSelector:_cmd]; return nil; } - (NSString *)description { NSString *requestStr = self.request.URL.description; if (requestStr.length == 0) { if (self.downloadResumeData.length > 0) { requestStr = @""; } else if (_wasCreatedFromBackgroundSession) { requestStr = @""; } else { requestStr = @""; } } return [NSString stringWithFormat:@"%@ %p (%@)", [self class], self, requestStr]; } - (void)dealloc { GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, @"unbalanced fetcher notification for %@", _request.URL); [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; // Note: if a session task or a retry timer was pending, then this instance // would be retained by those so it wouldn't be getting dealloc'd, // hence we don't need to stopFetch here } #pragma mark - // Begin fetching the URL (or begin a retry fetch). The delegate is retained // for the duration of the fetch connection. - (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler { GTMSessionCheckNotSynchronized(self); _completionHandler = [handler copy]; // The user may have called setDelegate: earlier if they want to use other // delegate-style callbacks during the fetch; otherwise, the delegate is nil, // which is fine. [self beginFetchMayDelay:YES mayAuthorize:YES]; } - (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(GTM_NULLABLE_TYPE id)target didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { GTMSessionFetcherAssertValidSelector(target, finishedSelector, @encode(GTMSessionFetcher *), @encode(NSData *), @encode(NSError *), 0); GTMSessionFetcherCompletionHandler completionHandler = ^(NSData *data, NSError *error) { if (target && finishedSelector) { id selfArg = self; // Placate ARC. NSMethodSignature *sig = [target methodSignatureForSelector:finishedSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; [invocation setSelector:(SEL)finishedSelector]; [invocation setTarget:target]; [invocation setArgument:&selfArg atIndex:2]; [invocation setArgument:&data atIndex:3]; [invocation setArgument:&error atIndex:4]; [invocation invoke]; } }; return completionHandler; } - (void)beginFetchWithDelegate:(GTM_NULLABLE_TYPE id)target didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { GTMSessionCheckNotSynchronized(self); GTMSessionFetcherCompletionHandler handler = [self completionHandlerWithTarget:target didFinishSelector:finishedSelector]; [self beginFetchWithCompletionHandler:handler]; } - (void)beginFetchMayDelay:(BOOL)mayDelay mayAuthorize:(BOOL)mayAuthorize { // This is the internal entry point for re-starting fetches. GTMSessionCheckNotSynchronized(self); NSMutableURLRequest *fetchRequest = _request; // The request property is now externally immutable. NSURL *fetchRequestURL = fetchRequest.URL; NSString *priorSessionIdentifier = self.sessionIdentifier; // A utility block for creating error objects when we fail to start the fetch. NSError *(^beginFailureError)(NSInteger) = ^(NSInteger code){ NSString *urlString = fetchRequestURL.absoluteString; NSDictionary *userInfo = @{ NSURLErrorFailingURLStringErrorKey : (urlString ? urlString : @"(missing URL)") }; return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain code:code userInfo:userInfo]; }; // Catch delegate queue maxConcurrentOperationCount values other than 1, particularly // NSOperationQueueDefaultMaxConcurrentOperationCount (-1), to avoid the additional complexity // of simultaneous or out-of-order delegate callbacks. GTMSESSION_ASSERT_DEBUG(_delegateQueue.maxConcurrentOperationCount == 1, @"delegate queue %@ should support one concurrent operation, not %zd", _delegateQueue.name, _delegateQueue.maxConcurrentOperationCount); if (!_initialBeginFetchDate) { // This ivar is set only here on the initial beginFetch so need not be synchronized. _initialBeginFetchDate = [[NSDate alloc] init]; } if (self.sessionTask != nil) { // If cached fetcher returned through fetcherWithSessionIdentifier:, then it's // already begun, but don't consider this a failure, since the user need not know this. if (self.sessionIdentifier != nil) { return; } GTMSESSION_ASSERT_DEBUG(NO, @"Fetch object %@ being reused; this should never happen", self); [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; return; } if (fetchRequestURL == nil && !_downloadResumeData && !priorSessionIdentifier) { GTMSESSION_ASSERT_DEBUG(NO, @"Beginning a fetch requires a request with a URL"); [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; return; } // We'll respect the user's request for a background session (unless this is // an upload fetcher, which does its initial request foreground.) self.usingBackgroundSession = self.useBackgroundSession && [self canFetchWithBackgroundSession]; NSURL *bodyFileURL = self.bodyFileURL; if (bodyFileURL) { NSError *fileCheckError; if (![bodyFileURL checkResourceIsReachableAndReturnError:&fileCheckError]) { // This assert fires when the file being uploaded no longer exists once // the fetcher is ready to start the upload. GTMSESSION_ASSERT_DEBUG_OR_LOG(0, @"Body file is unreachable: %@\n %@", bodyFileURL.path, fileCheckError); [self failToBeginFetchWithError:fileCheckError]; return; } } NSString *requestScheme = fetchRequestURL.scheme; BOOL isDataRequest = [requestScheme isEqual:@"data"]; if (isDataRequest) { // NSURLSession does not support data URLs in background sessions. #if DEBUG if (priorSessionIdentifier || self.sessionIdentifier) { GTMSESSION_LOG_DEBUG(@"Converting background to foreground session for %@", fetchRequest); } #endif [self setSessionIdentifierInternal:nil]; self.useBackgroundSession = NO; } #if GTM_ALLOW_INSECURE_REQUESTS BOOL shouldCheckSecurity = NO; #else BOOL shouldCheckSecurity = (fetchRequestURL != nil && !isDataRequest && [[self class] appAllowsInsecureRequests]); #endif if (shouldCheckSecurity) { // Allow https only for requests, unless overridden by the client. // // Non-https requests may too easily be snooped, so we disallow them by default. // // file: and data: schemes are usually safe if they are hardcoded in the client or provided // by a trusted source, but since it's fairly rare to need them, it's safest to make clients // explicitly whitelist them. BOOL isSecure = requestScheme != nil && [requestScheme caseInsensitiveCompare:@"https"] == NSOrderedSame; if (!isSecure) { BOOL allowRequest = NO; NSString *host = fetchRequestURL.host; // Check schemes first. A file scheme request may be allowed here, or as a localhost request. for (NSString *allowedScheme in _allowedInsecureSchemes) { if (requestScheme != nil && [requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) { allowRequest = YES; break; } } if (!allowRequest) { // Check for localhost requests. Security checks only occur for non-https requests, so // this check won't happen for an https request to localhost. BOOL isLocalhostRequest = (host.length == 0 && [fetchRequestURL isFileURL]) || IsLocalhost(host); if (isLocalhostRequest) { if (self.allowLocalhostRequest) { allowRequest = YES; } else { GTMSESSION_ASSERT_DEBUG(NO, @"Fetch request for localhost but fetcher" @" allowLocalhostRequest is not set: %@", fetchRequestURL); } } else { GTMSESSION_ASSERT_DEBUG(NO, @"Insecure fetch request has a scheme (%@)" @" not found in fetcher allowedInsecureSchemes (%@): %@", requestScheme, _allowedInsecureSchemes ?: @" @[] ", fetchRequestURL); } } if (!allowRequest) { #if !DEBUG NSLog(@"Insecure fetch disallowed for %@", fetchRequestURL.description ?: @"nil request URL"); #endif [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorInsecureRequest)]; return; } } // !isSecure } // (requestURL != nil) && !isDataRequest if (self.cookieStorage == nil) { self.cookieStorage = [[self class] staticCookieStorage]; } BOOL isRecreatingSession = (self.sessionIdentifier != nil) && (fetchRequest == nil); self.canShareSession = !isRecreatingSession && !self.usingBackgroundSession; if (!self.session && self.canShareSession) { self.session = [_service sessionForFetcherCreation]; // If _session is nil, then the service's session creation semaphore will block // until this fetcher invokes fetcherDidCreateSession: below, so this *must* invoke // that method, even if the session fails to be created. } if (!self.session) { // Create a session. if (!_configuration) { if (priorSessionIdentifier || self.usingBackgroundSession) { NSString *sessionIdentifier = priorSessionIdentifier; if (!sessionIdentifier) { sessionIdentifier = [self createSessionIdentifierWithMetadata:nil]; } NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; [sessionIdentifierToFetcherMap setObject:self forKey:self.sessionIdentifier]; #if (TARGET_OS_TV \ || TARGET_OS_WATCH \ || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)) // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name. _configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; #elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) \ || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0) // Do a runtime check to avoid a deprecation warning about using // +backgroundSessionConfiguration: on iOS 8. if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) { // Running on iOS 8+/OS X 10.10+. _configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; } else { // Running on iOS 7/OS X 10.9. _configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; } #else // Building with an SDK earlier than iOS 8/OS X 10.10. _configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; #endif self.usingBackgroundSession = YES; self.canShareSession = NO; } else { _configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; } #if !GTM_ALLOW_INSECURE_REQUESTS _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12; #endif } // !_configuration _configuration.HTTPCookieStorage = self.cookieStorage; if (_configurationBlock) { _configurationBlock(self, _configuration); } id delegate = [_service sessionDelegate]; if (!delegate || !self.canShareSession) { delegate = self; } self.session = [NSURLSession sessionWithConfiguration:_configuration delegate:delegate delegateQueue:self.sessionDelegateQueue]; GTMSESSION_ASSERT_DEBUG(self.session, @"Couldn't create session"); // Tell the service about the session created by this fetcher. This also signals the // service's semaphore to allow other fetchers to request this session. [_service fetcherDidCreateSession:self]; // If this assertion fires, the client probably tried to use a session identifier that was // already used. The solution is to make the client use a unique identifier (or better yet let // the session fetcher assign the identifier). GTMSESSION_ASSERT_DEBUG(self.session.delegate == delegate, @"Couldn't assign delegate."); if (self.session) { BOOL isUsingSharedDelegate = (delegate != self); if (!isUsingSharedDelegate) { _shouldInvalidateSession = YES; } } } if (isRecreatingSession) { _shouldInvalidateSession = YES; // Let's make sure there are tasks still running or if not that we get a callback from a // completed one; otherwise, we assume the tasks failed. // This is the observed behavior perhaps 25% of the time within the Simulator running 7.0.3 on // exiting the app after starting an upload and relaunching the app if we manage to relaunch // after the task has completed, but before the system relaunches us in the background. [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { if (dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0) { double const kDelayInSeconds = 1.0; // We should get progress indication or completion soon dispatch_time_t checkForFeedbackDelay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDelayInSeconds * NSEC_PER_SEC)); dispatch_after(checkForFeedbackDelay, dispatch_get_main_queue(), ^{ if (!self.sessionTask && !fetchRequest) { // If our task and/or request haven't been restored, then we assume task feedback lost. [self removePersistedBackgroundSessionFromDefaults]; NSError *sessionError = [NSError errorWithDomain:kGTMSessionFetcherErrorDomain code:GTMSessionFetcherErrorBackgroundFetchFailed userInfo:nil]; [self failToBeginFetchWithError:sessionError]; } }); } }]; return; } self.downloadedData = nil; self.downloadedLength = 0; if (_servicePriority == NSIntegerMin) { mayDelay = NO; } if (mayDelay && _service) { BOOL shouldFetchNow = [_service fetcherShouldBeginFetching:self]; if (!shouldFetchNow) { // The fetch is deferred, but will happen later. // // If this session is held by the fetcher service, clear the session now so that we don't // assume it's still valid after the fetcher is restarted. if (self.canShareSession) { self.session = nil; } return; } } NSString *effectiveHTTPMethod = [fetchRequest valueForHTTPHeaderField:@"X-HTTP-Method-Override"]; if (effectiveHTTPMethod == nil) { effectiveHTTPMethod = fetchRequest.HTTPMethod; } BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil || [effectiveHTTPMethod isEqual:@"GET"]); BOOL needsUploadTask = (self.useUploadTask || self.bodyFileURL || self.bodyStreamProvider); if (_bodyData || self.bodyStreamProvider || fetchRequest.HTTPBodyStream) { if (isEffectiveHTTPGet) { fetchRequest.HTTPMethod = @"POST"; isEffectiveHTTPGet = NO; } if (_bodyData) { if (!needsUploadTask) { fetchRequest.HTTPBody = _bodyData; } #if !STRIP_GTM_FETCH_LOGGING } else if (fetchRequest.HTTPBodyStream) { if ([self respondsToSelector:@selector(loggedInputStreamForInputStream:)]) { fetchRequest.HTTPBodyStream = [self performSelector:@selector(loggedInputStreamForInputStream:) withObject:fetchRequest.HTTPBodyStream]; } #endif } } // We authorize after setting up the http method and body in the request // because OAuth 1 may need to sign the request body if (mayAuthorize && _authorizer && !isDataRequest) { BOOL isAuthorized = [_authorizer isAuthorizedRequest:fetchRequest]; if (!isAuthorized) { // Authorization needed. // // If this session is held by the fetcher service, clear the session now so that we don't // assume it's still valid after authorization completes. if (self.canShareSession) { self.session = nil; } // Authorizing the request will recursively call this beginFetch:mayDelay: // or failToBeginFetchWithError:. [self authorizeRequest]; return; } } // set the default upload or download retry interval, if necessary if ([self isRetryEnabled] && self.maxRetryInterval <= 0) { if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) { [self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval]; } else { [self setMaxRetryInterval:kDefaultMaxUploadRetryInterval]; } } // finally, start the connection NSURLSessionTask *newSessionTask; BOOL needsDataAccumulator = NO; if (_downloadResumeData) { newSessionTask = [_session downloadTaskWithResumeData:_downloadResumeData]; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed downloadTaskWithResumeData for %@, resume data %tu bytes", _session, _downloadResumeData.length); } else if (_destinationFileURL && !isDataRequest) { newSessionTask = [_session downloadTaskWithRequest:fetchRequest]; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed downloadTaskWithRequest for %@, %@", _session, fetchRequest); } else if (needsUploadTask) { if (bodyFileURL) { newSessionTask = [_session uploadTaskWithRequest:fetchRequest fromFile:bodyFileURL]; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed uploadTaskWithRequest for %@, %@, file %@", _session, fetchRequest, bodyFileURL.path); } else if (self.bodyStreamProvider) { newSessionTask = [_session uploadTaskWithStreamedRequest:fetchRequest]; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed uploadTaskWithStreamedRequest for %@, %@", _session, fetchRequest); } else { GTMSESSION_ASSERT_DEBUG_OR_LOG(_bodyData != nil, @"Upload task needs body data, %@", fetchRequest); newSessionTask = [_session uploadTaskWithRequest:fetchRequest fromData:(NSData * GTM_NONNULL_TYPE)_bodyData]; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed uploadTaskWithRequest for %@, %@, body data %tu bytes", _session, fetchRequest, _bodyData.length); } needsDataAccumulator = YES; } else { newSessionTask = [_session dataTaskWithRequest:fetchRequest]; needsDataAccumulator = YES; GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed dataTaskWithRequest for %@, %@", _session, fetchRequest); } self.sessionTask = newSessionTask; if (!newSessionTask) { // We shouldn't get here; if we're here, an earlier assertion should have fired to explain // which session task creation failed. [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorTaskCreationFailed)]; return; } if (needsDataAccumulator && _accumulateDataBlock == nil) { self.downloadedData = [NSMutableData data]; } if (_taskDescription) { newSessionTask.taskDescription = _taskDescription; } if (_taskPriority >= 0) { #if TARGET_OS_TV || TARGET_OS_WATCH BOOL hasTaskPriority = YES; #elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) BOOL hasTaskPriority = YES; #else BOOL hasTaskPriority = [newSessionTask respondsToSelector:@selector(setPriority:)]; #endif if (hasTaskPriority) { newSessionTask.priority = _taskPriority; } } #if GTM_DISABLE_FETCHER_TEST_BLOCK GTMSESSION_ASSERT_DEBUG(_testBlock == nil && gGlobalTestBlock == nil, @"test blocks disabled"); _testBlock = nil; #else if (!_testBlock) { if (gGlobalTestBlock) { // Note that the test block may pass nil for all of its response parameters, // indicating that the fetch should actually proceed. This is useful when the // global test block has been set, and the app is only testing a specific // fetcher. The block simulation code will then resume the task. _testBlock = gGlobalTestBlock; } } _isUsingTestBlock = (_testBlock != nil); #endif // GTM_DISABLE_FETCHER_TEST_BLOCK #if GTM_BACKGROUND_TASK_FETCHING id app = [[self class] fetcherUIApplication]; // Background tasks seem to interfere with out-of-process uploads and downloads. if (app && !self.skipBackgroundTask && !self.useBackgroundSession) { // Tell UIApplication that we want to continue even when the app is in the // background. #if DEBUG NSString *bgTaskName = [NSString stringWithFormat:@"%@-%@", [self class], fetchRequest.URL.host]; #else NSString *bgTaskName = @"GTMSessionFetcher"; #endif __block UIBackgroundTaskIdentifier bgTaskID = [app beginBackgroundTaskWithName:bgTaskName expirationHandler:^{ // Background task expiration callback - this block is always invoked by // UIApplication on the main thread. if (bgTaskID != UIBackgroundTaskInvalid) { if (bgTaskID == self.backgroundTaskIdentifier) { self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } [app endBackgroundTask:bgTaskID]; } }]; self.backgroundTaskIdentifier = bgTaskID; } #endif if (!_initialRequestDate) { _initialRequestDate = [[NSDate alloc] init]; } // We don't expect to reach here even on retry or auth until a stop notification has been sent // for the previous task, but we should ensure that we don't unbalance that. GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, @"Start notification without a prior stop"); [self sendStopNotificationIfNeeded]; [self addPersistedBackgroundSessionToDefaults]; [self setStopNotificationNeeded:YES]; [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStartedNotification userInfo:nil requireAsync:NO]; // The service needs to know our task if it is serving as NSURLSession delegate. [_service fetcherDidBeginFetching:self]; if (_testBlock) { #if !GTM_DISABLE_FETCHER_TEST_BLOCK [self simulateFetchForTestBlock]; #endif } else { // We resume the session task after posting the notification since the // delegate callbacks may happen immediately if the fetch is started off // the main thread or the session delegate queue is on a background thread, // and we don't want to post a start notification after a premature finish // of the session task. [newSessionTask resume]; } } NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError) { NSMutableData *data = [NSMutableData data]; [inputStream open]; NSInteger numberOfBytesRead = 0; while ([inputStream hasBytesAvailable]) { uint8_t buffer[512]; numberOfBytesRead = [inputStream read:buffer maxLength:sizeof(buffer)]; if (numberOfBytesRead > 0) { [data appendBytes:buffer length:(NSUInteger)numberOfBytesRead]; } else { break; } } [inputStream close]; NSError *streamError = inputStream.streamError; if (streamError) { data = nil; } if (outError) { *outError = streamError; } return data; } #if !GTM_DISABLE_FETCHER_TEST_BLOCK - (void)simulateFetchForTestBlock { // This is invoked on the same thread as the beginFetch method was. // // Callbacks will all occur on the callback queue. _testBlock(self, ^(NSURLResponse *response, NSData *responseData, NSError *error) { // Callback from test block. if (response == nil && responseData == nil && error == nil) { // Assume the fetcher should execute rather than be tested. _testBlock = nil; _isUsingTestBlock = NO; [_sessionTask resume]; return; } GTMSessionFetcherBodyStreamProvider bodyStreamProvider = self.bodyStreamProvider; if (bodyStreamProvider) { bodyStreamProvider(^(NSInputStream *bodyStream){ // Read from the input stream into an NSData buffer. We'll drain the stream // explicitly on a background queue. [self invokeOnCallbackQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) afterUserStopped:NO block:^{ NSError *streamError; NSData *streamedData = GTMDataFromInputStream(bodyStream, &streamError); dispatch_async(dispatch_get_main_queue(), ^{ // Continue callbacks on the main thread, since serial behavior // is more reliable for tests. [self simulateDataCallbacksForTestBlockWithBodyData:streamedData response:response responseData:responseData error:(error ?: streamError)]; }); }]; }); } else { // No input stream; use the supplied data or file URL. NSURL *bodyFileURL = self.bodyFileURL; if (bodyFileURL) { NSError *readError; _bodyData = [NSData dataWithContentsOfURL:bodyFileURL options:NSDataReadingMappedIfSafe error:&readError]; error = readError; } // No stream provider. // In real fetches, nothing happens until the run loop spins, so apps have leeway to // set callbacks after they call beginFetch. We'll mirror that fetcher behavior by // delaying callbacks here at least to the next spin of the run loop. That keeps // immediate, synchronous setting of callback blocks after beginFetch working in tests. dispatch_async(dispatch_get_main_queue(), ^{ [self simulateDataCallbacksForTestBlockWithBodyData:_bodyData response:response responseData:responseData error:error]; }); } }); } - (void)simulateByteTransferReportWithDataLength:(int64_t)totalDataLength block:(GTMSessionFetcherSendProgressBlock)block { // This utility method simulates transfer progress with up to three callbacks. // It is used to call back to any of the progress blocks. int64_t sendReportSize = totalDataLength / 3 + 1; int64_t totalSent = 0; while (totalSent < totalDataLength) { int64_t bytesRemaining = totalDataLength - totalSent; sendReportSize = MIN(sendReportSize, bytesRemaining); totalSent += sendReportSize; [self invokeOnCallbackQueueUnlessStopped:^{ block(sendReportSize, totalSent, totalDataLength); }]; } } - (void)simulateDataCallbacksForTestBlockWithBodyData:(NSData * GTM_NULLABLE_TYPE)bodyData response:(NSURLResponse *)response responseData:(NSData *)suppliedData error:(NSError *)suppliedError { __block NSData *responseData = suppliedData; __block NSError *responseError = suppliedError; // This method does the test simulation of callbacks once the upload // and download data are known. @synchronized(self) { GTMSessionMonitorSynchronized(self); // Get copies of ivars we'll access in async invocations. This simulation assumes // they won't change during fetcher execution. NSURL *destinationFileURL = _destinationFileURL; GTMSessionFetcherWillRedirectBlock willRedirectBlock = _willRedirectBlock; GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock = _didReceiveResponseBlock; GTMSessionFetcherSendProgressBlock sendProgressBlock = _sendProgressBlock; GTMSessionFetcherDownloadProgressBlock downloadProgressBlock = _downloadProgressBlock; GTMSessionFetcherAccumulateDataBlock accumulateDataBlock = _accumulateDataBlock; GTMSessionFetcherReceivedProgressBlock receivedProgressBlock = _receivedProgressBlock; GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock = _willCacheURLResponseBlock; // Simulate receipt of redirection. if (willRedirectBlock) { [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES block:^{ willRedirectBlock((NSHTTPURLResponse *)response, _request, ^(NSURLRequest *redirectRequest) { // For simulation, we'll assume the app will just continue. }); }]; } // If the fetcher has a challenge block, simulate a challenge. // // It might be nice to eventually let the user determine which testBlock // fetches get challenged rather than always executing the supplied // challenge block. if (_challengeBlock) { [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES block:^{ if (_challengeBlock) { NSURL *requestURL = _request.URL; NSString *host = requestURL.host; NSURLProtectionSpace *pspace = [[NSURLProtectionSpace alloc] initWithHost:host port:requestURL.port.integerValue protocol:requestURL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; id unusedSender = (id)[NSNull null]; NSURLAuthenticationChallenge *challenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:pspace proposedCredential:nil previousFailureCount:0 failureResponse:nil error:nil sender:unusedSender]; _challengeBlock(self, challenge, ^(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * GTM_NULLABLE_TYPE credential){ // We could change the responseData and responseError based on the disposition, // but it's easier for apps to just supply the expected data and error // directly to the test block. So this simulation ignores the disposition. }); } }]; } // Simulate receipt of an initial response. if (didReceiveResponseBlock) { [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES block:^{ didReceiveResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { // For simulation, we'll assume the disposition is to continue. }); }]; } // Simulate reporting send progress. if (sendProgressBlock) { [self simulateByteTransferReportWithDataLength:(int64_t)bodyData.length block:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) { // This is invoked on the callback queue unless stopped. sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); }]; } if (destinationFileURL) { // Simulate download to file progress. if (downloadProgressBlock) { [self simulateByteTransferReportWithDataLength:(int64_t)responseData.length block:^(int64_t bytesDownloaded, int64_t totalBytesDownloaded, int64_t totalBytesExpectedToDownload) { // This is invoked on the callback queue unless stopped. downloadProgressBlock(bytesDownloaded, totalBytesDownloaded, totalBytesExpectedToDownload); }]; } NSError *writeError; [responseData writeToURL:destinationFileURL options:NSDataWritingAtomic error:&writeError]; if (writeError) { // Tell the test code that writing failed. responseError = writeError; } } else { // Simulate download to NSData progress. if (accumulateDataBlock) { if (responseData) { [self invokeOnCallbackQueueUnlessStopped:^{ accumulateDataBlock(responseData); }]; } } else { _downloadedData = [responseData mutableCopy]; } if (receivedProgressBlock) { [self simulateByteTransferReportWithDataLength:(int64_t)responseData.length block:^(int64_t bytesReceived, int64_t totalBytesReceived, int64_t totalBytesExpectedToReceive) { // This is invoked on the callback queue unless stopped. receivedProgressBlock(bytesReceived, totalBytesReceived); }]; } if (willCacheURLResponseBlock) { // Simulate letting the client inspect and alter the cached response. NSData *cachedData = responseData ?: [[NSData alloc] init]; // Always have non-nil data. NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:cachedData]; [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES block:^{ willCacheURLResponseBlock(cachedResponse, ^(NSCachedURLResponse *responseToCache){ // The app may provide an alternative response, or nil to defeat caching. }); }]; } } _response = response; } // @synchronized(self) NSOperationQueue *queue = self.sessionDelegateQueue; [queue addOperationWithBlock:^{ // Rather than invoke failToBeginFetchWithError: we want to simulate completion of // a connection that started and ended, so we'll call down to finishWithError: NSInteger status = responseError ? responseError.code : 200; if (status >= 200 && status <= 399) { [self finishWithError:nil shouldRetry:NO]; } else { [self shouldRetryNowForStatus:status error:responseError forceAssumeRetry:NO response:^(BOOL shouldRetry) { [self finishWithError:responseError shouldRetry:shouldRetry]; }]; } }]; } #endif // !GTM_DISABLE_FETCHER_TEST_BLOCK - (void)setSessionTask:(NSURLSessionTask *)sessionTask { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_sessionTask != sessionTask) { _sessionTask = sessionTask; if (_sessionTask) { // Request could be nil on restoring this fetcher from a background session. if (!_request) { _request = [_sessionTask.originalRequest mutableCopy]; } } } } // @synchronized(self) } - (NSURLSessionTask * GTM_NULLABLE_TYPE)sessionTask { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _sessionTask; } // @synchronized(self) } + (NSUserDefaults *)fetcherUserDefaults { static NSUserDefaults *gFetcherUserDefaults = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class fetcherUserDefaultsClass = NSClassFromString(@"GTMSessionFetcherUserDefaultsFactory"); if (fetcherUserDefaultsClass) { gFetcherUserDefaults = [fetcherUserDefaultsClass fetcherUserDefaults]; } else { gFetcherUserDefaults = [NSUserDefaults standardUserDefaults]; } }); return gFetcherUserDefaults; } - (void)addPersistedBackgroundSessionToDefaults { NSString *sessionIdentifier = self.sessionIdentifier; if (!sessionIdentifier) { return; } NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; if ([oldBackgroundSessions containsObject:_sessionIdentifier]) { return; } NSMutableArray *newBackgroundSessions = [NSMutableArray arrayWithArray:oldBackgroundSessions]; [newBackgroundSessions addObject:sessionIdentifier]; GTM_LOG_BACKGROUND_SESSION(@"Add to background sessions: %@", newBackgroundSessions); NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; [userDefaults setObject:newBackgroundSessions forKey:kGTMSessionFetcherPersistedDestinationKey]; [userDefaults synchronize]; } - (void)removePersistedBackgroundSessionFromDefaults { NSString *sessionIdentifier = self.sessionIdentifier; if (!sessionIdentifier) return; NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; if (!oldBackgroundSessions) { return; } NSMutableArray *newBackgroundSessions = [NSMutableArray arrayWithArray:oldBackgroundSessions]; NSUInteger sessionIndex = [newBackgroundSessions indexOfObject:sessionIdentifier]; if (sessionIndex == NSNotFound) { return; } [newBackgroundSessions removeObjectAtIndex:sessionIndex]; GTM_LOG_BACKGROUND_SESSION(@"Remove from background sessions: %@", newBackgroundSessions); NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; if (newBackgroundSessions.count == 0) { [userDefaults removeObjectForKey:kGTMSessionFetcherPersistedDestinationKey]; } else { [userDefaults setObject:newBackgroundSessions forKey:kGTMSessionFetcherPersistedDestinationKey]; } [userDefaults synchronize]; } + (GTM_NULLABLE NSArray *)activePersistedBackgroundSessions { NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; NSArray *oldBackgroundSessions = [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; if (oldBackgroundSessions.count == 0) { return nil; } NSMutableArray *activeBackgroundSessions = nil; NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; for (NSString *sessionIdentifier in oldBackgroundSessions) { GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; if (fetcher) { if (!activeBackgroundSessions) { activeBackgroundSessions = [[NSMutableArray alloc] init]; } [activeBackgroundSessions addObject:sessionIdentifier]; } } return activeBackgroundSessions; } + (NSArray *)fetchersForBackgroundSessions { NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; NSArray *backgroundSessions = [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; NSMutableArray *fetchers = [NSMutableArray array]; for (NSString *sessionIdentifier in backgroundSessions) { GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; if (!fetcher) { fetcher = [self fetcherWithSessionIdentifier:sessionIdentifier]; GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"Unexpected invalid session identifier: %@", sessionIdentifier); [fetcher beginFetchWithCompletionHandler:nil]; } GTM_LOG_BACKGROUND_SESSION(@"%@ restoring session %@ by creating fetcher %@ %p", [self class], sessionIdentifier, fetcher, fetcher); if (fetcher != nil) { [fetchers addObject:fetcher]; } } return fetchers; } #if TARGET_OS_IPHONE + (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler { GTMSessionFetcher *fetcher = [self fetcherWithSessionIdentifier:identifier]; if (fetcher != nil) { fetcher.systemCompletionHandler = completionHandler; } else { GTM_LOG_BACKGROUND_SESSION(@"%@ did not create background session identifier: %@", [self class], identifier); } } #endif - (NSString * GTM_NULLABLE_TYPE)sessionIdentifier { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _sessionIdentifier; } // @synchronized(self) } - (void)setSessionIdentifier:(NSString *)sessionIdentifier { GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSESSION_ASSERT_DEBUG(!_session, @"Unable to set session identifier after session created"); _sessionIdentifier = [sessionIdentifier copy]; _usingBackgroundSession = YES; _canShareSession = NO; [self restoreDefaultStateForSessionIdentifierMetadata]; } // @synchronized(self) } - (void)setSessionIdentifierInternal:(GTM_NULLABLE NSString *)sessionIdentifier { // This internal method only does a synchronized set of the session identifier. // It does not have side effects on the background session, shared session, or // session identifier metadata. @synchronized(self) { GTMSessionMonitorSynchronized(self); _sessionIdentifier = [sessionIdentifier copy]; } // @synchronized(self) } - (NSDictionary * GTM_NULLABLE_TYPE)sessionUserInfo { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_sessionUserInfo == nil) { // We'll return the metadata dictionary with internal keys removed. This avoids the user // re-using the userInfo dictionary later and accidentally including the internal keys. NSMutableDictionary *metadata = [[self sessionIdentifierMetadataUnsynchronized] mutableCopy]; NSSet *keysToRemove = [metadata keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { return [key hasPrefix:@"_"]; }]; [metadata removeObjectsForKeys:[keysToRemove allObjects]]; if (metadata.count > 0) { _sessionUserInfo = metadata; } } return _sessionUserInfo; } // @synchronized(self) } - (void)setSessionUserInfo:(NSDictionary * GTM_NULLABLE_TYPE)dictionary { @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSESSION_ASSERT_DEBUG(_sessionIdentifier == nil, @"Too late to assign userInfo"); _sessionUserInfo = dictionary; } // @synchronized(self) } - (GTM_NULLABLE NSDictionary *)sessionIdentifierDefaultMetadata { GTMSessionCheckSynchronized(self); NSMutableDictionary *defaultUserInfo = [[NSMutableDictionary alloc] init]; if (_destinationFileURL) { defaultUserInfo[kGTMSessionIdentifierDestinationFileURLMetadataKey] = [_destinationFileURL absoluteString]; } if (_bodyFileURL) { defaultUserInfo[kGTMSessionIdentifierBodyFileURLMetadataKey] = [_bodyFileURL absoluteString]; } return (defaultUserInfo.count > 0) ? defaultUserInfo : nil; } - (void)restoreDefaultStateForSessionIdentifierMetadata { GTMSessionCheckSynchronized(self); NSDictionary *metadata = [self sessionIdentifierMetadataUnsynchronized]; NSString *destinationFileURLString = metadata[kGTMSessionIdentifierDestinationFileURLMetadataKey]; if (destinationFileURLString) { _destinationFileURL = [NSURL URLWithString:destinationFileURLString]; GTM_LOG_BACKGROUND_SESSION(@"Restoring destination file URL: %@", _destinationFileURL); } NSString *bodyFileURLString = metadata[kGTMSessionIdentifierBodyFileURLMetadataKey]; if (bodyFileURLString) { _bodyFileURL = [NSURL URLWithString:bodyFileURLString]; GTM_LOG_BACKGROUND_SESSION(@"Restoring body file URL: %@", _bodyFileURL); } } - (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadata { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [self sessionIdentifierMetadataUnsynchronized]; } } - (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadataUnsynchronized { GTMSessionCheckSynchronized(self); // Session Identifier format: "com.google.__ if (!_sessionIdentifier) { return nil; } NSScanner *metadataScanner = [NSScanner scannerWithString:_sessionIdentifier]; [metadataScanner setCharactersToBeSkipped:nil]; NSString *metadataString; NSString *uuid; if ([metadataScanner scanUpToString:@"_" intoString:NULL] && [metadataScanner scanString:@"_" intoString:NULL] && [metadataScanner scanUpToString:@"_" intoString:&uuid] && [metadataScanner scanString:@"_" intoString:NULL] && [metadataScanner scanUpToString:@"\n" intoString:&metadataString]) { _sessionIdentifierUUID = uuid; NSData *metadataData = [metadataString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error; NSDictionary *metadataDict = [NSJSONSerialization JSONObjectWithData:metadataData options:0 error:&error]; GTM_LOG_BACKGROUND_SESSION(@"User Info from session identifier: %@ %@", metadataDict, error ? error : @""); return metadataDict; } return nil; } - (NSString *)createSessionIdentifierWithMetadata:(NSDictionary * GTM_NULLABLE_TYPE)metadataToInclude { NSString *result; @synchronized(self) { GTMSessionMonitorSynchronized(self); // Session Identifier format: "com.google.__ GTMSESSION_ASSERT_DEBUG(!_sessionIdentifier, @"Session identifier already created"); _sessionIdentifierUUID = [[NSUUID UUID] UUIDString]; _sessionIdentifier = [NSString stringWithFormat:@"%@_%@", kGTMSessionIdentifierPrefix, _sessionIdentifierUUID]; // Start with user-supplied keys so they cannot accidentally override the fetcher's keys. NSMutableDictionary *metadataDict = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary * GTM_NONNULL_TYPE)_sessionUserInfo]; if (metadataToInclude) { [metadataDict addEntriesFromDictionary:(NSDictionary *)metadataToInclude]; } NSDictionary *defaultMetadataDict = [self sessionIdentifierDefaultMetadata]; if (defaultMetadataDict) { [metadataDict addEntriesFromDictionary:defaultMetadataDict]; } if (metadataDict.count > 0) { NSData *metadataData = [NSJSONSerialization dataWithJSONObject:metadataDict options:0 error:NULL]; GTMSESSION_ASSERT_DEBUG(metadataData != nil, @"Session identifier user info failed to convert to JSON"); if (metadataData.length > 0) { NSString *metadataString = [[NSString alloc] initWithData:metadataData encoding:NSUTF8StringEncoding]; _sessionIdentifier = [_sessionIdentifier stringByAppendingFormat:@"_%@", metadataString]; } } _didCreateSessionIdentifier = YES; result = _sessionIdentifier; } // @synchronized(self) return result; } - (void)failToBeginFetchWithError:(NSError *)error { @synchronized(self) { GTMSessionMonitorSynchronized(self); _hasStoppedFetching = YES; } if (error == nil) { error = [NSError errorWithDomain:kGTMSessionFetcherErrorDomain code:GTMSessionFetcherErrorDownloadFailed userInfo:nil]; } [self invokeFetchCallbacksOnCallbackQueueWithData:nil error:error]; [self releaseCallbacks]; [_service fetcherDidStop:self]; self.authorizer = nil; } + (GTMSessionCookieStorage *)staticCookieStorage { static GTMSessionCookieStorage *gCookieStorage = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ gCookieStorage = [[GTMSessionCookieStorage alloc] init]; }); return gCookieStorage; } #if GTM_BACKGROUND_TASK_FETCHING - (void)endBackgroundTask { // Whenever the connection stops or background execution expires, // we need to tell UIApplication we're done. // // We'll wait on _callbackGroup to ensure that any callbacks in flight have executed, // and that we access backgroundTaskIdentifier on the main thread, as happens when the // task has expired. UIBackgroundTaskIdentifier bgTaskID = self.backgroundTaskIdentifier; if (bgTaskID != UIBackgroundTaskInvalid) { self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; id app = [[self class] fetcherUIApplication]; [app endBackgroundTask:bgTaskID]; } } #endif // GTM_BACKGROUND_TASK_FETCHING - (void)authorizeRequest { GTMSessionCheckNotSynchronized(self); id authorizer = self.authorizer; SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:); if ([authorizer respondsToSelector:asyncAuthSel]) { SEL callbackSel = @selector(authorizer:request:finishedWithError:); NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; [authorizer authorizeRequest:mutableRequest delegate:self didFinishSelector:callbackSel]; } else { GTMSESSION_ASSERT_DEBUG(authorizer == nil, @"invalid authorizer for fetch"); // No authorizing possible, and authorizing happens only after any delay; // just begin fetching [self beginFetchMayDelay:NO mayAuthorize:NO]; } } - (void)authorizer:(id)auth request:(NSMutableURLRequest *)authorizedRequest finishedWithError:(NSError *)error { GTMSessionCheckNotSynchronized(self); if (error != nil) { // We can't fetch without authorization [self failToBeginFetchWithError:error]; } else { @synchronized(self) { _request = authorizedRequest; } [self beginFetchMayDelay:NO mayAuthorize:NO]; } } - (BOOL)canFetchWithBackgroundSession { // Subclasses may override. return YES; } // Returns YES if the fetcher has been started and has not yet stopped. // // Fetching includes waiting for authorization or for retry, waiting to be allowed by the // service object to start the request, and actually fetching the request. - (BOOL)isFetching { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [self isFetchingUnsynchronized]; } } - (BOOL)isFetchingUnsynchronized { GTMSessionCheckSynchronized(self); BOOL hasBegun = (_initialBeginFetchDate != nil); return hasBegun && !_hasStoppedFetching; } - (NSURLResponse * GTM_NULLABLE_TYPE)response { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSURLResponse *response = [self responseUnsynchronized]; return response; } // @synchronized(self) } - (NSURLResponse * GTM_NULLABLE_TYPE)responseUnsynchronized { GTMSessionCheckSynchronized(self); NSURLResponse *response = _sessionTask.response; if (!response) response = _response; return response; } - (NSInteger)statusCode { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSInteger statusCode = [self statusCodeUnsynchronized]; return statusCode; } // @synchronized(self) } - (NSInteger)statusCodeUnsynchronized { GTMSessionCheckSynchronized(self); NSURLResponse *response = [self responseUnsynchronized]; NSInteger statusCode; if ([response respondsToSelector:@selector(statusCode)]) { statusCode = [(NSHTTPURLResponse *)response statusCode]; } else { // Default to zero, in hopes of hinting "Unknown" (we can't be // sure that things are OK enough to use 200). statusCode = 0; } return statusCode; } - (NSDictionary * GTM_NULLABLE_TYPE)responseHeaders { GTMSessionCheckNotSynchronized(self); NSURLResponse *response = self.response; if ([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; return headers; } return nil; } - (NSDictionary * GTM_NULLABLE_TYPE)responseHeadersUnsynchronized { GTMSessionCheckSynchronized(self); NSURLResponse *response = [self responseUnsynchronized]; if ([response respondsToSelector:@selector(allHeaderFields)]) { NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; return headers; } return nil; } - (void)releaseCallbacks { // Avoid releasing blocks in the sync section since objects dealloc'd by // the blocks being released may call back into the fetcher or fetcher // service. dispatch_queue_t NS_VALID_UNTIL_END_OF_SCOPE holdCallbackQueue; GTMSessionFetcherCompletionHandler NS_VALID_UNTIL_END_OF_SCOPE holdCompletionHandler; @synchronized(self) { GTMSessionMonitorSynchronized(self); holdCallbackQueue = _callbackQueue; holdCompletionHandler = _completionHandler; _callbackQueue = nil; _completionHandler = nil; // Setter overridden in upload. Setter assumed to be used externally. } // Set local callback pointers to nil here rather than let them release at the end of the scope // to make any problems due to the blocks being released be a bit more obvious in a stack trace. holdCallbackQueue = nil; holdCompletionHandler = nil; self.configurationBlock = nil; self.didReceiveResponseBlock = nil; self.challengeBlock = nil; self.willRedirectBlock = nil; self.sendProgressBlock = nil; self.receivedProgressBlock = nil; self.downloadProgressBlock = nil; self.accumulateDataBlock = nil; self.willCacheURLResponseBlock = nil; self.retryBlock = nil; self.testBlock = nil; self.resumeDataBlock = nil; } - (void)forgetSessionIdentifierForFetcher { GTMSessionCheckSynchronized(self); [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; } - (void)forgetSessionIdentifierForFetcherWithoutSyncCheck { // This should be called inside a @synchronized block (except during dealloc.) if (_sessionIdentifier) { NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; [sessionIdentifierToFetcherMap removeObjectForKey:_sessionIdentifier]; _sessionIdentifier = nil; _didCreateSessionIdentifier = NO; } } // External stop method - (void)stopFetching { @synchronized(self) { GTMSessionMonitorSynchronized(self); // Prevent enqueued callbacks from executing. _userStoppedFetching = YES; } // @synchronized(self) [self stopFetchReleasingCallbacks:YES]; } // Cancel the fetch of the URL that's currently in progress. // // If shouldReleaseCallbacks is NO then the fetch will be retried so the callbacks // need to still be retained. - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { [self removePersistedBackgroundSessionFromDefaults]; id service; NSMutableURLRequest *request; // If the task or the retry timer is all that's retaining the fetcher, // we want to be sure this instance survives stopping at least long enough for // the stack to unwind. __autoreleasing GTMSessionFetcher *holdSelf = self; BOOL hasCanceledTask = NO; [holdSelf destroyRetryTimer]; @synchronized(self) { GTMSessionMonitorSynchronized(self); _hasStoppedFetching = YES; service = _service; request = _request; if (_sessionTask) { // In case cancelling the task or session calls this recursively, we want // to ensure that we'll only release the task and delegate once, // so first set _sessionTask to nil // // This may be called in a callback from the task, so use autorelease to avoid // releasing the task in its own callback. __autoreleasing NSURLSessionTask *oldTask = _sessionTask; if (!_isUsingTestBlock) { _response = _sessionTask.response; } _sessionTask = nil; if ([oldTask state] != NSURLSessionTaskStateCompleted) { // For download tasks, when the fetch is stopped, we may provide resume data that can // be used to create a new session. BOOL mayResume = (_resumeDataBlock && [oldTask respondsToSelector:@selector(cancelByProducingResumeData:)]); if (!mayResume) { [oldTask cancel]; // A side effect of stopping the task is that URLSession:task:didCompleteWithError: // will be invoked asynchronously on the delegate queue. } else { void (^resumeBlock)(NSData *) = _resumeDataBlock; _resumeDataBlock = nil; // Save callbackQueue since releaseCallbacks clears it. dispatch_queue_t callbackQueue = _callbackQueue; dispatch_group_enter(_callbackGroup); [(NSURLSessionDownloadTask *)oldTask cancelByProducingResumeData:^(NSData *resumeData) { [self invokeOnCallbackQueue:callbackQueue afterUserStopped:YES block:^{ resumeBlock(resumeData); dispatch_group_leave(_callbackGroup); }]; }]; } hasCanceledTask = YES; } } // If the task was canceled, wait until the URLSession:task:didCompleteWithError: to call // finishTasksAndInvalidate, since calling it immediately tends to crash, see radar 18471901. if (_session) { BOOL shouldInvalidate = _shouldInvalidateSession; #if TARGET_OS_IPHONE // Don't invalidate if we've got a systemCompletionHandler, since // URLSessionDidFinishEventsForBackgroundURLSession: won't be called if invalidated. shouldInvalidate = shouldInvalidate && !self.systemCompletionHandler; #endif if (shouldInvalidate) { __autoreleasing NSURLSession *oldSession = _session; _session = nil; if (!hasCanceledTask) { [oldSession finishTasksAndInvalidate]; } else { _sessionNeedingInvalidation = oldSession; } } } } // @synchronized(self) // send the stopped notification [self sendStopNotificationIfNeeded]; [_authorizer stopAuthorizationForRequest:request]; if (shouldReleaseCallbacks) { [self releaseCallbacks]; self.authorizer = nil; } [service fetcherDidStop:self]; #if GTM_BACKGROUND_TASK_FETCHING [self endBackgroundTask]; #endif } - (void)setStopNotificationNeeded:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); _isStopNotificationNeeded = flag; } // @synchronized(self) } - (void)sendStopNotificationIfNeeded { BOOL sendNow = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_isStopNotificationNeeded) { _isStopNotificationNeeded = NO; sendNow = YES; } } // @synchronized(self) if (sendNow) { [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStoppedNotification userInfo:nil requireAsync:NO]; } } - (void)retryFetch { [self stopFetchReleasingCallbacks:NO]; GTMSessionFetcherCompletionHandler completionHandler; // A retry will need a configuration with a fresh session identifier. @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_sessionIdentifier && _didCreateSessionIdentifier) { [self forgetSessionIdentifierForFetcher]; _configuration = nil; } if (_canShareSession) { // Force a grab of the current session from the fetcher service in case // the service's old one has become invalid. _session = nil; } completionHandler = _completionHandler; } // @synchronized(self) [self beginFetchWithCompletionHandler:completionHandler]; } - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { // Uncovered in upload fetcher testing, because the chunk fetcher is being waited on, and gets // released by the upload code. The uploader just holds onto it with an ivar, and that gets // nilled in the chunk fetcher callback. // Used once in while loop just to avoid unused variable compiler warning. __autoreleasing GTMSessionFetcher *holdSelf = self; NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; BOOL shouldSpinRunLoop = ([NSThread isMainThread] && (!self.callbackQueue || self.callbackQueue == dispatch_get_main_queue())); BOOL expired = NO; // Loop until the callbacks have been called and released, and until // the connection is no longer pending, until there are no callback dispatches // in flight, or until the timeout has expired. int64_t delta = (int64_t)(100 * NSEC_PER_MSEC); // 100 ms while (1) { BOOL isTaskInProgress = (holdSelf->_sessionTask && [_sessionTask state] != NSURLSessionTaskStateCompleted); BOOL needsToCallCompletion = (_completionHandler != nil); BOOL isCallbackInProgress = (_callbackGroup && dispatch_group_wait(_callbackGroup, dispatch_time(DISPATCH_TIME_NOW, delta))); if (!isTaskInProgress && !needsToCallCompletion && !isCallbackInProgress) break; expired = ([giveUpDate timeIntervalSinceNow] < 0); if (expired) { GTMSESSION_LOG_DEBUG(@"GTMSessionFetcher waitForCompletionWithTimeout:%0.1f expired -- " @"%@%@%@", timeoutInSeconds, isTaskInProgress ? @"taskInProgress " : @"", needsToCallCompletion ? @"needsToCallCompletion " : @"", isCallbackInProgress ? @"isCallbackInProgress" : @""); break; } // Run the current run loop 1/1000 of a second to give the networking // code a chance to work const NSTimeInterval kSpinInterval = 0.001; if (shouldSpinRunLoop) { NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; } else { [NSThread sleepForTimeInterval:kSpinInterval]; } } return !expired; } + (void)setGlobalTestBlock:(GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE)block { #if GTM_DISABLE_FETCHER_TEST_BLOCK GTMSESSION_ASSERT_DEBUG(block == nil, @"test blocks disabled"); #endif gGlobalTestBlock = [block copy]; } #if TARGET_OS_IPHONE static GTM_NULLABLE_TYPE id gSubstituteUIApp; + (void)setSubstituteUIApplication:(nullable id)app { gSubstituteUIApp = app; } + (nullable id)substituteUIApplication { return gSubstituteUIApp; } + (nullable id)fetcherUIApplication { id app = gSubstituteUIApp; if (app) return app; // Some projects use GTM_BACKGROUND_UIAPPLICATION to avoid compile-time references // to UIApplication. #if GTM_BACKGROUND_UIAPPLICATION return (id) [UIApplication sharedApplication]; #else return nil; #endif } #endif // TARGET_OS_IPHONE #pragma mark NSURLSession Delegate Methods // NSURLSession documentation indicates that redirectRequest can be passed to the handler // but empirically redirectRequest lacks the HTTP body, so passing it will break POSTs. // Instead, we construct a new request, a copy of the original, with overrides from the // redirect. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse newRequest:(NSURLRequest *)redirectRequest completionHandler:(void (^)(NSURLRequest * GTM_NULLABLE_TYPE))handler { [self setSessionTask:task]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ willPerformHTTPRedirection:%@ newRequest:%@", [self class], self, session, task, redirectResponse, redirectRequest); if ([self userStoppedFetching]) { handler(nil); return; } if (redirectRequest && redirectResponse) { // Copy the original request, including the body. NSURLRequest *originalRequest = self.request; NSMutableURLRequest *newRequest = [originalRequest mutableCopy]; // Disallow scheme changes (say, from https to http). NSURL *originalRequestURL = originalRequest.URL; NSURL *redirectRequestURL = redirectRequest.URL; NSString *originalScheme = originalRequestURL.scheme; NSString *redirectScheme = redirectRequestURL.scheme; if (originalScheme != nil && [originalScheme caseInsensitiveCompare:@"http"] == NSOrderedSame && redirectScheme != nil && [redirectScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { // Allow the change from http to https. } else { // Disallow any other scheme changes. redirectScheme = originalScheme; } // The new requests's URL overrides the original's URL. NSURLComponents *components = [NSURLComponents componentsWithURL:redirectRequestURL resolvingAgainstBaseURL:NO]; components.scheme = redirectScheme; NSURL *newURL = components.URL; [newRequest setURL:newURL]; // Any headers in the redirect override headers in the original. NSDictionary *redirectHeaders = redirectRequest.allHTTPHeaderFields; for (NSString *key in redirectHeaders) { NSString *value = [redirectHeaders objectForKey:key]; [newRequest setValue:value forHTTPHeaderField:key]; } redirectRequest = newRequest; // Log the response we just received [self setResponse:redirectResponse]; [self logNowWithError:nil]; GTMSessionFetcherWillRedirectBlock willRedirectBlock = self.willRedirectBlock; if (willRedirectBlock) { @synchronized(self) { GTMSessionMonitorSynchronized(self); [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ willRedirectBlock(redirectResponse, redirectRequest, ^(NSURLRequest *clientRequest) { // Update the request for future logging. [self updateMutableRequest:[clientRequest mutableCopy]]; handler(clientRequest); }); }]; } // @synchronized(self) return; } // Continues here if the client did not provide a redirect block. // Update the request for future logging. [self updateMutableRequest:[redirectRequest mutableCopy]]; } handler(redirectRequest); } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))handler { [self setSessionTask:dataTask]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveResponse:%@", [self class], self, session, dataTask, response); void (^accumulateAndFinish)(NSURLSessionResponseDisposition) = ^(NSURLSessionResponseDisposition dispositionValue) { // This method is called when the server has determined that it // has enough information to create the NSURLResponse // it can be called multiple times, for example in the case of a // redirect, so each time we reset the data. @synchronized(self) { GTMSessionMonitorSynchronized(self); BOOL hadPreviousData = _downloadedLength > 0; [_downloadedData setLength:0]; _downloadedLength = 0; if (hadPreviousData && (dispositionValue != NSURLSessionResponseCancel)) { // Tell the accumulate block to discard prior data. GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock; if (accumulateBlock) { [self invokeOnCallbackQueueUnlessStopped:^{ accumulateBlock(nil); }]; } } } // @synchronized(self) handler(dispositionValue); }; GTMSessionFetcherDidReceiveResponseBlock receivedResponseBlock; @synchronized(self) { GTMSessionMonitorSynchronized(self); receivedResponseBlock = _didReceiveResponseBlock; if (receivedResponseBlock) { // We will ultimately need to call back to NSURLSession's handler with the disposition value // for this delegate method even if the user has stopped the fetcher. [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ receivedResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { accumulateAndFinish(desiredDisposition); }); }]; } } // @synchronized(self) if (receivedResponseBlock == nil) { accumulateAndFinish(NSURLSessionResponseAllow); } } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didBecomeDownloadTask:%@", [self class], self, session, dataTask, downloadTask); [self setSessionTask:downloadTask]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * GTM_NULLABLE_TYPE credential))handler { [self setSessionTask:task]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didReceiveChallenge:%@", [self class], self, session, task, challenge); GTMSessionFetcherChallengeBlock challengeBlock = self.challengeBlock; if (challengeBlock) { // The fetcher user has provided custom challenge handling. // // We will ultimately need to call back to NSURLSession's handler with the disposition value // for this delegate method even if the user has stopped the fetcher. @synchronized(self) { GTMSessionMonitorSynchronized(self); [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ challengeBlock(self, challenge, handler); }]; } } else { // No challenge block was provided by the client. [self respondToChallenge:challenge completionHandler:handler]; } } - (void)respondToChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * GTM_NULLABLE_TYPE credential))handler { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSInteger previousFailureCount = [challenge previousFailureCount]; if (previousFailureCount <= 2) { NSURLProtectionSpace *protectionSpace = [challenge protectionSpace]; NSString *authenticationMethod = [protectionSpace authenticationMethod]; if ([authenticationMethod isEqual:NSURLAuthenticationMethodServerTrust]) { // SSL. // // Background sessions seem to require an explicit check of the server trust object // rather than default handling. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; if (serverTrust == NULL) { // No server trust information is available. handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } else { // Server trust information is available. void (^callback)(SecTrustRef, BOOL) = ^(SecTrustRef trustRef, BOOL allow){ if (allow) { NSURLCredential *trustCredential = [NSURLCredential credentialForTrust:trustRef]; handler(NSURLSessionAuthChallengeUseCredential, trustCredential); } else { GTMSESSION_LOG_DEBUG(@"Cancelling authentication challenge for %@", _request.URL); handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); } }; if (_allowInvalidServerCertificates) { callback(serverTrust, YES); } else { [[self class] evaluateServerTrust:serverTrust forRequest:_request completionHandler:callback]; } } return; } NSURLCredential *credential = _credential; if ([[challenge protectionSpace] isProxy] && _proxyCredential != nil) { credential = _proxyCredential; } if (credential) { handler(NSURLSessionAuthChallengeUseCredential, credential); } else { // The credential is still nil; tell the OS to use the default handling. This is needed // for things that can come out of the keychain (proxies, client certificates, etc.). // // Note: Looking up a credential with NSURLCredentialStorage's // defaultCredentialForProtectionSpace: is *not* the same invoking the handler with // NSURLSessionAuthChallengePerformDefaultHandling. In the case of // NSURLAuthenticationMethodClientCertificate, you can get nil back from // NSURLCredentialStorage, while using this code path instead works. handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } } else { // We've failed auth 3 times. The completion handler will be called with code // NSURLErrorCancelled. handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); } } // @synchronized(self) } // Validate the certificate chain. // // This may become a public method if it appears to be useful to users. + (void)evaluateServerTrust:(SecTrustRef)serverTrust forRequest:(NSURLRequest *)request completionHandler:(void (^)(SecTrustRef trustRef, BOOL allow))handler { // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7. CFRetain(serverTrust); // Evaluate the certificate chain. // // The delegate queue may be the main thread. Trust evaluation could cause some // blocking network activity, so we must evaluate async, as documented at // https://developer.apple.com/library/ios/technotes/tn2232/ // // We must also avoid multiple uses of the trust object, per docs: // "It is not safe to call this function concurrently with any other function that uses // the same trust management object, or to re-enter this function for the same trust // management object." // // SecTrustEvaluateAsync both does sync execution of Evaluate and calls back on the // queue passed to it, according to at sources in // http://www.opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55050.9/lib/SecTrust.cpp // It would require a global serial queue to ensure the evaluate happens only on a // single thread at a time, so we'll stick with using SecTrustEvaluate on a background // thread. dispatch_queue_t evaluateBackgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(evaluateBackgroundQueue, ^{ // It looks like the implementation of SecTrustEvaluate() on Mac grabs a global lock, // so it may be redundant for us to also lock, but it's easy to synchronize here // anyway. SecTrustResultType trustEval = kSecTrustResultInvalid; BOOL shouldAllow; OSStatus trustError; @synchronized([GTMSessionFetcher class]) { GTMSessionMonitorSynchronized([GTMSessionFetcher class]); trustError = SecTrustEvaluate(serverTrust, &trustEval); } if (trustError != errSecSuccess) { GTMSESSION_LOG_DEBUG(@"Error %d evaluating trust for %@", (int)trustError, request); shouldAllow = NO; } else { // Having a trust level "unspecified" by the user is the usual result, described at // https://developer.apple.com/library/mac/qa/qa1360 if (trustEval == kSecTrustResultUnspecified || trustEval == kSecTrustResultProceed) { shouldAllow = YES; } else { shouldAllow = NO; GTMSESSION_LOG_DEBUG(@"Challenge SecTrustResultType %u for %@, properties: %@", trustEval, request.URL.host, CFBridgingRelease(SecTrustCopyProperties(serverTrust))); } } handler(serverTrust, shouldAllow); CFRelease(serverTrust); }); } - (void)invokeOnCallbackQueueUnlessStopped:(void (^)(void))block { [self invokeOnCallbackQueueAfterUserStopped:NO block:block]; } - (void)invokeOnCallbackQueueAfterUserStopped:(BOOL)afterStopped block:(void (^)(void))block { GTMSessionCheckSynchronized(self); [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:afterStopped block:block]; } - (void)invokeOnCallbackUnsynchronizedQueueAfterUserStopped:(BOOL)afterStopped block:(void (^)(void))block { // testBlock simulation code may not be synchronizing when this is invoked. [self invokeOnCallbackQueue:_callbackQueue afterUserStopped:afterStopped block:block]; } - (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue afterUserStopped:(BOOL)afterStopped block:(void (^)(void))block { if (callbackQueue) { dispatch_group_async(_callbackGroup, callbackQueue, ^{ if (!afterStopped) { NSDate *serviceStoppedAllDate = [_service stoppedAllFetchersDate]; @synchronized(self) { GTMSessionMonitorSynchronized(self); // Avoid a race between stopFetching and the callback. if (_userStoppedFetching) { return; } // Also avoid calling back if the service has stopped all fetchers // since this one was created. The fetcher may have stopped before // stopAllFetchers was invoked, so _userStoppedFetching wasn't set, // but the app still won't expect the callback to fire after // the service's stopAllFetchers was invoked. if (serviceStoppedAllDate && [_initialBeginFetchDate compare:serviceStoppedAllDate] != NSOrderedDescending) { // stopAllFetchers was called after this fetcher began. return; } } // @synchronized(self) } block(); }); } } - (void)invokeFetchCallbacksOnCallbackQueueWithData:(GTM_NULLABLE NSData *)data error:(GTM_NULLABLE NSError *)error { // Callbacks will be released in the method stopFetchReleasingCallbacks: GTMSessionFetcherCompletionHandler handler; @synchronized(self) { GTMSessionMonitorSynchronized(self); handler = _completionHandler; if (handler) { [self invokeOnCallbackQueueUnlessStopped:^{ handler(data, error); // Post a notification, primarily to allow code to collect responses for // testing. // // The observing code is not likely on the fetcher's callback // queue, so this posts explicitly to the main queue. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; if (data) { userInfo[kGTMSessionFetcherCompletionDataKey] = data; } if (error) { userInfo[kGTMSessionFetcherCompletionErrorKey] = error; } [self postNotificationOnMainThreadWithName:kGTMSessionFetcherCompletionInvokedNotification userInfo:userInfo requireAsync:NO]; }]; } } // @synchronized(self) } - (void)postNotificationOnMainThreadWithName:(NSString *)noteName userInfo:(GTM_NULLABLE NSDictionary *)userInfo requireAsync:(BOOL)requireAsync { dispatch_block_t postBlock = ^{ [[NSNotificationCenter defaultCenter] postNotificationName:noteName object:self userInfo:userInfo]; }; if ([NSThread isMainThread] && !requireAsync) { // Post synchronously for compatibility with older code using the fetcher. // Avoid calling out to other code from inside a sync block to avoid risk // of a deadlock or of recursive sync. GTMSessionCheckNotSynchronized(self); postBlock(); } else { dispatch_async(dispatch_get_main_queue(), postBlock); } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)uploadTask needNewBodyStream:(void (^)(NSInputStream * GTM_NULLABLE_TYPE bodyStream))completionHandler { [self setSessionTask:uploadTask]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ needNewBodyStream:", [self class], self, session, uploadTask); @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSessionFetcherBodyStreamProvider provider = _bodyStreamProvider; #if !STRIP_GTM_FETCH_LOGGING if ([self respondsToSelector:@selector(loggedStreamProviderForStreamProvider:)]) { provider = [self performSelector:@selector(loggedStreamProviderForStreamProvider:) withObject:provider]; } #endif if (provider) { [self invokeOnCallbackQueueUnlessStopped:^{ provider(completionHandler); }]; } else { GTMSESSION_ASSERT_DEBUG(NO, @"NSURLSession expects a stream provider"); completionHandler(nil); } } // @synchronized(self) } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { [self setSessionTask:task]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didSendBodyData:%lld" @" totalBytesSent:%lld totalBytesExpectedToSend:%lld", [self class], self, session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend); @synchronized(self) { GTMSessionMonitorSynchronized(self); if (!_sendProgressBlock) { return; } // We won't hold on to send progress block; it's ok to not send it if the upload finishes. [self invokeOnCallbackQueueUnlessStopped:^{ GTMSessionFetcherSendProgressBlock progressBlock; @synchronized(self) { GTMSessionMonitorSynchronized(self); progressBlock = _sendProgressBlock; } if (progressBlock) { progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); } }]; } // @synchronized(self) } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { [self setSessionTask:dataTask]; NSUInteger bufferLength = data.length; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveData:%p (%llu bytes)", [self class], self, session, dataTask, data, (unsigned long long)bufferLength); if (bufferLength == 0) { // Observed on completing an out-of-process upload. return; } @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock; if (accumulateBlock) { // Let the client accumulate the data. _downloadedLength += bufferLength; [self invokeOnCallbackQueueUnlessStopped:^{ accumulateBlock(data); }]; } else if (!_userStoppedFetching) { // Append to the mutable data buffer unless the fetch has been cancelled. // Resumed upload tasks may not yet have a data buffer. if (_downloadedData == nil) { // Using NSClassFromString for iOS 6 compatibility. GTMSESSION_ASSERT_DEBUG( ![dataTask isKindOfClass:NSClassFromString(@"NSURLSessionDownloadTask")], @"Resumed download tasks should not receive data bytes"); _downloadedData = [[NSMutableData alloc] init]; } [_downloadedData appendData:data]; _downloadedLength = (int64_t)_downloadedData.length; // We won't hold on to receivedProgressBlock here; it's ok to not send // it if the transfer finishes. if (_receivedProgressBlock) { [self invokeOnCallbackQueueUnlessStopped:^{ GTMSessionFetcherReceivedProgressBlock progressBlock; @synchronized(self) { GTMSessionMonitorSynchronized(self); progressBlock = _receivedProgressBlock; } if (progressBlock) { progressBlock((int64_t)bufferLength, _downloadedLength); } }]; } } } // @synchronized(self) } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ willCacheResponse:%@ %@", [self class], self, session, dataTask, proposedResponse, proposedResponse.response); GTMSessionFetcherWillCacheURLResponseBlock callback; @synchronized(self) { GTMSessionMonitorSynchronized(self); callback = _willCacheURLResponseBlock; if (callback) { [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ callback(proposedResponse, completionHandler); }]; } } // @synchronized(self) if (!callback) { completionHandler(proposedResponse); } } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didWriteData:%lld" @" bytesWritten:%lld totalBytesExpectedToWrite:%lld", [self class], self, session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); [self setSessionTask:downloadTask]; @synchronized(self) { GTMSessionMonitorSynchronized(self); if ((totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown) && (totalBytesExpectedToWrite < totalBytesWritten)) { // Have observed cases were bytesWritten == totalBytesExpectedToWrite, // but totalBytesWritten > totalBytesExpectedToWrite, so setting to unkown in these cases. totalBytesExpectedToWrite = NSURLSessionTransferSizeUnknown; } // We won't hold on to download progress block during the enqueue; // it's ok to not send it if the upload finishes. [self invokeOnCallbackQueueUnlessStopped:^{ GTMSessionFetcherDownloadProgressBlock progressBlock; @synchronized(self) { GTMSessionMonitorSynchronized(self); progressBlock = _downloadProgressBlock; } if (progressBlock) { progressBlock(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); } }]; } // @synchronized(self) } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didResumeAtOffset:%lld" @" expectedTotalBytes:%lld", [self class], self, session, downloadTask, fileOffset, expectedTotalBytes); [self setSessionTask:downloadTask]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)downloadLocationURL { // Download may have relaunched app, so update _sessionTask. [self setSessionTask:downloadTask]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didFinishDownloadingToURL:%@", [self class], self, session, downloadTask, downloadLocationURL); NSNumber *fileSizeNum; [downloadLocationURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:NULL]; @synchronized(self) { GTMSessionMonitorSynchronized(self); NSURL *destinationURL = _destinationFileURL; _downloadedLength = fileSizeNum.longLongValue; // Overwrite any previous file at the destination URL. NSFileManager *fileMgr = [NSFileManager defaultManager]; NSError *removeError; if (![fileMgr removeItemAtURL:destinationURL error:&removeError] && removeError.code != NSFileNoSuchFileError) { GTMSESSION_LOG_DEBUG(@"Could not remove previous file at %@ due to %@", downloadLocationURL.path, removeError); } NSInteger statusCode = [self statusCodeUnsynchronized]; if (statusCode < 200 || statusCode > 399) { // In OS X 10.11, the response body is written to a file even on a server // status error. For convenience of the fetcher client, we'll skip saving the // downloaded body to the destination URL so that clients do not need to know // to delete the file following fetch errors. A downside of this is that // the server may have included error details in the response body, and // abandoning the downloaded file here means that the details from the // body are not available to the fetcher client. GTMSESSION_LOG_DEBUG(@"Abandoning download due to status %zd, file %@", statusCode, downloadLocationURL.path); } else { NSError *moveError; NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; BOOL didMoveDownload = NO; if ([fileMgr createDirectoryAtURL:destinationFolderURL withIntermediateDirectories:YES attributes:nil error:&moveError]) { didMoveDownload = [fileMgr moveItemAtURL:downloadLocationURL toURL:destinationURL error:&moveError]; } if (!didMoveDownload) { _downloadFinishedError = moveError; } GTM_LOG_BACKGROUND_SESSION(@"%@ %p Moved download from \"%@\" to \"%@\" %@", [self class], self, downloadLocationURL.path, destinationURL.path, error ? error : @""); } } // @synchronized(self) } /* Sent as the last message related to a specific task. Error may be * nil, which implies that no error occurred and this task is complete. */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { [self setSessionTask:task]; GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didCompleteWithError:%@", [self class], self, session, task, error); NSInteger status = self.statusCode; BOOL forceAssumeRetry = NO; BOOL succeeded = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); #if !GTM_DISABLE_FETCHER_TEST_BLOCK // The task is never resumed when a testBlock is used. When the session is destroyed, // we should ignore the callback, since the testBlock support code itself invokes // shouldRetryNowForStatus: and finishWithError:shouldRetry: if (_isUsingTestBlock) return; #endif if (error == nil) { error = _downloadFinishedError; } succeeded = (error == nil && status >= 0 && status < 300); if (succeeded) { // Succeeded. _bodyLength = task.countOfBytesSent; } } // @synchronized(self) if (succeeded) { [self finishWithError:nil shouldRetry:NO]; return; } // For background redirects, no delegate method is called, so we cannot restore a stripped // Authorization header, so if a 403 ("Forbidden") was generated due to a missing OAuth 2 header, // set the current request's URL to the redirected URL, so we in effect restore the Authorization // header. if ((status == 403) && self.usingBackgroundSession) { NSURL *redirectURL = self.response.URL; NSURLRequest *request = self.request; if (![request.URL isEqual:redirectURL]) { NSString *authorizationHeader = [request.allHTTPHeaderFields objectForKey:@"Authorization"]; if (authorizationHeader != nil) { NSMutableURLRequest *mutableRequest = [request mutableCopy]; mutableRequest.URL = redirectURL; [self updateMutableRequest:mutableRequest]; // Avoid assuming the session is still valid. self.session = nil; forceAssumeRetry = YES; } } } // If invalidating the session was deferred in stopFetchReleasingCallbacks: then do it now. NSURLSession *oldSession = self.sessionNeedingInvalidation; if (oldSession) { [self setSessionNeedingInvalidation:NULL]; [oldSession finishTasksAndInvalidate]; } // Failed. [self shouldRetryNowForStatus:status error:error forceAssumeRetry:forceAssumeRetry response:^(BOOL shouldRetry) { [self finishWithError:error shouldRetry:shouldRetry]; }]; } #if TARGET_OS_IPHONE - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSessionDidFinishEventsForBackgroundURLSession:%@", [self class], self, session); [self removePersistedBackgroundSessionFromDefaults]; GTMSessionFetcherSystemCompletionHandler handler; @synchronized(self) { GTMSessionMonitorSynchronized(self); handler = self.systemCompletionHandler; self.systemCompletionHandler = nil; } // @synchronized(self) if (handler) { GTM_LOG_BACKGROUND_SESSION(@"%@ %p Calling system completionHandler", [self class], self); handler(); @synchronized(self) { GTMSessionMonitorSynchronized(self); NSURLSession *oldSession = _session; _session = nil; if (_shouldInvalidateSession) { [oldSession finishTasksAndInvalidate]; } } // @synchronized(self) } } #endif - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(GTM_NULLABLE NSError *)error { // This may happen repeatedly for retries. On authentication callbacks, the retry // may begin before the prior session sends the didBecomeInvalid delegate message. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", [self class], self, session, error); if (session == (NSURLSession *)self.session) { GTM_LOG_SESSION_DELEGATE(@" Unexpected retained invalid session: %@", session); self.session = nil; } } - (void)finishWithError:(GTM_NULLABLE NSError *)error shouldRetry:(BOOL)shouldRetry { [self removePersistedBackgroundSessionFromDefaults]; BOOL shouldStopFetching = YES; NSData *downloadedData = nil; #if !STRIP_GTM_FETCH_LOGGING BOOL shouldDeferLogging = NO; #endif BOOL shouldBeginRetryTimer = NO; NSInteger status = [self statusCode]; NSURL *destinationURL = self.destinationFileURL; BOOL fetchSucceeded = (error == nil && status >= 0 && status < 300); #if !STRIP_GTM_FETCH_LOGGING if (!fetchSucceeded) { if (!shouldDeferLogging && !self.hasLoggedError) { [self logNowWithError:error]; self.hasLoggedError = YES; } } #endif // !STRIP_GTM_FETCH_LOGGING @synchronized(self) { GTMSessionMonitorSynchronized(self); #if !STRIP_GTM_FETCH_LOGGING shouldDeferLogging = _deferResponseBodyLogging; #endif if (fetchSucceeded) { // Success if ((_downloadedData.length > 0) && (destinationURL != nil)) { // Overwrite any previous file at the destination URL. NSFileManager *fileMgr = [NSFileManager defaultManager]; [fileMgr removeItemAtURL:destinationURL error:NULL]; NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; BOOL didMoveDownload = NO; if ([fileMgr createDirectoryAtURL:destinationFolderURL withIntermediateDirectories:YES attributes:nil error:&error]) { didMoveDownload = [_downloadedData writeToURL:destinationURL options:NSDataWritingAtomic error:&error]; } if (didMoveDownload) { _downloadedData = nil; } else { _downloadFinishedError = error; } } downloadedData = _downloadedData; } else { // Unsuccessful with error or status over 300. Retry or notify the delegate of failure if (shouldRetry) { // Retrying. shouldBeginRetryTimer = YES; shouldStopFetching = NO; } else { if (error == nil) { // Create an error. NSDictionary *userInfo = nil; if (_downloadedData.length > 0) { userInfo = @{ kGTMSessionFetcherStatusDataKey : _downloadedData }; } error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain code:status userInfo:userInfo]; } else { // If the error had resume data, and the client supplied a resume block, pass the // data to the client. void (^resumeBlock)(NSData *) = _resumeDataBlock; _resumeDataBlock = nil; if (resumeBlock) { NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]; if (resumeData) { [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ resumeBlock(resumeData); }]; } } } if (_downloadedData.length > 0) { downloadedData = _downloadedData; } // If the error occurred after retries, report the number and duration of the // retries. This provides a clue to a developer looking at the error description // that the fetcher did retry before failing with this error. if (_retryCount > 0) { NSMutableDictionary *userInfoWithRetries = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)error.userInfo]; NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; [userInfoWithRetries setObject:@(timeSinceInitialRequest) forKey:kGTMSessionFetcherElapsedIntervalWithRetriesKey]; [userInfoWithRetries setObject:@(_retryCount) forKey:kGTMSessionFetcherNumberOfRetriesDoneKey]; error = [NSError errorWithDomain:(NSString *)error.domain code:error.code userInfo:userInfoWithRetries]; } } } } // @synchronized(self) if (shouldBeginRetryTimer) { [self beginRetryTimer]; } // We want to send the stop notification before calling the delegate's // callback selector, since the callback selector may release all of // the fetcher properties that the client is using to track the fetches. // // We'll also stop now so that, to any observers watching the notifications, // it doesn't look like our wait for a retry (which may be long, // 30 seconds or more) is part of the network activity. [self sendStopNotificationIfNeeded]; if (shouldStopFetching) { [self invokeFetchCallbacksOnCallbackQueueWithData:downloadedData error:error]; // The upload subclass doesn't want to release callbacks until upload chunks have completed. BOOL shouldRelease = [self shouldReleaseCallbacksUponCompletion]; [self stopFetchReleasingCallbacks:shouldRelease]; } #if !STRIP_GTM_FETCH_LOGGING // _hasLoggedError is only set by this method if (!shouldDeferLogging && !_hasLoggedError) { [self logNowWithError:error]; } #endif } - (BOOL)shouldReleaseCallbacksUponCompletion { // A subclass can override this to keep callbacks around after the // connection has finished successfully return YES; } - (void)logNowWithError:(GTM_NULLABLE NSError *)error { GTMSessionCheckNotSynchronized(self); // If the logging category is available, then log the current request, // response, data, and error if ([self respondsToSelector:@selector(logFetchWithError:)]) { [self performSelector:@selector(logFetchWithError:) withObject:error]; } } #pragma mark Retries - (BOOL)isRetryError:(NSError *)error { struct RetryRecord { __unsafe_unretained NSString *const domain; NSInteger code; }; struct RetryRecord retries[] = { { kGTMSessionFetcherStatusDomain, 408 }, // request timeout { kGTMSessionFetcherStatusDomain, 502 }, // failure gatewaying to another server { kGTMSessionFetcherStatusDomain, 503 }, // service unavailable { kGTMSessionFetcherStatusDomain, 504 }, // request timeout { NSURLErrorDomain, NSURLErrorTimedOut }, { NSURLErrorDomain, NSURLErrorNetworkConnectionLost }, { nil, 0 } }; // NSError's isEqual always returns false for equal but distinct instances // of NSError, so we have to compare the domain and code values explicitly NSString *domain = error.domain; NSInteger code = error.code; for (int idx = 0; retries[idx].domain != nil; idx++) { if (code == retries[idx].code && [domain isEqual:retries[idx].domain]) { return YES; } } return NO; } // shouldRetryNowForStatus:error: responds with YES if the user has enabled retries // and the status or error is one that is suitable for retrying. "Suitable" // means either the isRetryError:'s list contains the status or error, or the // user's retry block is present and returns YES when called, or the // authorizer may be able to fix. - (void)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error forceAssumeRetry:(BOOL)forceAssumeRetry response:(GTMSessionFetcherRetryResponse)response { // Determine if a refreshed authorizer may avoid an authorization error BOOL willRetry = NO; // We assume _authorizer is immutable after beginFetch, and _hasAttemptedAuthRefresh is modified // only in this method, and this method is invoked on the serial delegate queue. // // We want to avoid calling the authorizer from inside a sync block. BOOL isFirstAuthError = (_authorizer != nil && !_hasAttemptedAuthRefresh && status == GTMSessionFetcherStatusUnauthorized); // 401 BOOL hasPrimed = NO; if (isFirstAuthError) { if ([_authorizer respondsToSelector:@selector(primeForRefresh)]) { hasPrimed = [_authorizer primeForRefresh]; } } BOOL shouldRetryForAuthRefresh = NO; if (hasPrimed) { shouldRetryForAuthRefresh = YES; _hasAttemptedAuthRefresh = YES; [self updateRequestValue:nil forHTTPHeaderField:@"Authorization"]; } @synchronized(self) { GTMSessionMonitorSynchronized(self); BOOL shouldDoRetry = [self isRetryEnabledUnsynchronized]; if (shouldDoRetry && ![self hasRetryAfterInterval]) { // Determine if we're doing exponential backoff retries shouldDoRetry = [self nextRetryIntervalUnsynchronized] < _maxRetryInterval; if (shouldDoRetry) { // If an explicit max retry interval was set, we expect repeated backoffs to take // up to roughly twice that for repeated fast failures. If the initial attempt is // already more than 3 times the max retry interval, then failures have taken a long time // (such as from network timeouts) so don't retry again to avoid the app becoming // unexpectedly unresponsive. if (_maxRetryInterval > 0) { NSTimeInterval maxAllowedIntervalBeforeRetry = _maxRetryInterval * 3; NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; if (timeSinceInitialRequest > maxAllowedIntervalBeforeRetry) { shouldDoRetry = NO; } } } } BOOL canRetry = shouldRetryForAuthRefresh || forceAssumeRetry || shouldDoRetry; if (canRetry) { NSDictionary *userInfo = nil; if (_downloadedData.length > 0) { userInfo = @{ kGTMSessionFetcherStatusDataKey : _downloadedData }; } NSError *statusError = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain code:status userInfo:userInfo]; if (error == nil) { error = statusError; } willRetry = shouldRetryForAuthRefresh || forceAssumeRetry || [self isRetryError:error] || ((error != statusError) && [self isRetryError:statusError]); // If the user has installed a retry callback, consult that. GTMSessionFetcherRetryBlock retryBlock = _retryBlock; if (retryBlock) { [self invokeOnCallbackQueueUnlessStopped:^{ retryBlock(willRetry, error, response); }]; return; } } } // @synchronized(self) response(willRetry); } - (BOOL)hasRetryAfterInterval { GTMSessionCheckSynchronized(self); NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; return (retryAfterValue != nil); } - (NSTimeInterval)retryAfterInterval { GTMSessionCheckSynchronized(self); NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; if (retryAfterValue == nil) { return 0; } // Retry-After formatted as HTTP-date | delta-seconds // Reference: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html NSDateFormatter *rfc1123DateFormatter = [[NSDateFormatter alloc] init]; rfc1123DateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; rfc1123DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; rfc1123DateFormatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z"; NSDate *retryAfterDate = [rfc1123DateFormatter dateFromString:retryAfterValue]; NSTimeInterval retryAfterInterval = (retryAfterDate != nil) ? retryAfterDate.timeIntervalSinceNow : retryAfterValue.intValue; retryAfterInterval = MAX(0, retryAfterInterval); return retryAfterInterval; } - (void)beginRetryTimer { if (![NSThread isMainThread]) { // Defer creating and starting the timer until we're on the main thread to ensure it has // a run loop. dispatch_group_async(_callbackGroup, dispatch_get_main_queue(), ^{ [self beginRetryTimer]; }); return; } [self destroyRetryTimer]; @synchronized(self) { GTMSessionMonitorSynchronized(self); NSTimeInterval nextInterval = [self nextRetryIntervalUnsynchronized]; NSTimeInterval maxInterval = _maxRetryInterval; NSTimeInterval newInterval = MIN(nextInterval, (maxInterval > 0 ? maxInterval : DBL_MAX)); NSTimeInterval newIntervalTolerance = (newInterval / 10) > 1.0 ?: 1.0; _lastRetryInterval = newInterval; _retryTimer = [NSTimer timerWithTimeInterval:newInterval target:self selector:@selector(retryTimerFired:) userInfo:nil repeats:NO]; _retryTimer.tolerance = newIntervalTolerance; [[NSRunLoop mainRunLoop] addTimer:_retryTimer forMode:NSDefaultRunLoopMode]; } // @synchronized(self) [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStartedNotification userInfo:nil requireAsync:NO]; } - (void)retryTimerFired:(NSTimer *)timer { [self destroyRetryTimer]; @synchronized(self) { GTMSessionMonitorSynchronized(self); _retryCount++; } // @synchronized(self) NSOperationQueue *queue = self.sessionDelegateQueue; [queue addOperationWithBlock:^{ [self retryFetch]; }]; } - (void)destroyRetryTimer { BOOL shouldNotify = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_retryTimer) { [_retryTimer invalidate]; _retryTimer = nil; shouldNotify = YES; } } if (shouldNotify) { [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStoppedNotification userInfo:nil requireAsync:NO]; } } - (NSUInteger)retryCount { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _retryCount; } // @synchronized(self) } - (NSTimeInterval)nextRetryInterval { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSTimeInterval interval = [self nextRetryIntervalUnsynchronized]; return interval; } // @synchronized(self) } - (NSTimeInterval)nextRetryIntervalUnsynchronized { GTMSessionCheckSynchronized(self); NSInteger statusCode = [self statusCodeUnsynchronized]; if ((statusCode == 503) && [self hasRetryAfterInterval]) { NSTimeInterval secs = [self retryAfterInterval]; return secs; } // The next wait interval is the factor (2.0) times the last interval, // but never less than the minimum interval. NSTimeInterval secs = _lastRetryInterval * _retryFactor; if (_maxRetryInterval > 0) { secs = MIN(secs, _maxRetryInterval); } secs = MAX(secs, _minRetryInterval); return secs; } - (NSTimer *)retryTimer { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _retryTimer; } // @synchronized(self) } - (BOOL)isRetryEnabled { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _isRetryEnabled; } // @synchronized(self) } - (BOOL)isRetryEnabledUnsynchronized { GTMSessionCheckSynchronized(self); return _isRetryEnabled; } - (void)setRetryEnabled:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (flag && !_isRetryEnabled) { // We defer initializing these until the user calls setRetryEnabled // to avoid using the random number generator if it's not needed. // However, this means min and max intervals for this fetcher are reset // as a side effect of calling setRetryEnabled. // // Make an initial retry interval random between 1.0 and 2.0 seconds _minRetryInterval = InitialMinRetryInterval(); _maxRetryInterval = kUnsetMaxRetryInterval; _retryFactor = 2.0; _lastRetryInterval = 0.0; } _isRetryEnabled = flag; } // @synchronized(self) }; - (NSTimeInterval)maxRetryInterval { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _maxRetryInterval; } // @synchronized(self) } - (void)setMaxRetryInterval:(NSTimeInterval)secs { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (secs > 0) { _maxRetryInterval = secs; } else { _maxRetryInterval = kUnsetMaxRetryInterval; } } // @synchronized(self) } - (double)minRetryInterval { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _minRetryInterval; } // @synchronized(self) } - (void)setMinRetryInterval:(NSTimeInterval)secs { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (secs > 0) { _minRetryInterval = secs; } else { // Set min interval to a random value between 1.0 and 2.0 seconds // so that if multiple clients start retrying at the same time, they'll // repeat at different times and avoid overloading the server _minRetryInterval = InitialMinRetryInterval(); } } // @synchronized(self) } #pragma mark iOS System Completion Handlers #if TARGET_OS_IPHONE static NSMutableDictionary *gSystemCompletionHandlers = nil; - (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { return [[self class] systemCompletionHandlerForSessionIdentifier:_sessionIdentifier]; } - (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { [[self class] setSystemCompletionHandler:systemCompletionHandler forSessionIdentifier:_sessionIdentifier]; } + (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler forSessionIdentifier:(NSString *)sessionIdentifier { if (!sessionIdentifier) { NSLog(@"%s with nil identifier", __PRETTY_FUNCTION__); return; } @synchronized([GTMSessionFetcher class]) { if (gSystemCompletionHandlers == nil && systemCompletionHandler != nil) { gSystemCompletionHandlers = [[NSMutableDictionary alloc] init]; } // Use setValue: to remove the object if completionHandler is nil. [gSystemCompletionHandlers setValue:systemCompletionHandler forKey:sessionIdentifier]; } } + (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandlerForSessionIdentifier:(NSString *)sessionIdentifier { if (!sessionIdentifier) { return nil; } @synchronized([GTMSessionFetcher class]) { return [gSystemCompletionHandlers objectForKey:sessionIdentifier]; } } #endif // TARGET_OS_IPHONE #pragma mark Getters and Setters @synthesize downloadResumeData = _downloadResumeData, configuration = _configuration, configurationBlock = _configurationBlock, sessionTask = _sessionTask, wasCreatedFromBackgroundSession = _wasCreatedFromBackgroundSession, sessionUserInfo = _sessionUserInfo, taskDescription = _taskDescription, taskPriority = _taskPriority, usingBackgroundSession = _usingBackgroundSession, canShareSession = _canShareSession, completionHandler = _completionHandler, credential = _credential, proxyCredential = _proxyCredential, bodyData = _bodyData, bodyLength = _bodyLength, service = _service, serviceHost = _serviceHost, accumulateDataBlock = _accumulateDataBlock, receivedProgressBlock = _receivedProgressBlock, downloadProgressBlock = _downloadProgressBlock, resumeDataBlock = _resumeDataBlock, didReceiveResponseBlock = _didReceiveResponseBlock, challengeBlock = _challengeBlock, willRedirectBlock = _willRedirectBlock, sendProgressBlock = _sendProgressBlock, willCacheURLResponseBlock = _willCacheURLResponseBlock, retryBlock = _retryBlock, retryFactor = _retryFactor, allowedInsecureSchemes = _allowedInsecureSchemes, allowLocalhostRequest = _allowLocalhostRequest, allowInvalidServerCertificates = _allowInvalidServerCertificates, cookieStorage = _cookieStorage, callbackQueue = _callbackQueue, initialBeginFetchDate = _initialBeginFetchDate, testBlock = _testBlock, comment = _comment, log = _log; #if !STRIP_GTM_FETCH_LOGGING @synthesize redirectedFromURL = _redirectedFromURL, logRequestBody = _logRequestBody, logResponseBody = _logResponseBody, hasLoggedError = _hasLoggedError; #endif #if GTM_BACKGROUND_TASK_FETCHING @synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier, skipBackgroundTask = _skipBackgroundTask; #endif - (GTM_NULLABLE NSURLRequest *)request { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_request copy]; } // @synchronized(self) } - (void)setRequest:(GTM_NULLABLE NSURLRequest *)request { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (![self isFetchingUnsynchronized]) { _request = [request mutableCopy]; } else { GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); } } // @synchronized(self) } - (GTM_NULLABLE NSMutableURLRequest *)mutableRequestForTesting { // Allow tests only to modify the request, useful during retries. return _request; } - (GTM_NULLABLE NSMutableURLRequest *)mutableRequest { @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSESSION_LOG_DEBUG(@"[GTMSessionFetcher mutableRequest] is deprecated; use -request or" @" -setRequestVaue:forHTTPHeaderField:"); return _request; } // @synchronized(self) } - (void)setMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request { GTMSESSION_LOG_DEBUG(@"[GTMSessionFetcher setMutableRequest:] is deprecated; use -request or" @" -setRequestVaue:forHTTPHeaderField:"); GTMSESSION_ASSERT_DEBUG(![self isFetching], @"mutableRequest should not change after beginFetch has been invoked"); [self updateMutableRequest:request]; } // Internal method for updating the request property such as on redirects. - (void)updateMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request { @synchronized(self) { GTMSessionMonitorSynchronized(self); _request = request; } // @synchronized(self) } // Set a header field value on the request. Header field value changes will not // affect a fetch after the fetch has begun. - (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { if (![self isFetching]) { [self updateRequestValue:value forHTTPHeaderField:field]; } else { GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); } } // Internal method for updating request headers. - (void)updateRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { @synchronized(self) { GTMSessionMonitorSynchronized(self); [_request setValue:value forHTTPHeaderField:field]; } // @synchronized(self) } - (void)setResponse:(GTM_NULLABLE NSURLResponse *)response { @synchronized(self) { GTMSessionMonitorSynchronized(self); _response = response; } // @synchronized(self) } - (int64_t)bodyLength { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_bodyLength == NSURLSessionTransferSizeUnknown) { if (_bodyData) { _bodyLength = (int64_t)_bodyData.length; } else if (_bodyFileURL) { NSNumber *fileSizeNum = nil; NSError *fileSizeError = nil; if ([_bodyFileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:&fileSizeError]) { _bodyLength = [fileSizeNum longLongValue]; } } } return _bodyLength; } // @synchronized(self) } - (BOOL)useUploadTask { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _useUploadTask; } // @synchronized(self) } - (void)setUseUploadTask:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (flag != _useUploadTask) { GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], @"useUploadTask should not change after beginFetch has been invoked"); _useUploadTask = flag; } } // @synchronized(self) } - (GTM_NULLABLE NSURL *)bodyFileURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _bodyFileURL; } // @synchronized(self) } - (void)setBodyFileURL:(GTM_NULLABLE NSURL *)fileURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); // The comparison here is a trivial optimization and forgiveness for any client that // repeatedly sets the property, so it just uses pointer comparison rather than isEqual:. if (fileURL != _bodyFileURL) { GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], @"fileURL should not change after beginFetch has been invoked"); _bodyFileURL = fileURL; } } // @synchronized(self) } - (GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)bodyStreamProvider { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _bodyStreamProvider; } // @synchronized(self) } - (void)setBodyStreamProvider:(GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)block { @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], @"stream provider should not change after beginFetch has been invoked"); _bodyStreamProvider = [block copy]; } // @synchronized(self) } - (GTM_NULLABLE id)authorizer { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _authorizer; } // @synchronized(self) } - (void)setAuthorizer:(GTM_NULLABLE id)authorizer { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (authorizer != _authorizer) { if ([self isFetchingUnsynchronized]) { GTMSESSION_ASSERT_DEBUG(0, @"authorizer should not change after beginFetch has been invoked"); } else { _authorizer = authorizer; } } } // @synchronized(self) } - (GTM_NULLABLE NSData *)downloadedData { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _downloadedData; } // @synchronized(self) } - (void)setDownloadedData:(GTM_NULLABLE NSData *)data { @synchronized(self) { GTMSessionMonitorSynchronized(self); _downloadedData = [data mutableCopy]; } // @synchronized(self) } - (int64_t)downloadedLength { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _downloadedLength; } // @synchronized(self) } - (void)setDownloadedLength:(int64_t)length { @synchronized(self) { GTMSessionMonitorSynchronized(self); _downloadedLength = length; } // @synchronized(self) } - (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _callbackQueue; } // @synchronized(self) } - (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { @synchronized(self) { GTMSessionMonitorSynchronized(self); _callbackQueue = queue ?: dispatch_get_main_queue(); } // @synchronized(self) } - (GTM_NULLABLE NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _session; } // @synchronized(self) } - (NSInteger)servicePriority { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _servicePriority; } // @synchronized(self) } - (void)setServicePriority:(NSInteger)value { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (value != _servicePriority) { GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], @"servicePriority should not change after beginFetch has been invoked"); _servicePriority = value; } } // @synchronized(self) } - (void)setSession:(GTM_NULLABLE NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); _session = session; } // @synchronized(self) } - (BOOL)canShareSession { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _canShareSession; } // @synchronized(self) } - (void)setCanShareSession:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); _canShareSession = flag; } // @synchronized(self) } - (BOOL)useBackgroundSession { // This reflects if the user requested a background session, not necessarily // if one was created. That is tracked with _usingBackgroundSession. @synchronized(self) { GTMSessionMonitorSynchronized(self); return _userRequestedBackgroundSession; } // @synchronized(self) } - (void)setUseBackgroundSession:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (flag != _userRequestedBackgroundSession) { GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], @"useBackgroundSession should not change after beginFetch has been invoked"); _userRequestedBackgroundSession = flag; } } // @synchronized(self) } - (BOOL)isUsingBackgroundSession { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _usingBackgroundSession; } // @synchronized(self) } - (void)setUsingBackgroundSession:(BOOL)flag { @synchronized(self) { GTMSessionMonitorSynchronized(self); _usingBackgroundSession = flag; } // @synchronized(self) } - (GTM_NULLABLE NSURLSession *)sessionNeedingInvalidation { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _sessionNeedingInvalidation; } // @synchronized(self) } - (void)setSessionNeedingInvalidation:(GTM_NULLABLE NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); _sessionNeedingInvalidation = session; } // @synchronized(self) } - (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _delegateQueue; } // @synchronized(self) } - (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (queue != _delegateQueue) { if ([self isFetchingUnsynchronized]) { GTMSESSION_ASSERT_DEBUG(0, @"sessionDelegateQueue should not change after fetch begins"); } else { _delegateQueue = queue ?: [NSOperationQueue mainQueue]; } } } // @synchronized(self) } - (BOOL)userStoppedFetching { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _userStoppedFetching; } // @synchronized(self) } - (GTM_NULLABLE id)userData { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _userData; } // @synchronized(self) } - (void)setUserData:(GTM_NULLABLE id)theObj { @synchronized(self) { GTMSessionMonitorSynchronized(self); _userData = theObj; } // @synchronized(self) } - (GTM_NULLABLE NSURL *)destinationFileURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _destinationFileURL; } // @synchronized(self) } - (void)setDestinationFileURL:(GTM_NULLABLE NSURL *)destinationFileURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (((_destinationFileURL == nil) && (destinationFileURL == nil)) || [_destinationFileURL isEqual:destinationFileURL]) { return; } if (_sessionIdentifier) { // This is something we don't expect to happen in production. // However if it ever happen, leave a system log. NSLog(@"%@: Destination File URL changed from (%@) to (%@) after session identifier has " @"been created.", [self class], _destinationFileURL, destinationFileURL); #if DEBUG // On both the simulator and devices, the path can change to the download file, but the name // shouldn't change. Technically, this isn't supported in the fetcher, but the change of // URL is expected to happen only across development runs through Xcode. NSString *oldFilename = [_destinationFileURL lastPathComponent]; NSString *newFilename = [destinationFileURL lastPathComponent]; #pragma unused(oldFilename) #pragma unused(newFilename) GTMSESSION_ASSERT_DEBUG([oldFilename isEqualToString:newFilename], @"Destination File URL cannot be changed after session identifier has been created"); #endif } _destinationFileURL = destinationFileURL; } // @synchronized(self) } - (void)setProperties:(GTM_NULLABLE NSDictionary *)dict { @synchronized(self) { GTMSessionMonitorSynchronized(self); _properties = [dict mutableCopy]; } // @synchronized(self) } - (GTM_NULLABLE NSDictionary *)properties { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _properties; } // @synchronized(self) } - (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_properties == nil && obj != nil) { _properties = [[NSMutableDictionary alloc] init]; } [_properties setValue:obj forKey:key]; } // @synchronized(self) } - (GTM_NULLABLE id)propertyForKey:(NSString *)key { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_properties objectForKey:key]; } // @synchronized(self) } - (void)addPropertiesFromDictionary:(NSDictionary *)dict { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_properties == nil && dict != nil) { [self setProperties:[dict mutableCopy]]; } else { [_properties addEntriesFromDictionary:dict]; } } // @synchronized(self) } - (void)setCommentWithFormat:(id)format, ... { #if !STRIP_GTM_FETCH_LOGGING NSString *result = format; if (format) { va_list argList; va_start(argList, format); result = [[NSString alloc] initWithFormat:format arguments:argList]; va_end(argList); } [self setComment:result]; #endif } #if !STRIP_GTM_FETCH_LOGGING - (NSData *)loggedStreamData { return _loggedStreamData; } - (void)appendLoggedStreamData:dataToAdd { if (!_loggedStreamData) { _loggedStreamData = [NSMutableData data]; } [_loggedStreamData appendData:dataToAdd]; } - (void)clearLoggedStreamData { _loggedStreamData = nil; } - (void)setDeferResponseBodyLogging:(BOOL)deferResponseBodyLogging { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (deferResponseBodyLogging != _deferResponseBodyLogging) { _deferResponseBodyLogging = deferResponseBodyLogging; if (!deferResponseBodyLogging && !self.hasLoggedError) { [_delegateQueue addOperationWithBlock:^{ [self logNowWithError:nil]; }]; } } } // @synchronized(self) } - (BOOL)deferResponseBodyLogging { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _deferResponseBodyLogging; } // @synchronized(self) } #else + (void)setLoggingEnabled:(BOOL)flag { } + (BOOL)isLoggingEnabled { return NO; } #endif // STRIP_GTM_FETCH_LOGGING @end @implementation GTMSessionFetcher (BackwardsCompatibilityOnly) - (void)setCookieStorageMethod:(NSInteger)method { // For backwards compatibility with the old fetcher, we'll support the old constants. // // Clients using the GTMSessionFetcher class should set the cookie storage explicitly // themselves. NSHTTPCookieStorage *storage = nil; switch(method) { case 0: // kGTMHTTPFetcherCookieStorageMethodStatic // nil storage will use [[self class] staticCookieStorage] when the fetch begins. break; case 1: // kGTMHTTPFetcherCookieStorageMethodFetchHistory // Do nothing; use whatever was set by the fetcher service. return; case 2: // kGTMHTTPFetcherCookieStorageMethodSystemDefault storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; break; case 3: // kGTMHTTPFetcherCookieStorageMethodNone // Create temporary storage for this fetcher only. storage = [[GTMSessionCookieStorage alloc] init]; break; default: GTMSESSION_ASSERT_DEBUG(0, @"Invalid cookie storage method: %d", (int)method); } self.cookieStorage = storage; } @end @implementation GTMSessionCookieStorage { NSMutableArray *_cookies; NSHTTPCookieAcceptPolicy _policy; } - (id)init { self = [super init]; if (self != nil) { _cookies = [[NSMutableArray alloc] init]; } return self; } - (GTM_NULLABLE NSArray *)cookies { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_cookies copy]; } // @synchronized(self) } - (void)setCookie:(NSHTTPCookie *)cookie { if (!cookie) return; if (_policy == NSHTTPCookieAcceptPolicyNever) return; @synchronized(self) { GTMSessionMonitorSynchronized(self); [self internalSetCookie:cookie]; } // @synchronized(self) } // Note: this should only be called from inside a @synchronized(self) block. - (void)internalSetCookie:(NSHTTPCookie *)newCookie { GTMSessionCheckSynchronized(self); if (_policy == NSHTTPCookieAcceptPolicyNever) return; BOOL isValidCookie = (newCookie.name.length > 0 && newCookie.domain.length > 0 && newCookie.path.length > 0); GTMSESSION_ASSERT_DEBUG(isValidCookie, @"invalid cookie: %@", newCookie); if (isValidCookie) { // Remove the cookie if it's currently in the array. NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie]; if (oldCookie) { [_cookies removeObjectIdenticalTo:oldCookie]; } if (![[self class] hasCookieExpired:newCookie]) { [_cookies addObject:newCookie]; } } } // Add all cookies in the new cookie array to the storage, // replacing stored cookies as appropriate. // // Side effect: removes expired cookies from the storage array. - (void)setCookies:(GTM_NULLABLE NSArray *)newCookies { @synchronized(self) { GTMSessionMonitorSynchronized(self); [self removeExpiredCookies]; for (NSHTTPCookie *newCookie in newCookies) { [self internalSetCookie:newCookie]; } } // @synchronized(self) } - (void)setCookies:(NSArray *)cookies forURL:(GTM_NULLABLE NSURL *)URL mainDocumentURL:(GTM_NULLABLE NSURL *)mainDocumentURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_policy == NSHTTPCookieAcceptPolicyNever) { return; } if (_policy == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) { NSString *mainHost = mainDocumentURL.host; NSString *associatedHost = URL.host; if (!mainHost || ![associatedHost hasSuffix:mainHost]) { return; } } } // @synchronized(self) [self setCookies:cookies]; } - (void)deleteCookie:(NSHTTPCookie *)cookie { if (!cookie) return; @synchronized(self) { GTMSessionMonitorSynchronized(self); NSHTTPCookie *foundCookie = [self cookieMatchingCookie:cookie]; if (foundCookie) { [_cookies removeObjectIdenticalTo:foundCookie]; } } // @synchronized(self) } // Retrieve all cookies appropriate for the given URL, considering // domain, path, cookie name, expiration, security setting. // Side effect: removed expired cookies from the storage array. - (GTM_NULLABLE NSArray *)cookiesForURL:(NSURL *)theURL { NSMutableArray *foundCookies = nil; @synchronized(self) { GTMSessionMonitorSynchronized(self); [self removeExpiredCookies]; // We'll prepend "." to the desired domain, since we want the // actual domain "nytimes.com" to still match the cookie domain // ".nytimes.com" when we check it below with hasSuffix. NSString *host = theURL.host.lowercaseString; NSString *path = theURL.path; NSString *scheme = [theURL scheme]; NSString *requestingDomain = nil; BOOL isLocalhostRetrieval = NO; if (IsLocalhost(host)) { isLocalhostRetrieval = YES; } else { if (host.length > 0) { requestingDomain = [@"." stringByAppendingString:host]; } } for (NSHTTPCookie *storedCookie in _cookies) { NSString *cookieDomain = storedCookie.domain.lowercaseString; NSString *cookiePath = storedCookie.path; BOOL cookieIsSecure = [storedCookie isSecure]; BOOL isDomainOK; if (isLocalhostRetrieval) { // Prior to 10.5.6, the domain stored into NSHTTPCookies for localhost // is "localhost.local" isDomainOK = (IsLocalhost(cookieDomain) || [cookieDomain isEqual:@"localhost.local"]); } else { // Ensure we're matching exact domain names. We prepended a dot to the // requesting domain, so we can also prepend one here if needed before // checking if the request contains the cookie domain. if (![cookieDomain hasPrefix:@"."]) { cookieDomain = [@"." stringByAppendingString:cookieDomain]; } isDomainOK = [requestingDomain hasSuffix:cookieDomain]; } BOOL isPathOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath]; BOOL isSecureOK = (!cookieIsSecure || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame); if (isDomainOK && isPathOK && isSecureOK) { if (foundCookies == nil) { foundCookies = [NSMutableArray array]; } [foundCookies addObject:storedCookie]; } } } // @synchronized(self) return foundCookies; } // Override methods from the NSHTTPCookieStorage (NSURLSessionTaskAdditions) category. - (void)storeCookies:(NSArray *)cookies forTask:(NSURLSessionTask *)task { NSURLRequest *currentRequest = task.currentRequest; [self setCookies:cookies forURL:currentRequest.URL mainDocumentURL:nil]; } - (void)getCookiesForTask:(NSURLSessionTask *)task completionHandler:(void (^)(GTM_NSArrayOf(NSHTTPCookie *) *))completionHandler { if (completionHandler) { NSURLRequest *currentRequest = task.currentRequest; NSURL *currentRequestURL = currentRequest.URL; NSArray *cookies = [self cookiesForURL:currentRequestURL]; completionHandler(cookies); } } // Return a cookie from the array with the same name, domain, and path as the // given cookie, or else return nil if none found. // // Both the cookie being tested and all cookies in the storage array should // be valid (non-nil name, domains, paths). // // Note: this should only be called from inside a @synchronized(self) block - (GTM_NULLABLE NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie { GTMSessionCheckSynchronized(self); NSString *name = cookie.name; NSString *domain = cookie.domain; NSString *path = cookie.path; GTMSESSION_ASSERT_DEBUG(name && domain && path, @"Invalid stored cookie (name:%@ domain:%@ path:%@)", name, domain, path); for (NSHTTPCookie *storedCookie in _cookies) { if ([storedCookie.name isEqual:name] && [storedCookie.domain isEqual:domain] && [storedCookie.path isEqual:path]) { return storedCookie; } } return nil; } // Internal routine to remove any expired cookies from the array, excluding // cookies with nil expirations. // // Note: this should only be called from inside a @synchronized(self) block - (void)removeExpiredCookies { GTMSessionCheckSynchronized(self); // Count backwards since we're deleting items from the array for (NSInteger idx = (NSInteger)_cookies.count - 1; idx >= 0; idx--) { NSHTTPCookie *storedCookie = [_cookies objectAtIndex:(NSUInteger)idx]; if ([[self class] hasCookieExpired:storedCookie]) { [_cookies removeObjectAtIndex:(NSUInteger)idx]; } } } + (BOOL)hasCookieExpired:(NSHTTPCookie *)cookie { NSDate *expiresDate = [cookie expiresDate]; if (expiresDate == nil) { // Cookies seem to have a Expires property even when the expiresDate method returns nil. id expiresVal = [[cookie properties] objectForKey:NSHTTPCookieExpires]; if ([expiresVal isKindOfClass:[NSDate class]]) { expiresDate = expiresVal; } } BOOL hasExpired = (expiresDate != nil && [expiresDate timeIntervalSinceNow] < 0); return hasExpired; } - (void)removeAllCookies { @synchronized(self) { GTMSessionMonitorSynchronized(self); [_cookies removeAllObjects]; } // @synchronized(self) } - (NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _policy; } // @synchronized(self) } - (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { @synchronized(self) { GTMSessionMonitorSynchronized(self); _policy = cookieAcceptPolicy; } // @synchronized(self) } @end void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...) { // Verify that the object's selector is implemented with the proper // number and type of arguments #if DEBUG va_list argList; va_start(argList, sel); if (obj && sel) { // Check that the selector is implemented if (![obj respondsToSelector:sel]) { NSLog(@"\"%@\" selector \"%@\" is unimplemented or misnamed", NSStringFromClass([(id)obj class]), NSStringFromSelector((SEL)sel)); NSCAssert(0, @"callback selector unimplemented or misnamed"); } else { const char *expectedArgType; unsigned int argCount = 2; // skip self and _cmd NSMethodSignature *sig = [obj methodSignatureForSelector:sel]; // Check that each expected argument is present and of the correct type while ((expectedArgType = va_arg(argList, const char*)) != 0) { if ([sig numberOfArguments] > argCount) { const char *foundArgType = [sig getArgumentTypeAtIndex:argCount]; if (0 != strncmp(foundArgType, expectedArgType, strlen(expectedArgType))) { NSLog(@"\"%@\" selector \"%@\" argument %d should be type %s", NSStringFromClass([(id)obj class]), NSStringFromSelector((SEL)sel), (argCount - 2), expectedArgType); NSCAssert(0, @"callback selector argument type mistake"); } } argCount++; } // Check that the proper number of arguments are present in the selector if (argCount != [sig numberOfArguments]) { NSLog(@"\"%@\" selector \"%@\" should have %d arguments", NSStringFromClass([(id)obj class]), NSStringFromSelector((SEL)sel), (argCount - 2)); NSCAssert(0, @"callback selector arguments incorrect"); } } } va_end(argList); #endif } NSString *GTMFetcherCleanedUserAgentString(NSString *str) { // Reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html // and http://www-archive.mozilla.org/build/user-agent-strings.html if (str == nil) return @""; NSMutableString *result = [NSMutableString stringWithString:str]; // Replace spaces and commas with underscores [result replaceOccurrencesOfString:@" " withString:@"_" options:0 range:NSMakeRange(0, result.length)]; [result replaceOccurrencesOfString:@"," withString:@"_" options:0 range:NSMakeRange(0, result.length)]; // Delete http token separators and remaining whitespace static NSCharacterSet *charsToDelete = nil; if (charsToDelete == nil) { // Make a set of unwanted characters NSString *const kSeparators = @"()<>@;:\\\"/[]?={}"; NSMutableCharacterSet *mutableChars = [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy]; [mutableChars addCharactersInString:kSeparators]; charsToDelete = [mutableChars copy]; // hang on to an immutable copy } while (1) { NSRange separatorRange = [result rangeOfCharacterFromSet:charsToDelete]; if (separatorRange.location == NSNotFound) break; [result deleteCharactersInRange:separatorRange]; }; return result; } NSString *GTMFetcherSystemVersionString(void) { static NSString *sSavedSystemString; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // The Xcode 8 SDKs finally cleaned up this mess by providing TARGET_OS_OSX // and TARGET_OS_IOS, but to build with older SDKs, those don't exist and // instead one has to rely on TARGET_OS_MAC (which is true for iOS, watchOS, // and tvOS) and TARGET_OS_IPHONE (which is true for iOS, watchOS, tvOS). So // one has to order these carefully so you pick off the specific things // first. // If the code can ever assume Xcode 8 or higher (even when building for // older OSes), then // TARGET_OS_MAC -> TARGET_OS_OSX // TARGET_OS_IPHONE -> TARGET_OS_IOS // TARGET_IPHONE_SIMULATOR -> TARGET_OS_SIMULATOR #if TARGET_OS_WATCH // watchOS - WKInterfaceDevice WKInterfaceDevice *currentDevice = [WKInterfaceDevice currentDevice]; NSString *rawModel = [currentDevice model]; NSString *model = GTMFetcherCleanedUserAgentString(rawModel); NSString *systemVersion = [currentDevice systemVersion]; #if TARGET_OS_SIMULATOR NSString *hardwareModel = @"sim"; #else NSString *hardwareModel; struct utsname unameRecord; if (uname(&unameRecord) == 0) { NSString *machineName = @(unameRecord.machine); hardwareModel = GTMFetcherCleanedUserAgentString(machineName); } if (hardwareModel.length == 0) { hardwareModel = @"unk"; } #endif sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", model, systemVersion, hardwareModel]; // Example: Apple_Watch/3.0 hw/Watch1_2 #elif TARGET_OS_TV || TARGET_OS_IPHONE // iOS and tvOS have UIDevice, use that. UIDevice *currentDevice = [UIDevice currentDevice]; NSString *rawModel = [currentDevice model]; NSString *model = GTMFetcherCleanedUserAgentString(rawModel); NSString *systemVersion = [currentDevice systemVersion]; #if TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR NSString *hardwareModel = @"sim"; #else NSString *hardwareModel; struct utsname unameRecord; if (uname(&unameRecord) == 0) { NSString *machineName = @(unameRecord.machine); hardwareModel = GTMFetcherCleanedUserAgentString(machineName); } if (hardwareModel.length == 0) { hardwareModel = @"unk"; } #endif sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", model, systemVersion, hardwareModel]; // Example: iPod_Touch/2.2 hw/iPod1_1 // Example: Apple_TV/9.2 hw/AppleTV5,3 #elif TARGET_OS_MAC // Mac build NSProcessInfo *procInfo = [NSProcessInfo processInfo]; #if !defined(MAC_OS_X_VERSION_10_10) BOOL hasOperatingSystemVersion = NO; #elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10 BOOL hasOperatingSystemVersion = [procInfo respondsToSelector:@selector(operatingSystemVersion)]; #else BOOL hasOperatingSystemVersion = YES; #endif NSString *versString; if (hasOperatingSystemVersion) { #if defined(MAC_OS_X_VERSION_10_10) // A reference to NSOperatingSystemVersion requires the 10.10 SDK. NSOperatingSystemVersion version = procInfo.operatingSystemVersion; versString = [NSString stringWithFormat:@"%zd.%zd.%zd", version.majorVersion, version.minorVersion, version.patchVersion]; #else #pragma unused(procInfo) #endif } else { // With Gestalt inexplicably deprecated in 10.8, we're reduced to reading // the system plist file. NSString *const kPath = @"/System/Library/CoreServices/SystemVersion.plist"; NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:kPath]; versString = [plist objectForKey:@"ProductVersion"]; if (versString.length == 0) { versString = @"10.?.?"; } } sSavedSystemString = [[NSString alloc] initWithFormat:@"MacOSX/%@", versString]; #elif defined(_SYS_UTSNAME_H) // Foundation-only build struct utsname unameRecord; uname(&unameRecord); sSavedSystemString = [NSString stringWithFormat:@"%s/%s", unameRecord.sysname, unameRecord.release]; // "Darwin/8.11.1" #else #error No branch taken for a default user agent #endif }); return sSavedSystemString; } NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle) { NSString *result = [NSString stringWithFormat:@"%@ %@", GTMFetcherApplicationIdentifier(bundle), GTMFetcherSystemVersionString()]; return result; } NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle) { @synchronized([GTMSessionFetcher class]) { static NSMutableDictionary *sAppIDMap = nil; // If there's a bundle ID, use that; otherwise, use the process name if (bundle == nil) { bundle = [NSBundle mainBundle]; } NSString *bundleID = [bundle bundleIdentifier]; if (bundleID == nil) { bundleID = @""; } NSString *identifier = [sAppIDMap objectForKey:bundleID]; if (identifier) return identifier; // Apps may add a string to the info.plist to uniquely identify different builds. identifier = [bundle objectForInfoDictionaryKey:@"GTMUserAgentID"]; if (identifier.length == 0) { if (bundleID.length > 0) { identifier = bundleID; } else { // Fall back on the procname, prefixed by "proc" to flag that it's // autogenerated and perhaps unreliable NSString *procName = [[NSProcessInfo processInfo] processName]; identifier = [NSString stringWithFormat:@"proc_%@", procName]; } } // Clean up whitespace and special characters identifier = GTMFetcherCleanedUserAgentString(identifier); // If there's a version number, append that NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; if (version.length == 0) { version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; } // Clean up whitespace and special characters version = GTMFetcherCleanedUserAgentString(version); // Glue the two together (cleanup done above or else cleanup would strip the // slash) if (version.length > 0) { identifier = [identifier stringByAppendingFormat:@"/%@", version]; } if (sAppIDMap == nil) { sAppIDMap = [[NSMutableDictionary alloc] init]; } [sAppIDMap setObject:identifier forKey:bundleID]; return identifier; } } #if DEBUG @implementation GTMSessionSyncMonitorInternal { NSValue *_objectKey; // The synchronize target object. const char *_functionName; // The function containing the monitored sync block. } - (instancetype)initWithSynchronizationObject:(id)object allowRecursive:(BOOL)allowRecursive functionName:(const char *)functionName { self = [super init]; if (self) { Class threadKey = [GTMSessionSyncMonitorInternal class]; _objectKey = [NSValue valueWithNonretainedObject:object]; _functionName = functionName; NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; NSMutableDictionary *counters = threadDict[threadKey]; if (counters == nil) { counters = [NSMutableDictionary dictionary]; threadDict[(id)threadKey] = counters; } NSCountedSet *functionNamesCounter = counters[_objectKey]; NSUInteger numberOfSyncingFunctions = functionNamesCounter.count; if (!allowRecursive) { BOOL isTopLevelSyncScope = (numberOfSyncingFunctions == 0); NSArray *stack = [NSThread callStackSymbols]; GTMSESSION_ASSERT_DEBUG(isTopLevelSyncScope, @"*** Recursive sync on %@ at %s; previous sync at %@\n%@", [object class], functionName, functionNamesCounter.allObjects, [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); } if (!functionNamesCounter) { functionNamesCounter = [NSCountedSet set]; counters[_objectKey] = functionNamesCounter; } [functionNamesCounter addObject:@(functionName)]; } return self; } - (void)dealloc { Class threadKey = [GTMSessionSyncMonitorInternal class]; NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; NSMutableDictionary *counters = threadDict[threadKey]; NSCountedSet *functionNamesCounter = counters[_objectKey]; NSString *functionNameStr = @(_functionName); NSUInteger numberOfSyncsByThisFunction = [functionNamesCounter countForObject:functionNameStr]; NSArray *stack = [NSThread callStackSymbols]; GTMSESSION_ASSERT_DEBUG(numberOfSyncsByThisFunction > 0, @"Sync not found on %@ at %s\n%@", [_objectKey.nonretainedObjectValue class], _functionName, [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); [functionNamesCounter removeObject:functionNameStr]; if (functionNamesCounter.count == 0) { [counters removeObjectForKey:_objectKey]; } } + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object { Class threadKey = [GTMSessionSyncMonitorInternal class]; NSValue *localObjectKey = [NSValue valueWithNonretainedObject:object]; NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; NSMutableDictionary *counters = threadDict[threadKey]; NSCountedSet *functionNamesCounter = counters[localObjectKey]; return functionNamesCounter.count > 0 ? functionNamesCounter.allObjects : nil; } @end #endif // DEBUG GTM_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #import "GTMSessionFetcher.h" // GTM HTTP Logging // // All traffic using GTMSessionFetcher can be easily logged. Call // // [GTMSessionFetcher setLoggingEnabled:YES]; // // to begin generating log files. // // Log files are put into a folder on the desktop called "GTMHTTPDebugLogs" // unless another directory is specified with +setLoggingDirectory. // // In the iPhone simulator, the default logs location is the user's home // directory in ~/Library/Application Support. On the iPhone device, the // default logs location is the application's documents directory on the device. // // Tip: use the Finder's "Sort By Date" to find the most recent logs. // // Each run of an application gets a separate set of log files. An html // file is generated to simplify browsing the run's http transactions. // The html file includes javascript links for inline viewing of uploaded // and downloaded data. // // A symlink is created in the logs folder to simplify finding the html file // for the latest run of the application; the symlink is called // // AppName_http_log_newest.html // // For better viewing of XML logs, use Camino or Firefox rather than Safari. // // Each fetcher may be given a comment to be inserted as a label in the logs, // such as // [fetcher setCommentWithFormat:@"retrieve item %@", itemName]; // // Projects may define STRIP_GTM_FETCH_LOGGING to remove logging code. #if !STRIP_GTM_FETCH_LOGGING @interface GTMSessionFetcher (GTMSessionFetcherLogging) // Note: the default logs directory is ~/Desktop/GTMHTTPDebugLogs; it will be // created as needed. If a custom directory is set, the directory should // already exist. + (void)setLoggingDirectory:(NSString *)path; + (NSString *)loggingDirectory; // client apps can turn logging on and off + (void)setLoggingEnabled:(BOOL)isLoggingEnabled; + (BOOL)isLoggingEnabled; // client apps can turn off logging to a file if they want to only check // the fetcher's log property + (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled; + (BOOL)isLoggingToFileEnabled; // client apps can optionally specify process name and date string used in // log file names + (void)setLoggingProcessName:(NSString *)processName; + (NSString *)loggingProcessName; + (void)setLoggingDateStamp:(NSString *)dateStamp; + (NSString *)loggingDateStamp; // client apps can specify the directory for the log for this specific run, // typically to match the directory used by another fetcher class, like: // // [GTMSessionFetcher setLogDirectoryForCurrentRun:[GTMHTTPFetcher logDirectoryForCurrentRun]]; // // Setting this overrides the logging directory, process name, and date stamp when writing // the log file. + (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun; + (NSString *)logDirectoryForCurrentRun; // Prunes old log directories that have not been modified since the provided date. // This will not delete the current run's log directory. + (void)deleteLogDirectoriesOlderThanDate:(NSDate *)date; // internal; called by fetcher - (void)logFetchWithError:(NSError *)error; - (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; - (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: (GTMSessionFetcherBodyStreamProvider)streamProvider; // internal; accessors useful for viewing logs + (NSString *)processNameLogPrefix; + (NSString *)symlinkNameSuffix; + (NSString *)htmlFileName; @end #endif // !STRIP_GTM_FETCH_LOGGING ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif #include #include #import "GTMSessionFetcherLogging.h" #ifndef STRIP_GTM_FETCH_LOGGING #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. #endif #if !STRIP_GTM_FETCH_LOGGING // Sensitive credential strings are replaced in logs with _snip_ // // Apps that must see the contents of sensitive tokens can set this to 1 #ifndef SKIP_GTM_FETCH_LOGGING_SNIPPING #define SKIP_GTM_FETCH_LOGGING_SNIPPING 0 #endif // If GTMReadMonitorInputStream is available, it can be used for // capturing uploaded streams of data // // We locally declare methods of GTMReadMonitorInputStream so we // do not need to import the header, as some projects may not have it available #if !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMReadMonitorInputStream : NSInputStream + (instancetype)inputStreamWithStream:(NSInputStream *)input; @property (assign) id readDelegate; @property (assign) SEL readSelector; @end #else @class GTMReadMonitorInputStream; #endif // !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionFetcher (GTMHTTPFetcherLoggingUtilities) + (NSString *)headersStringForDictionary:(NSDictionary *)dict; + (NSString *)snipSubstringOfString:(NSString *)originalStr betweenStartString:(NSString *)startStr endString:(NSString *)endStr; - (void)inputStream:(GTMReadMonitorInputStream *)stream readIntoBuffer:(void *)buffer length:(int64_t)length; @end @implementation GTMSessionFetcher (GTMSessionFetcherLogging) // fetchers come and fetchers go, but statics are forever static BOOL gIsLoggingEnabled = NO; static BOOL gIsLoggingToFile = YES; static NSString *gLoggingDirectoryPath = nil; static NSString *gLogDirectoryForCurrentRun = nil; static NSString *gLoggingDateStamp = nil; static NSString *gLoggingProcessName = nil; + (void)setLoggingDirectory:(NSString *)path { gLoggingDirectoryPath = [path copy]; } + (NSString *)loggingDirectory { if (!gLoggingDirectoryPath) { NSArray *paths = nil; #if TARGET_IPHONE_SIMULATOR // default to a directory called GTMHTTPDebugLogs into a sandbox-safe // directory that a developer can find easily, the application home paths = @[ NSHomeDirectory() ]; #elif TARGET_OS_IPHONE // Neither ~/Desktop nor ~/Home is writable on an actual iOS, watchOS, or tvOS device. // Put it in ~/Documents. paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); #else // default to a directory called GTMHTTPDebugLogs in the desktop folder paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); #endif NSString *desktopPath = paths.firstObject; if (desktopPath) { NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs"; NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName]; NSFileManager *fileMgr = [NSFileManager defaultManager]; BOOL isDir; BOOL doesFolderExist = [fileMgr fileExistsAtPath:logsFolderPath isDirectory:&isDir]; if (!doesFolderExist) { // make the directory doesFolderExist = [fileMgr createDirectoryAtPath:logsFolderPath withIntermediateDirectories:YES attributes:nil error:NULL]; } if (doesFolderExist) { // it's there; store it in the global gLoggingDirectoryPath = [logsFolderPath copy]; } } } return gLoggingDirectoryPath; } + (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun { // Set the path for this run's logs. gLogDirectoryForCurrentRun = [logDirectoryForCurrentRun copy]; } + (NSString *)logDirectoryForCurrentRun { // make a directory for this run's logs, like SyncProto_logs_10-16_01-56-58PM if (gLogDirectoryForCurrentRun) return gLogDirectoryForCurrentRun; NSString *parentDir = [self loggingDirectory]; NSString *logNamePrefix = [self processNameLogPrefix]; NSString *dateStamp = [self loggingDateStamp]; NSString *dirName = [NSString stringWithFormat:@"%@%@", logNamePrefix, dateStamp]; NSString *logDirectory = [parentDir stringByAppendingPathComponent:dirName]; if (gIsLoggingToFile) { NSFileManager *fileMgr = [NSFileManager defaultManager]; // Be sure that the first time this app runs, it's not writing to a preexisting folder static BOOL gShouldReuseFolder = NO; if (!gShouldReuseFolder) { gShouldReuseFolder = YES; NSString *origLogDir = logDirectory; for (int ctr = 2; ctr < 20; ++ctr) { if (![fileMgr fileExistsAtPath:logDirectory]) break; // append a digit logDirectory = [origLogDir stringByAppendingFormat:@"_%d", ctr]; } } if (![fileMgr createDirectoryAtPath:logDirectory withIntermediateDirectories:YES attributes:nil error:NULL]) return nil; } gLogDirectoryForCurrentRun = logDirectory; return gLogDirectoryForCurrentRun; } + (void)setLoggingEnabled:(BOOL)isLoggingEnabled { gIsLoggingEnabled = isLoggingEnabled; } + (BOOL)isLoggingEnabled { return gIsLoggingEnabled; } + (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled { gIsLoggingToFile = isLoggingToFileEnabled; } + (BOOL)isLoggingToFileEnabled { return gIsLoggingToFile; } + (void)setLoggingProcessName:(NSString *)processName { gLoggingProcessName = [processName copy]; } + (NSString *)loggingProcessName { // get the process name (once per run) replacing spaces with underscores if (!gLoggingProcessName) { NSString *procName = [[NSProcessInfo processInfo] processName]; gLoggingProcessName = [procName stringByReplacingOccurrencesOfString:@" " withString:@"_"]; } return gLoggingProcessName; } + (void)setLoggingDateStamp:(NSString *)dateStamp { gLoggingDateStamp = [dateStamp copy]; } + (NSString *)loggingDateStamp { // We'll pick one date stamp per run, so a run that starts at a later second // will get a unique results html file if (!gLoggingDateStamp) { // produce a string like 08-21_01-41-23PM NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setFormatterBehavior:NSDateFormatterBehavior10_4]; [formatter setDateFormat:@"M-dd_hh-mm-ssa"]; gLoggingDateStamp = [formatter stringFromDate:[NSDate date]]; } return gLoggingDateStamp; } + (NSString *)processNameLogPrefix { static NSString *gPrefix = nil; if (!gPrefix) { NSString *processName = [self loggingProcessName]; gPrefix = [[NSString alloc] initWithFormat:@"%@_log_", processName]; } return gPrefix; } + (NSString *)symlinkNameSuffix { return @"_log_newest.html"; } + (NSString *)htmlFileName { return @"aperçu_http_log.html"; } + (void)deleteLogDirectoriesOlderThanDate:(NSDate *)cutoffDate { NSFileManager *fileMgr = [NSFileManager defaultManager]; NSURL *parentDir = [NSURL fileURLWithPath:[[self class] loggingDirectory]]; NSURL *logDirectoryForCurrentRun = [NSURL fileURLWithPath:[[self class] logDirectoryForCurrentRun]]; NSError *error; NSArray *contents = [fileMgr contentsOfDirectoryAtURL:parentDir includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] options:0 error:&error]; for (NSURL *itemURL in contents) { if ([itemURL isEqual:logDirectoryForCurrentRun]) continue; NSDate *modDate; if ([itemURL getResourceValue:&modDate forKey:NSURLContentModificationDateKey error:&error]) { if ([modDate compare:cutoffDate] == NSOrderedAscending) { if (![fileMgr removeItemAtURL:itemURL error:&error]) { NSLog(@"deleteLogDirectoriesOlderThanDate failed to delete %@: %@", itemURL.path, error); } } } else { NSLog(@"deleteLogDirectoriesOlderThanDate failed to get mod date of %@: %@", itemURL.path, error); } } } // formattedStringFromData returns a prettyprinted string for XML or JSON input, // and a plain string for other input data - (NSString *)formattedStringFromData:(NSData *)inputData contentType:(NSString *)contentType JSON:(NSDictionary **)outJSON { if (!inputData) return nil; // if the content type is JSON and we have the parsing class available, use that if ([contentType hasPrefix:@"application/json"] && inputData.length > 5) { // convert from JSON string to NSObjects and back to a formatted string NSMutableDictionary *obj = [NSJSONSerialization JSONObjectWithData:inputData options:NSJSONReadingMutableContainers error:NULL]; if (obj) { if (outJSON) *outJSON = obj; if ([obj isKindOfClass:[NSMutableDictionary class]]) { // for security and privacy, omit OAuth 2 response access and refresh tokens if ([obj valueForKey:@"refresh_token"] != nil) { [obj setObject:@"_snip_" forKey:@"refresh_token"]; } if ([obj valueForKey:@"access_token"] != nil) { [obj setObject:@"_snip_" forKey:@"access_token"]; } } NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:NULL]; if (data) { NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return jsonStr; } } } #if !TARGET_OS_IPHONE && !GTM_SKIP_LOG_XMLFORMAT // verify that this data starts with the bytes indicating XML NSString *const kXMLLintPath = @"/usr/bin/xmllint"; static BOOL gHasCheckedAvailability = NO; static BOOL gIsXMLLintAvailable = NO; if (!gHasCheckedAvailability) { gIsXMLLintAvailable = [[NSFileManager defaultManager] fileExistsAtPath:kXMLLintPath]; gHasCheckedAvailability = YES; } if (gIsXMLLintAvailable && inputData.length > 5 && strncmp(inputData.bytes, " 0) { // success inputData = formattedData; } } #else // we can't call external tasks on the iPhone; leave the XML unformatted #endif NSString *dataStr = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding]; return dataStr; } // stringFromStreamData creates a string given the supplied data // // If NSString can create a UTF-8 string from the data, then that is returned. // // Otherwise, this routine tries to find a MIME boundary at the beginning of the data block, and // uses that to break up the data into parts. Each part will be used to try to make a UTF-8 string. // For parts that fail, a replacement string showing the part header and <> is supplied // in place of the binary data. - (NSString *)stringFromStreamData:(NSData *)data contentType:(NSString *)contentType { if (!data) return nil; // optimistically, see if the whole data block is UTF-8 NSString *streamDataStr = [self formattedStringFromData:data contentType:contentType JSON:NULL]; if (streamDataStr) return streamDataStr; // Munge a buffer by replacing non-ASCII bytes with underscores, and turn that munged buffer an // NSString. That gives us a string we can use with NSScanner. NSMutableData *mutableData = [NSMutableData dataWithData:data]; unsigned char *bytes = (unsigned char *)mutableData.mutableBytes; for (unsigned int idx = 0; idx < mutableData.length; ++idx) { if (bytes[idx] > 0x7F || bytes[idx] == 0) { bytes[idx] = '_'; } } NSString *mungedStr = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding]; if (mungedStr) { // scan for the boundary string NSString *boundary = nil; NSScanner *scanner = [NSScanner scannerWithString:mungedStr]; if ([scanner scanUpToString:@"\r\n" intoString:&boundary] && [boundary hasPrefix:@"--"]) { // we found a boundary string; use it to divide the string into parts NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary]; // look at each munged part in the original string, and try to convert those into UTF-8 NSMutableArray *origParts = [NSMutableArray array]; NSUInteger offset = 0; for (NSString *mungedPart in mungedParts) { NSUInteger partSize = mungedPart.length; NSData *origPartData = [data subdataWithRange:NSMakeRange(offset, partSize)]; NSString *origPartStr = [[NSString alloc] initWithData:origPartData encoding:NSUTF8StringEncoding]; if (origPartStr) { // we could make this original part into UTF-8; use the string [origParts addObject:origPartStr]; } else { // this part can't be made into UTF-8; scan the header, if we can NSString *header = nil; NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart]; if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) { // we couldn't find a header header = @""; } // make a part string with the header and <> NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%lu bytes>>\r", header, (long)(partSize - header.length)]; [origParts addObject:binStr]; } offset += partSize + boundary.length; } // rejoin the original parts streamDataStr = [origParts componentsJoinedByString:boundary]; } } if (!streamDataStr) { // give up; just make a string showing the uploaded bytes streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", (unsigned int)data.length]; } return streamDataStr; } // logFetchWithError is called following a successful or failed fetch attempt // // This method does all the work for appending to and creating log files - (void)logFetchWithError:(NSError *)error { if (![[self class] isLoggingEnabled]) return; NSString *logDirectory = [[self class] logDirectoryForCurrentRun]; if (!logDirectory) return; NSString *processName = [[self class] loggingProcessName]; // TODO: add Javascript to display response data formatted in hex // each response's NSData goes into its own xml or txt file, though all responses for this run of // the app share a main html file. This counter tracks all fetch responses for this app run. // // we'll use a local variable since this routine may be reentered while waiting for XML formatting // to be completed by an external task static int gResponseCounter = 0; int responseCounter = ++gResponseCounter; NSURLResponse *response = [self response]; NSDictionary *responseHeaders = [self responseHeaders]; NSString *responseDataStr = nil; NSDictionary *responseJSON = nil; // if there's response data, decide what kind of file to put it in based on the first bytes of the // file or on the mime type supplied by the server NSString *responseMIMEType = [response MIMEType]; BOOL isResponseImage = NO; // file name for an image data file NSString *responseDataFileName = nil; int64_t responseDataLength = self.downloadedLength; if (responseDataLength > 0) { NSData *downloadedData = self.downloadedData; if (downloadedData == nil && responseDataLength > 0 && responseDataLength < 20000 && self.destinationFileURL) { // There's a download file that's not too big, so get the data to display from the downloaded // file. NSURL *destinationURL = self.destinationFileURL; downloadedData = [NSData dataWithContentsOfURL:destinationURL]; } NSString *responseType = [responseHeaders valueForKey:@"Content-Type"]; responseDataStr = [self formattedStringFromData:downloadedData contentType:responseType JSON:&responseJSON]; NSString *responseDataExtn = nil; NSData *dataToWrite = nil; if (responseDataStr) { // we were able to make a UTF-8 string from the response data if ([responseMIMEType isEqual:@"application/atom+xml"] || [responseMIMEType hasSuffix:@"/xml"]) { responseDataExtn = @"xml"; dataToWrite = [responseDataStr dataUsingEncoding:NSUTF8StringEncoding]; } } else if ([responseMIMEType isEqual:@"image/jpeg"]) { responseDataExtn = @"jpg"; dataToWrite = downloadedData; isResponseImage = YES; } else if ([responseMIMEType isEqual:@"image/gif"]) { responseDataExtn = @"gif"; dataToWrite = downloadedData; isResponseImage = YES; } else if ([responseMIMEType isEqual:@"image/png"]) { responseDataExtn = @"png"; dataToWrite = downloadedData; isResponseImage = YES; } else { // add more non-text types here } // if we have an extension, save the raw data in a file with that extension if (responseDataExtn && dataToWrite) { // generate a response file base name like NSString *responseBaseName = [NSString stringWithFormat:@"fetch_%d_response", responseCounter]; responseDataFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn]; NSString *responseDataFilePath = [logDirectory stringByAppendingPathComponent:responseDataFileName]; NSError *downloadedError = nil; if (gIsLoggingToFile && ![dataToWrite writeToFile:responseDataFilePath options:0 error:&downloadedError]) { NSLog(@"%@ logging write error:%@ (%@)", [self class], downloadedError, responseDataFileName); } } } // we'll have one main html file per run of the app NSString *htmlName = [[self class] htmlFileName]; NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName]; // if the html file exists (from logging previous fetches) we don't need // to re-write the header or the scripts NSFileManager *fileMgr = [NSFileManager defaultManager]; BOOL didFileExist = [fileMgr fileExistsAtPath:htmlPath]; NSMutableString* outputHTML = [NSMutableString string]; // we need a header to say we'll have UTF-8 text if (!didFileExist) { [outputHTML appendFormat:@"%@ HTTP fetch log %@", processName, [[self class] loggingDateStamp]]; } // now write the visible html elements NSString *copyableFileName = [NSString stringWithFormat:@"fetch_%d.txt", responseCounter]; NSDate *now = [NSDate date]; // write the date & time, the comment, and the link to the plain-text (copyable) log [outputHTML appendFormat:@"%@      ", now]; NSString *comment = [self comment]; if (comment.length > 0) { [outputHTML appendFormat:@"%@      ", comment]; } [outputHTML appendFormat:@"request/response log
", copyableFileName]; NSTimeInterval elapsed = -self.initialBeginFetchDate.timeIntervalSinceNow; [outputHTML appendFormat:@"elapsed: %5.3fsec
", elapsed]; // write the request URL NSURLRequest *request = self.request; NSString *requestMethod = request.HTTPMethod; NSURL *requestURL = request.URL; // Save the request URL for next time in case this redirects. NSString *redirectedFromURLString = [self.redirectedFromURL absoluteString]; self.redirectedFromURL = [requestURL copy]; if (redirectedFromURLString) { [outputHTML appendFormat:@"redirected from %@
", redirectedFromURLString]; } [outputHTML appendFormat:@"request: %@ %@
\n", requestMethod, requestURL]; // write the request headers NSDictionary *requestHeaders = request.allHTTPHeaderFields; NSUInteger numberOfRequestHeaders = requestHeaders.count; if (numberOfRequestHeaders > 0) { // Indicate if the request is authorized; warn if the request is authorized but non-SSL NSString *auth = [requestHeaders objectForKey:@"Authorization"]; NSString *headerDetails = @""; if (auth) { BOOL isInsecure = [[requestURL scheme] isEqual:@"http"]; if (isInsecure) { // 26A0 = ⚠ headerDetails = @"   authorized, non-SSL "; } else { headerDetails = @"   authorized"; } } NSString *cookiesHdr = [requestHeaders objectForKey:@"Cookie"]; if (cookiesHdr) { headerDetails = [headerDetails stringByAppendingString:@"   cookies"]; } NSString *matchHdr = [requestHeaders objectForKey:@"If-Match"]; if (matchHdr) { headerDetails = [headerDetails stringByAppendingString:@"   if-match"]; } matchHdr = [requestHeaders objectForKey:@"If-None-Match"]; if (matchHdr) { headerDetails = [headerDetails stringByAppendingString:@"   if-none-match"]; } [outputHTML appendFormat:@"   headers: %d %@
", (int)numberOfRequestHeaders, headerDetails]; } else { [outputHTML appendFormat:@"   headers: none
"]; } // write the request post data NSData *bodyData = nil; NSData *loggedStreamData = self.loggedStreamData; if (loggedStreamData) { bodyData = loggedStreamData; } else { bodyData = self.bodyData; if (bodyData == nil) { bodyData = self.request.HTTPBody; } } uint64_t bodyDataLength = bodyData.length; if (bodyData.length == 0) { // If the data is in a body upload file URL, read that in if it's not huge. NSURL *bodyFileURL = self.bodyFileURL; if (bodyFileURL) { NSNumber *fileSizeNum = nil; NSError *fileSizeError = nil; if ([bodyFileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:&fileSizeError]) { bodyDataLength = [fileSizeNum unsignedLongLongValue]; if (bodyDataLength > 0 && bodyDataLength < 50000) { bodyData = [NSData dataWithContentsOfURL:bodyFileURL options:NSDataReadingUncached error:&fileSizeError]; } } } } NSString *bodyDataStr = nil; NSString *postType = [requestHeaders valueForKey:@"Content-Type"]; if (bodyDataLength > 0) { [outputHTML appendFormat:@"   data: %llu bytes, %@
\n", bodyDataLength, postType ? postType : @"(no type)"]; NSString *logRequestBody = self.logRequestBody; if (logRequestBody) { bodyDataStr = [logRequestBody copy]; self.logRequestBody = nil; } else { bodyDataStr = [self stringFromStreamData:bodyData contentType:postType]; if (bodyDataStr) { // remove OAuth 2 client secret and refresh token bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr betweenStartString:@"client_secret=" endString:@"&"]; bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr betweenStartString:@"refresh_token=" endString:@"&"]; // remove ClientLogin password bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr betweenStartString:@"&Passwd=" endString:@"&"]; } } } else { // no post data } // write the response status, MIME type, URL NSInteger status = [self statusCode]; if (response) { NSString *statusString = @""; if (status != 0) { if (status == 200 || status == 201) { statusString = [NSString stringWithFormat:@"%ld", (long)status]; // report any JSON-RPC error if ([responseJSON isKindOfClass:[NSDictionary class]]) { NSDictionary *jsonError = [responseJSON objectForKey:@"error"]; if ([jsonError isKindOfClass:[NSDictionary class]]) { NSString *jsonCode = [[jsonError valueForKey:@"code"] description]; NSString *jsonMessage = [jsonError valueForKey:@"message"]; if (jsonCode || jsonMessage) { // 2691 = ⚑ NSString *const jsonErrFmt = @"   JSON error: %@ %@  ⚑"; statusString = [statusString stringByAppendingFormat:jsonErrFmt, jsonCode ? jsonCode : @"", jsonMessage ? jsonMessage : @""]; } } } } else { // purple for anything other than 200 or 201 NSString *flag = status >= 400 ? @" ⚑" : @""; // 2691 = ⚑ NSString *explanation = [NSHTTPURLResponse localizedStringForStatusCode:status]; NSString *const statusFormat = @"%ld %@ %@"; statusString = [NSString stringWithFormat:statusFormat, (long)status, explanation, flag]; } } // show the response URL only if it's different from the request URL NSString *responseURLStr = @""; NSURL *responseURL = response.URL; if (responseURL && ![responseURL isEqual:request.URL]) { NSString *const responseURLFormat = @"response URL: %@
\n"; responseURLStr = [NSString stringWithFormat:responseURLFormat, [responseURL absoluteString]]; } [outputHTML appendFormat:@"response:  status %@
\n%@", statusString, responseURLStr]; // Write the response headers NSUInteger numberOfResponseHeaders = responseHeaders.count; if (numberOfResponseHeaders > 0) { // Indicate if the server is setting cookies NSString *cookiesSet = [responseHeaders valueForKey:@"Set-Cookie"]; NSString *cookiesStr = cookiesSet ? @"  sets cookies" : @""; // Indicate if the server is redirecting NSString *location = [responseHeaders valueForKey:@"Location"]; BOOL isRedirect = status >= 300 && status <= 399 && location != nil; NSString *redirectsStr = isRedirect ? @"  redirects" : @""; [outputHTML appendFormat:@"   headers: %d %@ %@
\n", (int)numberOfResponseHeaders, cookiesStr, redirectsStr]; } else { [outputHTML appendString:@"   headers: none
\n"]; } } // error if (error) { [outputHTML appendFormat:@"Error: %@
\n", error.description]; } // Write the response data if (responseDataFileName) { if (isResponseImage) { // Make a small inline image that links to the full image file [outputHTML appendFormat:@"   data: %lld bytes, %@
", responseDataLength, responseMIMEType]; NSString *const fmt = @"image\n"; [outputHTML appendFormat:fmt, responseDataFileName, responseDataFileName]; } else { // The response data was XML; link to the xml file NSString *const fmt = @"   data: %lld bytes, %@   %@\n"; [outputHTML appendFormat:fmt, responseDataLength, responseMIMEType, responseDataFileName, [responseDataFileName pathExtension]]; } } else { // The response data was not an image; just show the length and MIME type [outputHTML appendFormat:@"   data: %lld bytes, %@\n", responseDataLength, responseMIMEType ? responseMIMEType : @"(no response type)"]; } // Make a single string of the request and response, suitable for copying // to the clipboard and pasting into a bug report NSMutableString *copyable = [NSMutableString string]; if (comment) { [copyable appendFormat:@"%@\n\n", comment]; } [copyable appendFormat:@"%@ elapsed: %5.3fsec\n", now, elapsed]; if (redirectedFromURLString) { [copyable appendFormat:@"Redirected from %@\n", redirectedFromURLString]; } [copyable appendFormat:@"Request: %@ %@\n", requestMethod, requestURL]; if (requestHeaders.count > 0) { [copyable appendFormat:@"Request headers:\n%@\n", [[self class] headersStringForDictionary:requestHeaders]]; } if (bodyDataLength > 0) { [copyable appendFormat:@"Request body: (%llu bytes)\n", bodyDataLength]; if (bodyDataStr) { [copyable appendFormat:@"%@\n", bodyDataStr]; } [copyable appendString:@"\n"]; } if (response) { [copyable appendFormat:@"Response: status %d\n", (int) status]; [copyable appendFormat:@"Response headers:\n%@\n", [[self class] headersStringForDictionary:responseHeaders]]; [copyable appendFormat:@"Response body: (%lld bytes)\n", responseDataLength]; if (responseDataLength > 0) { NSString *logResponseBody = self.logResponseBody; if (logResponseBody) { // The user has provided the response body text. responseDataStr = [logResponseBody copy]; self.logResponseBody = nil; } if (responseDataStr != nil) { [copyable appendFormat:@"%@\n", responseDataStr]; } else { // Even though it's redundant, we'll put in text to indicate that all the bytes are binary. if (self.destinationFileURL) { [copyable appendFormat:@"<<%lld bytes>> to file %@\n", responseDataLength, self.destinationFileURL.path]; } else { [copyable appendFormat:@"<<%lld bytes>>\n", responseDataLength]; } } } } if (error) { [copyable appendFormat:@"Error: %@\n", error]; } // Save to log property before adding the separator self.log = copyable; [copyable appendString:@"-----------------------------------------------------------\n"]; // Write the copyable version to another file (linked to at the top of the html file, above) // // Ideally, something to just copy this to the clipboard like // Copy here." // would work everywhere, but it only works in Safari as of 8/2010 if (gIsLoggingToFile) { NSString *parentDir = [[self class] loggingDirectory]; NSString *copyablePath = [logDirectory stringByAppendingPathComponent:copyableFileName]; NSError *copyableError = nil; if (![copyable writeToFile:copyablePath atomically:NO encoding:NSUTF8StringEncoding error:©ableError]) { // Error writing to file NSLog(@"%@ logging write error:%@ (%@)", [self class], copyableError, copyablePath); } [outputHTML appendString:@"

"]; // Append the HTML to the main output file const char* htmlBytes = outputHTML.UTF8String; NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath append:YES]; [stream open]; [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)]; [stream close]; // Make a symlink to the latest html NSString *const symlinkNameSuffix = [[self class] symlinkNameSuffix]; NSString *symlinkName = [processName stringByAppendingString:symlinkNameSuffix]; NSString *symlinkPath = [parentDir stringByAppendingPathComponent:symlinkName]; [fileMgr removeItemAtPath:symlinkPath error:NULL]; [fileMgr createSymbolicLinkAtPath:symlinkPath withDestinationPath:htmlPath error:NULL]; #if TARGET_OS_IPHONE static BOOL gReportedLoggingPath = NO; if (!gReportedLoggingPath) { gReportedLoggingPath = YES; NSLog(@"GTMSessionFetcher logging to \"%@\"", parentDir); } #endif } } - (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream { if (!inputStream) return nil; if (![GTMSessionFetcher isLoggingEnabled]) return inputStream; [self clearLoggedStreamData]; // Clear any previous data. Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); if (!monitorClass) { NSString const *str = @"<>"; NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; [self appendLoggedStreamData:stringData]; return inputStream; } inputStream = [monitorClass inputStreamWithStream:inputStream]; GTMReadMonitorInputStream *readMonitorInputStream = (GTMReadMonitorInputStream *)inputStream; [readMonitorInputStream setReadDelegate:self]; SEL readSel = @selector(inputStream:readIntoBuffer:length:); [readMonitorInputStream setReadSelector:readSel]; return inputStream; } - (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: (GTMSessionFetcherBodyStreamProvider)streamProvider { if (!streamProvider) return nil; if (![GTMSessionFetcher isLoggingEnabled]) return streamProvider; [self clearLoggedStreamData]; // Clear any previous data. Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); if (!monitorClass) { NSString const *str = @"<>"; NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; [self appendLoggedStreamData:stringData]; return streamProvider; } GTMSessionFetcherBodyStreamProvider loggedStreamProvider = ^(GTMSessionFetcherBodyStreamProviderResponse response) { streamProvider(^(NSInputStream *bodyStream) { bodyStream = [self loggedInputStreamForInputStream:bodyStream]; response(bodyStream); }); }; return loggedStreamProvider; } @end @implementation GTMSessionFetcher (GTMSessionFetcherLoggingUtilities) - (void)inputStream:(GTMReadMonitorInputStream *)stream readIntoBuffer:(void *)buffer length:(int64_t)length { // append the captured data NSData *data = [NSData dataWithBytesNoCopy:buffer length:(NSUInteger)length freeWhenDone:NO]; [self appendLoggedStreamData:data]; } #pragma mark Fomatting Utilities + (NSString *)snipSubstringOfString:(NSString *)originalStr betweenStartString:(NSString *)startStr endString:(NSString *)endStr { #if SKIP_GTM_FETCH_LOGGING_SNIPPING return originalStr; #else if (!originalStr) return nil; // Find the start string, and replace everything between it // and the end string (or the end of the original string) with "_snip_" NSRange startRange = [originalStr rangeOfString:startStr]; if (startRange.location == NSNotFound) return originalStr; // We found the start string NSUInteger originalLength = originalStr.length; NSUInteger startOfTarget = NSMaxRange(startRange); NSRange targetAndRest = NSMakeRange(startOfTarget, originalLength - startOfTarget); NSRange endRange = [originalStr rangeOfString:endStr options:0 range:targetAndRest]; NSRange replaceRange; if (endRange.location == NSNotFound) { // Found no end marker so replace to end of string replaceRange = targetAndRest; } else { // Replace up to the endStr replaceRange = NSMakeRange(startOfTarget, endRange.location - startOfTarget); } NSString *result = [originalStr stringByReplacingCharactersInRange:replaceRange withString:@"_snip_"]; return result; #endif // SKIP_GTM_FETCH_LOGGING_SNIPPING } + (NSString *)headersStringForDictionary:(NSDictionary *)dict { // Format the dictionary in http header style, like // Accept: application/json // Cache-Control: no-cache // Content-Type: application/json; charset=utf-8 // // Pad the key names, but not beyond 16 chars, since long custom header // keys just create too much whitespace NSArray *keys = [dict.allKeys sortedArrayUsingSelector:@selector(compare:)]; NSMutableString *str = [NSMutableString string]; for (NSString *key in keys) { NSString *value = [dict valueForKey:key]; if ([key isEqual:@"Authorization"]) { // Remove OAuth 1 token value = [[self class] snipSubstringOfString:value betweenStartString:@"oauth_token=\"" endString:@"\""]; // Remove OAuth 2 bearer token (draft 16, and older form) value = [[self class] snipSubstringOfString:value betweenStartString:@"Bearer " endString:@"\n"]; value = [[self class] snipSubstringOfString:value betweenStartString:@"OAuth " endString:@"\n"]; // Remove Google ClientLogin value = [[self class] snipSubstringOfString:value betweenStartString:@"GoogleLogin auth=" endString:@"\n"]; } [str appendFormat:@" %@: %@\n", key, value]; } return str; } @end #endif // !STRIP_GTM_FETCH_LOGGING ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // For best performance and convenient usage, fetchers should be generated by a common // GTMSessionFetcherService instance, like // // _fetcherService = [[GTMSessionFetcherService alloc] init]; // GTMSessionFetcher* myFirstFetcher = [_fetcherService fetcherWithRequest:request1]; // GTMSessionFetcher* mySecondFetcher = [_fetcherService fetcherWithRequest:request2]; #import "GTMSessionFetcher.h" GTM_ASSUME_NONNULL_BEGIN // Notifications. // This notification indicates a reusable session has become invalid. It is intended mainly for the // service's unit tests. // // The notification object is the fetcher service. // The invalid session is provided via the userInfo kGTMSessionFetcherServiceSessionKey key. extern NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification; extern NSString *const kGTMSessionFetcherServiceSessionKey; @interface GTMSessionFetcherService : NSObject // Queues of delayed and running fetchers. Each dictionary contains arrays // of GTMSessionFetcher *fetchers, keyed by NSString *host @property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *delayedFetchersByHost; @property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *runningFetchersByHost; // A max value of 0 means no fetchers should be delayed. // The default limit is 10 simultaneous fetchers targeting each host. // This does not apply to fetchers whose useBackgroundSession property is YES. Since services are // not resurrected on an app relaunch, delayed fetchers would effectively be abandoned. @property(atomic, assign) NSUInteger maxRunningFetchersPerHost; // Properties to be applied to each fetcher; see GTMSessionFetcher.h for descriptions @property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; @property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; @property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; @property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; @property(atomic, strong) NSURLCredential *proxyCredential; @property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; @property(atomic, assign) BOOL allowLocalhostRequest; @property(atomic, assign) BOOL allowInvalidServerCertificates; @property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; @property(atomic, assign) NSTimeInterval maxRetryInterval; @property(atomic, assign) NSTimeInterval minRetryInterval; @property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; #if GTM_BACKGROUND_TASK_FETCHING @property(atomic, assign) BOOL skipBackgroundTask; #endif // A default useragent of GTMFetcherStandardUserAgentString(nil) will be given to each fetcher // created by this service unless the request already has a user-agent header set. // This default will be added starting with builds with the SDKs for OS X 10.11 and iOS 9. // // To use the configuration's default user agent, set this property to nil. @property(atomic, copy, GTM_NULLABLE) NSString *userAgent; // The authorizer to attach to the created fetchers. If a specific fetcher should // not authorize its requests, the fetcher's authorizer property may be set to nil // before the fetch begins. @property(atomic, strong, GTM_NULLABLE) id authorizer; // Delegate queue used by the session when calling back to the fetcher. The default // is the main queue. Changing this does not affect the queue used to call back to the // application; that is specified by the callbackQueue property above. @property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; // When enabled, indicates the same session should be used by subsequent fetchers. // // This is enabled by default. @property(atomic, assign) BOOL reuseSession; // Sets the delay until an unused session is invalidated. // The default interval is 60 seconds. // // If the interval is set to 0, then any reused session is not invalidated except by // explicitly invoking -resetSession. Be aware that setting the interval to 0 thus // causes the session's delegate to be retained until the session is explicitly reset. @property(atomic, assign) NSTimeInterval unusedSessionTimeout; // If shouldReuseSession is enabled, this will force creation of a new session when future // fetchers begin. - (void)resetSession; // Create a fetcher // // These methods will return a fetcher. If successfully created, the connection // will hold a strong reference to it for the life of the connection as well. // So the caller doesn't have to hold onto the fetcher explicitly unless they // want to be able to monitor or cancel it. - (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; - (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL; - (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString; // Common method for fetcher creation. // // -fetcherWithRequest:fetcherClass: may be overridden to customize creation of // fetchers. This is the ONLY method in the GTMSessionFetcher library intended to // be overridden. - (id)fetcherWithRequest:(NSURLRequest *)request fetcherClass:(Class)fetcherClass; - (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; - (NSUInteger)numberOfFetchers; // running + delayed fetchers - (NSUInteger)numberOfRunningFetchers; - (NSUInteger)numberOfDelayedFetchers; // Return a list of all running or delayed fetchers. This includes fetchers created // by the service which have been started and have not yet stopped. // // Returns an array of fetcher objects, or nil if none. - (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchers; // Search for running or delayed fetchers with the specified URL. // // Returns an array of fetcher objects found, or nil if none found. - (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchersWithRequestURL:(NSURL *)requestURL; - (void)stopAllFetchers; // Methods for use by the fetcher class only. - (GTM_NULLABLE NSURLSession *)session; - (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; - (GTM_NULLABLE id)sessionDelegate; - (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; // The testBlock can inspect its fetcher parameter's request property to // determine which fetcher is being faked. @property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; @end @interface GTMSessionFetcherService (TestingSupport) // Convenience method to create a fetcher service for testing. // // Fetchers generated by this mock fetcher service will not perform any // network operation, but will invoke callbacks and provide the supplied data // or error to the completion handler. // // You can make more customized mocks by setting the test block property of the service // or fetcher; the test block can inspect the fetcher's request or other properties. // // See the description of the testBlock property below. + (instancetype)mockFetcherServiceWithFakedData:(GTM_NULLABLE NSData *)fakedDataOrNil fakedError:(GTM_NULLABLE NSError *)fakedErrorOrNil; // Spin the run loop and discard events (or, if not on the main thread, just sleep the thread) // until all running and delayed fetchers have completed. // // This is only for use in testing or in tools without a user interface. // // Synchronous fetches should never be done by shipping apps; they are // sufficient reason for rejection from the app store. // // Returns NO if timed out. - (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds; @end @interface GTMSessionFetcherService (BackwardsCompatibilityOnly) // Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. // This method is just for compatibility with the old fetcher. @property(atomic, assign) NSInteger cookieStorageMethod; @end GTM_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif #import "GTMSessionFetcherService.h" NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification = @"kGTMSessionFetcherServiceSessionBecameInvalidNotification"; NSString *const kGTMSessionFetcherServiceSessionKey = @"kGTMSessionFetcherServiceSessionKey"; #if !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionFetcher (ServiceMethods) - (BOOL)beginFetchMayDelay:(BOOL)mayDelay mayAuthorize:(BOOL)mayAuthorize; @end #endif // !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionFetcherService () @property(atomic, strong, readwrite) NSDictionary *delayedFetchersByHost; @property(atomic, strong, readwrite) NSDictionary *runningFetchersByHost; @end // Since NSURLSession doesn't support a separate delegate per task (!), instances of this // class serve as a session delegate trampoline. // // This class maps a session's tasks to fetchers, and resends delegate messages to the task's // fetcher. @interface GTMSessionFetcherSessionDelegateDispatcher : NSObject // The session for the tasks in this dispatcher's task-to-fetcher map. @property(atomic) NSURLSession *session; // The timer interval for invalidating a session that has no active tasks. @property(atomic) NSTimeInterval discardInterval; // The current discard timer. @property(atomic, readonly) NSTimer *discardTimer; - (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService sessionDiscardInterval:(NSTimeInterval)discardInterval; - (void)setFetcher:(GTMSessionFetcher *)fetcher forTask:(NSURLSessionTask *)task; - (void)removeFetcher:(GTMSessionFetcher *)fetcher; // Before using a session, tells the delegate dispatcher to stop the discard timer. - (void)startSessionUsage; // When abandoning a delegate dispatcher, we want to avoid the session retaining // the delegate after tasks complete. - (void)abandon; @end @implementation GTMSessionFetcherService { NSMutableDictionary *_delayedFetchersByHost; NSMutableDictionary *_runningFetchersByHost; NSUInteger _maxRunningFetchersPerHost; // When this ivar is nil, the service will not reuse sessions. GTMSessionFetcherSessionDelegateDispatcher *_delegateDispatcher; // Fetchers will wait on this if another fetcher is creating the shared NSURLSession. dispatch_semaphore_t _sessionCreationSemaphore; dispatch_queue_t _callbackQueue; NSOperationQueue *_delegateQueue; NSHTTPCookieStorage *_cookieStorage; NSString *_userAgent; NSTimeInterval _timeout; NSURLCredential *_credential; // Username & password. NSURLCredential *_proxyCredential; // Credential supplied to proxy servers. NSInteger _cookieStorageMethod; id _authorizer; // For waitForCompletionOfAllFetchersWithTimeout: we need to wait on stopped fetchers since // they've not yet finished invoking their queued callbacks. This array is nil except when // waiting on fetchers. NSMutableArray *_stoppedFetchersToWaitFor; // For fetchers that enqueued their callbacks before stopAllFetchers was called on the service, // set a barrier so the callbacks know to bail out. NSDate *_stoppedAllFetchersDate; } @synthesize maxRunningFetchersPerHost = _maxRunningFetchersPerHost, configuration = _configuration, configurationBlock = _configurationBlock, cookieStorage = _cookieStorage, userAgent = _userAgent, challengeBlock = _challengeBlock, credential = _credential, proxyCredential = _proxyCredential, allowedInsecureSchemes = _allowedInsecureSchemes, allowLocalhostRequest = _allowLocalhostRequest, allowInvalidServerCertificates = _allowInvalidServerCertificates, retryEnabled = _retryEnabled, retryBlock = _retryBlock, maxRetryInterval = _maxRetryInterval, minRetryInterval = _minRetryInterval, properties = _properties, unusedSessionTimeout = _unusedSessionTimeout, testBlock = _testBlock; #if GTM_BACKGROUND_TASK_FETCHING @synthesize skipBackgroundTask = _skipBackgroundTask; #endif - (instancetype)init { self = [super init]; if (self) { _delayedFetchersByHost = [[NSMutableDictionary alloc] init]; _runningFetchersByHost = [[NSMutableDictionary alloc] init]; _maxRunningFetchersPerHost = 10; _cookieStorageMethod = -1; _unusedSessionTimeout = 60.0; _delegateDispatcher = [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self sessionDiscardInterval:_unusedSessionTimeout]; _callbackQueue = dispatch_get_main_queue(); _delegateQueue = [[NSOperationQueue alloc] init]; _delegateQueue.maxConcurrentOperationCount = 1; _delegateQueue.name = @"com.google.GTMSessionFetcher.NSURLSessionDelegateQueue"; _sessionCreationSemaphore = dispatch_semaphore_create(1); // Starting with the SDKs for OS X 10.11/iOS 9, the service has a default useragent. // Apps can remove this and get the default system "CFNetwork" useragent by setting the // fetcher service's userAgent property to nil. #if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) _userAgent = GTMFetcherStandardUserAgentString(nil); #endif } return self; } - (void)dealloc { [self detachAuthorizer]; [_delegateDispatcher abandon]; } #pragma mark Generate a new fetcher // Clients may override this method. Clients should not override any other library methods. - (id)fetcherWithRequest:(NSURLRequest *)request fetcherClass:(Class)fetcherClass { GTMSessionFetcher *fetcher = [[fetcherClass alloc] initWithRequest:request configuration:self.configuration]; fetcher.callbackQueue = self.callbackQueue; fetcher.sessionDelegateQueue = self.sessionDelegateQueue; fetcher.challengeBlock = self.challengeBlock; fetcher.credential = self.credential; fetcher.proxyCredential = self.proxyCredential; fetcher.authorizer = self.authorizer; fetcher.cookieStorage = self.cookieStorage; fetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; fetcher.allowLocalhostRequest = self.allowLocalhostRequest; fetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; fetcher.configurationBlock = self.configurationBlock; fetcher.retryEnabled = self.retryEnabled; fetcher.retryBlock = self.retryBlock; fetcher.maxRetryInterval = self.maxRetryInterval; fetcher.minRetryInterval = self.minRetryInterval; fetcher.properties = self.properties; fetcher.service = self; if (self.cookieStorageMethod >= 0) { [fetcher setCookieStorageMethod:self.cookieStorageMethod]; } #if GTM_BACKGROUND_TASK_FETCHING fetcher.skipBackgroundTask = self.skipBackgroundTask; #endif NSString *userAgent = self.userAgent; if (userAgent.length > 0 && [request valueForHTTPHeaderField:@"User-Agent"] == nil) { [fetcher setRequestValue:userAgent forHTTPHeaderField:@"User-Agent"]; } fetcher.testBlock = self.testBlock; return fetcher; } - (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request { return [self fetcherWithRequest:request fetcherClass:[GTMSessionFetcher class]]; } - (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL { return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; } - (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString { NSURL *url = [NSURL URLWithString:requestURLString]; return [self fetcherWithURL:url]; } // Returns a session for the fetcher's host, or nil. - (NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSURLSession *session = _delegateDispatcher.session; return session; } } // Returns a session for the fetcher's host, or nil. For shared sessions, this // waits on a semaphore, blocking other fetchers while the caller creates the // session if needed. - (NSURLSession *)sessionForFetcherCreation { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (!_delegateDispatcher) { // This fetcher is creating a non-shared session, so skip the semaphore usage. return nil; } } // Wait if another fetcher is currently creating a session; avoid waiting // inside the @synchronized block, as that can deadlock. dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); @synchronized(self) { GTMSessionMonitorSynchronized(self); // Before getting the NSURLSession for task creation, it is // important to invalidate and nil out the session discard timer; otherwise // the session can be invalidated between when it is returned to the // fetcher, and when the fetcher attempts to create its NSURLSessionTask. [_delegateDispatcher startSessionUsage]; NSURLSession *session = _delegateDispatcher.session; if (session) { // The calling fetcher will receive a preexisting session, so // we can allow other fetchers to create a session. dispatch_semaphore_signal(_sessionCreationSemaphore); } else { // No existing session was obtained, so the calling fetcher will create the session; // it *must* invoke fetcherDidCreateSession: to signal the dispatcher's semaphore after // the session has been created (or fails to be created) to avoid a hang. } return session; } } - (id)sessionDelegate { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _delegateDispatcher; } } #pragma mark Queue Management - (void)addRunningFetcher:(GTMSessionFetcher *)fetcher forHost:(NSString *)host { // Add to the array of running fetchers for this host, creating the array if needed. NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; if (runningForHost == nil) { runningForHost = [NSMutableArray arrayWithObject:fetcher]; [_runningFetchersByHost setObject:runningForHost forKey:host]; } else { [runningForHost addObject:fetcher]; } } - (void)addDelayedFetcher:(GTMSessionFetcher *)fetcher forHost:(NSString *)host { // Add to the array of delayed fetchers for this host, creating the array if needed. NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; if (delayedForHost == nil) { delayedForHost = [NSMutableArray arrayWithObject:fetcher]; [_delayedFetchersByHost setObject:delayedForHost forKey:host]; } else { [delayedForHost addObject:fetcher]; } } - (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSString *host = fetcher.request.URL.host; if (host == nil) { return NO; } NSArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; NSUInteger idx = [delayedForHost indexOfObjectIdenticalTo:fetcher]; BOOL isDelayed = (delayedForHost != nil) && (idx != NSNotFound); return isDelayed; } } - (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher { // Entry point from the fetcher NSURL *requestURL = fetcher.request.URL; NSString *host = requestURL.host; // Addresses "file:///path" case where localhost is the implicit host. if (host.length == 0 && [requestURL isFileURL]) { host = @"localhost"; } if (host.length == 0) { // Data URIs legitimately have no host, reject other hostless URLs. GTMSESSION_ASSERT_DEBUG([[requestURL scheme] isEqual:@"data"], @"%@ lacks host", fetcher); return YES; } BOOL shouldBeginResult; @synchronized(self) { GTMSessionMonitorSynchronized(self); NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; if (runningForHost != nil && [runningForHost indexOfObjectIdenticalTo:fetcher] != NSNotFound) { GTMSESSION_ASSERT_DEBUG(NO, @"%@ was already running", fetcher); return YES; } BOOL shouldRunNow = (fetcher.usingBackgroundSession || _maxRunningFetchersPerHost == 0 || _maxRunningFetchersPerHost > [[self class] numberOfNonBackgroundSessionFetchers:runningForHost]); if (shouldRunNow) { [self addRunningFetcher:fetcher forHost:host]; shouldBeginResult = YES; } else { [self addDelayedFetcher:fetcher forHost:host]; shouldBeginResult = NO; } } // @synchronized(self) // We'll save the host that serves as the key for this fetcher's array // to avoid any chance of the underlying request changing, stranding // the fetcher in the wrong array fetcher.serviceHost = host; return shouldBeginResult; } - (void)startFetcher:(GTMSessionFetcher *)fetcher { [fetcher beginFetchMayDelay:NO mayAuthorize:YES]; } // Internal utility. Returns a fetcher's delegate if it's a dispatcher, or nil if the fetcher // is its own delegate and has no dispatcher. - (GTMSessionFetcherSessionDelegateDispatcher *)delegateDispatcherForFetcher:(GTMSessionFetcher *)fetcher { GTMSessionCheckNotSynchronized(self); NSURLSession *fetcherSession = fetcher.session; if (fetcherSession) { id fetcherDelegate = fetcherSession.delegate; BOOL hasDispatcher = (fetcherDelegate != nil && fetcherDelegate != fetcher); if (hasDispatcher) { GTMSESSION_ASSERT_DEBUG([fetcherDelegate isKindOfClass:[GTMSessionFetcherSessionDelegateDispatcher class]], @"Fetcher delegate class: %@", [fetcherDelegate class]); return (GTMSessionFetcherSessionDelegateDispatcher *)fetcherDelegate; } } return nil; } - (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher { if (fetcher.canShareSession) { NSURLSession *fetcherSession = fetcher.session; GTMSESSION_ASSERT_DEBUG(fetcherSession != nil, @"Fetcher missing its session: %@", fetcher); GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = [self delegateDispatcherForFetcher:fetcher]; if (delegateDispatcher) { GTMSESSION_ASSERT_DEBUG(delegateDispatcher.session == nil, @"Fetcher made an extra session: %@", fetcher); // Save this fetcher's session. delegateDispatcher.session = fetcherSession; // Allow other fetchers to request this session now. dispatch_semaphore_signal(_sessionCreationSemaphore); } } } - (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher { // If this fetcher has a separate delegate with a shared session, then // this fetcher should be added to the delegate's map of tasks to fetchers. GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = [self delegateDispatcherForFetcher:fetcher]; if (delegateDispatcher) { GTMSESSION_ASSERT_DEBUG(fetcher.canShareSession, @"Inappropriate shared session: %@", fetcher); // There should already be a session, from this or a previous fetcher. // // Sanity check that the fetcher's session is the delegate's shared session. NSURLSession *sharedSession = delegateDispatcher.session; NSURLSession *fetcherSession = fetcher.session; GTMSESSION_ASSERT_DEBUG(sharedSession != nil, @"Missing delegate session: %@", fetcher); GTMSESSION_ASSERT_DEBUG(fetcherSession == sharedSession, @"Inconsistent session: %@ %@ (shared: %@)", fetcher, fetcherSession, sharedSession); if (sharedSession != nil && fetcherSession == sharedSession) { NSURLSessionTask *task = fetcher.sessionTask; GTMSESSION_ASSERT_DEBUG(task != nil, @"Missing session task: %@", fetcher); if (task) { [delegateDispatcher setFetcher:fetcher forTask:task]; } } } } - (void)stopFetcher:(GTMSessionFetcher *)fetcher { [fetcher stopFetching]; } - (void)fetcherDidStop:(GTMSessionFetcher *)fetcher { // Entry point from the fetcher NSString *host = fetcher.serviceHost; if (!host) { // fetcher has been stopped previously return; } // This removeFetcher: invocation is a fallback; typically, fetchers are removed from the task // map when the task completes. GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = [self delegateDispatcherForFetcher:fetcher]; [delegateDispatcher removeFetcher:fetcher]; NSMutableArray *fetchersToStart; @synchronized(self) { GTMSessionMonitorSynchronized(self); // If a test is waiting for all fetchers to stop, it needs to wait for this one // to invoke its callbacks on the callback queue. [_stoppedFetchersToWaitFor addObject:fetcher]; NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; [runningForHost removeObject:fetcher]; NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; [delayedForHost removeObject:fetcher]; while (delayedForHost.count > 0 && [[self class] numberOfNonBackgroundSessionFetchers:runningForHost] < _maxRunningFetchersPerHost) { // Start another delayed fetcher running, scanning for the minimum // priority value, defaulting to FIFO for equal priorities GTMSessionFetcher *nextFetcher = nil; for (GTMSessionFetcher *delayedFetcher in delayedForHost) { if (nextFetcher == nil || delayedFetcher.servicePriority < nextFetcher.servicePriority) { nextFetcher = delayedFetcher; } } if (nextFetcher) { [self addRunningFetcher:nextFetcher forHost:host]; runningForHost = [_runningFetchersByHost objectForKey:host]; [delayedForHost removeObjectIdenticalTo:nextFetcher]; if (!fetchersToStart) { fetchersToStart = [NSMutableArray array]; } [fetchersToStart addObject:nextFetcher]; } } if (runningForHost.count == 0) { // None left; remove the empty array [_runningFetchersByHost removeObjectForKey:host]; } if (delayedForHost.count == 0) { [_delayedFetchersByHost removeObjectForKey:host]; } } // @synchronized(self) // Start fetchers outside of the synchronized block to avoid a deadlock. for (GTMSessionFetcher *nextFetcher in fetchersToStart) { [self startFetcher:nextFetcher]; } // The fetcher is no longer in the running or the delayed array, // so remove its host and thread properties fetcher.serviceHost = nil; } - (NSUInteger)numberOfFetchers { NSUInteger running = [self numberOfRunningFetchers]; NSUInteger delayed = [self numberOfDelayedFetchers]; return running + delayed; } - (NSUInteger)numberOfRunningFetchers { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSUInteger sum = 0; for (NSString *host in _runningFetchersByHost) { NSArray *fetchers = [_runningFetchersByHost objectForKey:host]; sum += fetchers.count; } return sum; } } - (NSUInteger)numberOfDelayedFetchers { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSUInteger sum = 0; for (NSString *host in _delayedFetchersByHost) { NSArray *fetchers = [_delayedFetchersByHost objectForKey:host]; sum += fetchers.count; } return sum; } } - (NSArray *)issuedFetchers { @synchronized(self) { GTMSessionMonitorSynchronized(self); NSMutableArray *allFetchers = [NSMutableArray array]; void (^accumulateFetchers)(id, id, BOOL *) = ^(NSString *host, NSArray *fetchersForHost, BOOL *stop) { [allFetchers addObjectsFromArray:fetchersForHost]; }; [_runningFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; [_delayedFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; GTMSESSION_ASSERT_DEBUG(allFetchers.count == [NSSet setWithArray:allFetchers].count, @"Fetcher appears multiple times\n running: %@\n delayed: %@", _runningFetchersByHost, _delayedFetchersByHost); return allFetchers.count > 0 ? allFetchers : nil; } } - (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL { NSString *host = requestURL.host; if (host.length == 0) return nil; NSURL *targetURL = [requestURL absoluteURL]; NSArray *allFetchers = [self issuedFetchers]; NSIndexSet *indexes = [allFetchers indexesOfObjectsPassingTest:^BOOL(GTMSessionFetcher *fetcher, NSUInteger idx, BOOL *stop) { NSURL *fetcherURL = [fetcher.request.URL absoluteURL]; return [fetcherURL isEqual:targetURL]; }]; NSArray *result = nil; if (indexes.count > 0) { result = [allFetchers objectsAtIndexes:indexes]; } return result; } - (void)stopAllFetchers { NSArray *delayedFetchersByHost; NSArray *runningFetchersByHost; @synchronized(self) { GTMSessionMonitorSynchronized(self); // Set the time barrier so fetchers know not to call back even if // the stop calls below occur after the fetchers naturally // stopped and so were removed from _runningFetchersByHost, // but while the callbacks were already enqueued before stopAllFetchers // was invoked. _stoppedAllFetchersDate = [[NSDate alloc] init]; // Remove fetchers from the delayed list to avoid fetcherDidStop: from // starting more fetchers running as a side effect of stopping one delayedFetchersByHost = _delayedFetchersByHost.allValues; [_delayedFetchersByHost removeAllObjects]; runningFetchersByHost = _runningFetchersByHost.allValues; [_runningFetchersByHost removeAllObjects]; } for (NSArray *delayedForHost in delayedFetchersByHost) { for (GTMSessionFetcher *fetcher in delayedForHost) { [self stopFetcher:fetcher]; } } for (NSArray *runningForHost in runningFetchersByHost) { for (GTMSessionFetcher *fetcher in runningForHost) { [self stopFetcher:fetcher]; } } } - (NSDate *)stoppedAllFetchersDate { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _stoppedAllFetchersDate; } } #pragma mark Accessors - (BOOL)reuseSession { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _delegateDispatcher != nil; } } - (void)setReuseSession:(BOOL)shouldReuse { @synchronized(self) { GTMSessionMonitorSynchronized(self); BOOL wasReusing = (_delegateDispatcher != nil); if (shouldReuse != wasReusing) { [self abandonDispatcher]; if (shouldReuse) { _delegateDispatcher = [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self sessionDiscardInterval:_unusedSessionTimeout]; } else { _delegateDispatcher = nil; } } } } - (void)resetSession { GTMSessionCheckNotSynchronized(self); dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); @synchronized(self) { GTMSessionMonitorSynchronized(self); [self resetSessionInternal]; } dispatch_semaphore_signal(_sessionCreationSemaphore); } - (void)resetSessionInternal { GTMSessionCheckSynchronized(self); // The old dispatchers may be retained as delegates of any ongoing sessions by those sessions. if (_delegateDispatcher) { [self abandonDispatcher]; _delegateDispatcher = [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self sessionDiscardInterval:_unusedSessionTimeout]; } } - (void)resetSessionForDispatcherDiscardTimer:(NSTimer *)timer { GTMSessionCheckNotSynchronized(self); dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_delegateDispatcher.discardTimer == timer) { // If the delegate dispatcher's current discardTimer is the same object as the timer // that fired, no fetcher has recently attempted to start using the session by calling // startSessionUsage, which invalidates and nils out the timer. [self resetSessionInternal]; } else { // A fetcher has invalidated the timer between its triggering and now, potentially // meaning a fetcher has requested access to the NSURLSession, and may be in the process // of starting a new task. The dispatcher should not be abandoned, as this can lead // to a race condition between calling -finishTasksAndInvalidate on the NSURLSession // and the fetcher attempting to create a new task. } } dispatch_semaphore_signal(_sessionCreationSemaphore); } - (NSTimeInterval)unusedSessionTimeout { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _unusedSessionTimeout; } } - (void)setUnusedSessionTimeout:(NSTimeInterval)timeout { @synchronized(self) { GTMSessionMonitorSynchronized(self); _unusedSessionTimeout = timeout; _delegateDispatcher.discardInterval = timeout; } } // This method should be called inside of @synchronized(self) - (void)abandonDispatcher { GTMSessionCheckSynchronized(self); [_delegateDispatcher abandon]; } - (NSDictionary *)runningFetchersByHost { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_runningFetchersByHost copy]; } } - (void)setRunningFetchersByHost:(NSDictionary *)dict { @synchronized(self) { GTMSessionMonitorSynchronized(self); _runningFetchersByHost = [dict mutableCopy]; } } - (NSDictionary *)delayedFetchersByHost { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_delayedFetchersByHost copy]; } } - (void)setDelayedFetchersByHost:(NSDictionary *)dict { @synchronized(self) { GTMSessionMonitorSynchronized(self); _delayedFetchersByHost = [dict mutableCopy]; } } - (id)authorizer { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _authorizer; } } - (void)setAuthorizer:(id)obj { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (obj != _authorizer) { [self detachAuthorizer]; } _authorizer = obj; } // Use the fetcher service for the authorization fetches if the auth // object supports fetcher services if ([obj respondsToSelector:@selector(setFetcherService:)]) { #if GTM_USE_SESSION_FETCHER [obj setFetcherService:self]; #else [obj setFetcherService:(id)self]; #endif } } // This should be called inside a @synchronized(self) block except during dealloc. - (void)detachAuthorizer { // This method is called by the fetcher service's dealloc and setAuthorizer: // methods; do not override. // // The fetcher service retains the authorizer, and the authorizer has a // weak pointer to the fetcher service (a non-zeroing pointer for // compatibility with iOS 4 and Mac OS X 10.5/10.6.) // // When this fetcher service no longer uses the authorizer, we want to remove // the authorizer's dependence on the fetcher service. Authorizers can still // function without a fetcher service. if ([_authorizer respondsToSelector:@selector(fetcherService)]) { id authFetcherService = [_authorizer fetcherService]; if (authFetcherService == self) { [_authorizer setFetcherService:nil]; } } } - (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _callbackQueue; } // @synchronized(self) } - (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { @synchronized(self) { GTMSessionMonitorSynchronized(self); _callbackQueue = queue ?: dispatch_get_main_queue(); } // @synchronized(self) } - (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _delegateQueue; } // @synchronized(self) } - (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { @synchronized(self) { GTMSessionMonitorSynchronized(self); _delegateQueue = queue ?: [NSOperationQueue mainQueue]; } // @synchronized(self) } - (NSOperationQueue *)delegateQueue { // Provided for compatibility with the old fetcher service. The gtm-oauth2 code respects // any custom delegate queue for calling the app. return nil; } + (NSUInteger)numberOfNonBackgroundSessionFetchers:(NSArray *)fetchers { NSUInteger sum = 0; for (GTMSessionFetcher *fetcher in fetchers) { if (!fetcher.usingBackgroundSession) { ++sum; } } return sum; } @end @implementation GTMSessionFetcherService (TestingSupport) + (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil fakedError:(NSError *)fakedErrorOrNil { #if !GTM_DISABLE_FETCHER_TEST_BLOCK NSURL *url = [NSURL URLWithString:@"http://example.invalid"]; NSHTTPURLResponse *fakedResponse = [[NSHTTPURLResponse alloc] initWithURL:url statusCode:(fakedErrorOrNil ? 500 : 200) HTTPVersion:@"HTTP/1.1" headerFields:nil]; GTMSessionFetcherService *service = [[self alloc] init]; service.allowedInsecureSchemes = @[ @"http" ]; service.testBlock = ^(GTMSessionFetcher *fetcherToTest, GTMSessionFetcherTestResponse testResponse) { testResponse(fakedResponse, fakedDataOrNil, fakedErrorOrNil); }; return service; #else GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled"); return nil; #endif // GTM_DISABLE_FETCHER_TEST_BLOCK } #pragma mark Synchronous Wait for Unit Testing - (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds { NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; _stoppedFetchersToWaitFor = [NSMutableArray array]; BOOL shouldSpinRunLoop = [NSThread isMainThread]; const NSTimeInterval kSpinInterval = 0.001; BOOL didTimeOut = NO; while (([self numberOfFetchers] > 0 || _stoppedFetchersToWaitFor.count > 0)) { didTimeOut = [giveUpDate timeIntervalSinceNow] < 0; if (didTimeOut) break; GTMSessionFetcher *stoppedFetcher = _stoppedFetchersToWaitFor.firstObject; if (stoppedFetcher) { [_stoppedFetchersToWaitFor removeObject:stoppedFetcher]; [stoppedFetcher waitForCompletionWithTimeout:10.0 * kSpinInterval]; } if (shouldSpinRunLoop) { NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; } else { [NSThread sleepForTimeInterval:kSpinInterval]; } } _stoppedFetchersToWaitFor = nil; return !didTimeOut; } @end @implementation GTMSessionFetcherService (BackwardsCompatibilityOnly) - (NSInteger)cookieStorageMethod { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _cookieStorageMethod; } } - (void)setCookieStorageMethod:(NSInteger)cookieStorageMethod { @synchronized(self) { GTMSessionMonitorSynchronized(self); _cookieStorageMethod = cookieStorageMethod; } } @end @implementation GTMSessionFetcherSessionDelegateDispatcher { __weak GTMSessionFetcherService *_parentService; NSURLSession *_session; // The task map maps NSURLSessionTasks to GTMSessionFetchers NSMutableDictionary *_taskToFetcherMap; // The discard timer will invalidate sessions after the session's last task completes. NSTimer *_discardTimer; NSTimeInterval _discardInterval; } @synthesize discardInterval = _discardInterval, session = _session; - (instancetype)init { [self doesNotRecognizeSelector:_cmd]; return nil; } - (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService sessionDiscardInterval:(NSTimeInterval)discardInterval { self = [super init]; if (self) { _discardInterval = discardInterval; _parentService = parentService; } return self; } - (NSString *)description { return [NSString stringWithFormat:@"%@ %p %@ %@", [self class], self, _session ?: @"", _taskToFetcherMap.count > 0 ? _taskToFetcherMap : @""]; } - (NSTimer *)discardTimer { GTMSessionCheckNotSynchronized(self); @synchronized(self) { return _discardTimer; } } // This method should be called inside of a @synchronized(self) block. - (void)startDiscardTimer { GTMSessionCheckSynchronized(self); [_discardTimer invalidate]; _discardTimer = nil; if (_discardInterval > 0) { _discardTimer = [NSTimer timerWithTimeInterval:_discardInterval target:self selector:@selector(discardTimerFired:) userInfo:nil repeats:NO]; [_discardTimer setTolerance:(_discardInterval / 10)]; [[NSRunLoop mainRunLoop] addTimer:_discardTimer forMode:NSRunLoopCommonModes]; } } // This method should be called inside of a @synchronized(self) block. - (void)destroyDiscardTimer { GTMSessionCheckSynchronized(self); [_discardTimer invalidate]; _discardTimer = nil; } - (void)discardTimerFired:(NSTimer *)timer { GTMSessionFetcherService *service; @synchronized(self) { GTMSessionMonitorSynchronized(self); NSUInteger numberOfTasks = _taskToFetcherMap.count; if (numberOfTasks == 0) { service = _parentService; } } // Inform the service that the discard timer has fired, and should check whether the // service can abandon us. -resetSession cannot be called directly, as there is a // race condition that must be guarded against with the NSURLSession being returned // from sessionForFetcherCreation outside other locks. The service can take steps // to prevent resetting the session if that has occurred. // // The service must be called from outside the @synchronized block. [service resetSessionForDispatcherDiscardTimer:timer]; } - (void)abandon { @synchronized(self) { GTMSessionMonitorSynchronized(self); [self destroySessionAndTimer]; } } - (void)startSessionUsage { @synchronized(self) { GTMSessionMonitorSynchronized(self); [self destroyDiscardTimer]; } } // This method should be called inside of a @synchronized(self) block. - (void)destroySessionAndTimer { GTMSessionCheckSynchronized(self); [self destroyDiscardTimer]; // Break any retain cycle from the session holding the delegate. [_session finishTasksAndInvalidate]; // Immediately clear the session so no new task may be issued with it. // // The _taskToFetcherMap needs to stay valid until the outstanding tasks finish. _session = nil; } - (void)setFetcher:(GTMSessionFetcher *)fetcher forTask:(NSURLSessionTask *)task { GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"missing fetcher"); @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_taskToFetcherMap == nil) { _taskToFetcherMap = [[NSMutableDictionary alloc] init]; } if (fetcher) { [_taskToFetcherMap setObject:fetcher forKey:task]; [self destroyDiscardTimer]; } } } - (void)removeFetcher:(GTMSessionFetcher *)fetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); // Typically, a fetcher should be removed when its task invokes // URLSession:task:didCompleteWithError:. // // When fetching with a testBlock, though, the task completed delegate // method may not be invoked, requiring cleanup here. NSArray *tasks = [_taskToFetcherMap allKeysForObject:fetcher]; GTMSESSION_ASSERT_DEBUG(tasks.count <= 1, @"fetcher task not unmapped: %@", tasks); [_taskToFetcherMap removeObjectsForKeys:tasks]; if (_taskToFetcherMap.count == 0) { [self startDiscardTimer]; } } } // This helper method provides synchronized access to the task map for the delegate // methods below. - (id)fetcherForTask:(NSURLSessionTask *)task { @synchronized(self) { GTMSessionMonitorSynchronized(self); return [_taskToFetcherMap objectForKey:task]; } } - (void)removeTaskFromMap:(NSURLSessionTask *)task { @synchronized(self) { GTMSessionMonitorSynchronized(self); [_taskToFetcherMap removeObjectForKey:task]; } } - (void)setSession:(NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); _session = session; } } - (NSURLSession *)session { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _session; } } - (NSTimeInterval)discardInterval { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _discardInterval; } } - (void)setDiscardInterval:(NSTimeInterval)interval { @synchronized(self) { GTMSessionMonitorSynchronized(self); _discardInterval = interval; } } // NSURLSessionDelegate protocol methods. // - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session; // // TODO(seh): How do we route this to an appropriate fetcher? - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", [self class], self, session, error); NSDictionary *localTaskToFetcherMap; @synchronized(self) { GTMSessionMonitorSynchronized(self); _session = nil; localTaskToFetcherMap = [_taskToFetcherMap copy]; } // Any "suspended" tasks may not have received callbacks from NSURLSession when the session // completes; we'll call them now. [localTaskToFetcherMap enumerateKeysAndObjectsUsingBlock:^(NSURLSessionTask *task, GTMSessionFetcher *fetcher, BOOL *stop) { if (fetcher.session == session) { // Our delegate method URLSession:task:didCompleteWithError: will rely on // _taskToFetcherMap so that should still contain this fetcher. NSError *canceledError = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]; [self URLSession:session task:task didCompleteWithError:canceledError]; } else { GTMSESSION_ASSERT_DEBUG(0, @"Unexpected session in fetcher: %@ has %@ (expected %@)", fetcher, fetcher.session, session); } }]; // Our tests rely on this notification to know the session discard timer fired. NSDictionary *userInfo = @{ kGTMSessionFetcherServiceSessionKey : session }; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:kGTMSessionFetcherServiceSessionBecameInvalidNotification object:_parentService userInfo:userInfo]; } #pragma mark - NSURLSessionTaskDelegate // NSURLSessionTaskDelegate protocol methods. // // We won't test here if the fetcher responds to these since we only want this // class to implement the same delegate methods the fetcher does (so NSURLSession's // tests for respondsToSelector: will have the same result whether the session // delegate is the fetcher or this dispatcher.) - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { id fetcher = [self fetcherForTask:task]; [fetcher URLSession:session task:task willPerformHTTPRedirection:response newRequest:request completionHandler:completionHandler]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))handler { id fetcher = [self fetcherForTask:task]; [fetcher URLSession:session task:task didReceiveChallenge:challenge completionHandler:handler]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))handler { id fetcher = [self fetcherForTask:task]; [fetcher URLSession:session task:task needNewBodyStream:handler]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { id fetcher = [self fetcherForTask:task]; [fetcher URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { id fetcher = [self fetcherForTask:task]; // This is the usual way tasks are removed from the task map. [self removeTaskFromMap:task]; [fetcher URLSession:session task:task didCompleteWithError:error]; } // NSURLSessionDataDelegate protocol methods. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))handler { id fetcher = [self fetcherForTask:dataTask]; [fetcher URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:handler]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { id fetcher = [self fetcherForTask:dataTask]; GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"Missing fetcher for %@", dataTask); [self removeTaskFromMap:dataTask]; if (fetcher) { GTMSESSION_ASSERT_DEBUG([fetcher isKindOfClass:[GTMSessionFetcher class]], @"Expecting GTMSessionFetcher"); [self setFetcher:(GTMSessionFetcher *)fetcher forTask:downloadTask]; } [fetcher URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { id fetcher = [self fetcherForTask:dataTask]; [fetcher URLSession:session dataTask:dataTask didReceiveData:data]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *))handler { id fetcher = [self fetcherForTask:dataTask]; [fetcher URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:handler]; } // NSURLSessionDownloadDelegate protocol methods. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { id fetcher = [self fetcherForTask:downloadTask]; [fetcher URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalWritten totalBytesExpectedToWrite:(int64_t)totalExpected { id fetcher = [self fetcherForTask:downloadTask]; [fetcher URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalWritten totalBytesExpectedToWrite:totalExpected]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { id fetcher = [self fetcherForTask:downloadTask]; [fetcher URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; } @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // GTMSessionUploadFetcher implements Google's resumable upload protocol. // // This subclass of GTMSessionFetcher simulates the series of fetches // needed for chunked upload as a single fetch operation. // // Protocol document: TBD // // To the client, the only fetcher that exists is this class; the subsidiary // fetchers needed for uploading chunks are not visible (though the most recent // chunk fetcher may be accessed via the -activeFetcher or -chunkFetcher methods, and // -responseHeaders and -statusCode reflect results from the most recent chunk // fetcher.) // // Chunk fetchers are discarded as soon as they have completed. // // Note: Unlike the fetcher superclass, the methods of GTMSessionUploadFetcher should // only be used from the main thread until further work is done to make this subclass // thread-safe. #import "GTMSessionFetcher.h" #import "GTMSessionFetcherService.h" GTM_ASSUME_NONNULL_BEGIN // Unless an application knows it needs a smaller chunk size, it should use the standard // chunk size, which sends the entire file as a single chunk to minimize upload overhead. extern int64_t const kGTMSessionUploadFetcherStandardChunkSize; // When uploading requires data buffer allocations (such as uploading from an NSData or // an NSFileHandle) this is the maximum buffer size that will be created by the fetcher. extern int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize; // Notification that the upload location URL was provided by the server. extern NSString *const kGTMSessionFetcherUploadLocationObtainedNotification; // Block to provide data during uploads. // // Response data may be allocated with dataWithBytesNoCopy:length:freeWhenDone: for efficiency, // and released after the response block returns. // // Pass nil as the data (and optionally an NSError) for a failure. typedef void (^GTMSessionUploadFetcherDataProviderResponse)(NSData * GTM_NULLABLE_TYPE data, NSError * GTM_NULLABLE_TYPE error); typedef void (^GTMSessionUploadFetcherDataProvider)(int64_t offset, int64_t length, GTMSessionUploadFetcherDataProviderResponse response); @interface GTMSessionUploadFetcher : GTMSessionFetcher // Create an upload fetcher specifying either the request or the resume location URL, // then set an upload data source using one of these: // // setUploadFileURL: // setUploadDataLength:provider: // setUploadFileHandle: // setUploadData: + (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request uploadMIMEType:(NSString *)uploadMIMEType chunkSize:(int64_t)chunkSize fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; + (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL uploadMIMEType:(NSString *)uploadMIMEType chunkSize:(int64_t)chunkSize fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; - (void)setUploadDataLength:(int64_t)fullLength provider:(GTM_NULLABLE GTMSessionUploadFetcherDataProvider)block; + (NSArray *)uploadFetchersForBackgroundSessions; + (GTM_NULLABLE instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier; - (void)pauseFetching; - (void)resumeFetching; - (BOOL)isPaused; @property(atomic, strong, GTM_NULLABLE) NSURL *uploadLocationURL; @property(atomic, strong, GTM_NULLABLE) NSData *uploadData; @property(atomic, strong, GTM_NULLABLE) NSURL *uploadFileURL; @property(atomic, strong, GTM_NULLABLE) NSFileHandle *uploadFileHandle; @property(atomic, copy, readonly, GTM_NULLABLE) GTMSessionUploadFetcherDataProvider uploadDataProvider; @property(atomic, copy) NSString *uploadMIMEType; @property(atomic, assign) int64_t chunkSize; @property(atomic, readonly, assign) int64_t currentOffset; // The fetcher for the current data chunk, if any @property(atomic, strong, GTM_NULLABLE) GTMSessionFetcher *chunkFetcher; // The active fetcher is the current chunk fetcher, or the upload fetcher itself // if no chunk fetcher has yet been created. @property(atomic, readonly) GTMSessionFetcher *activeFetcher; // The last request made by an active fetcher. Useful for testing. @property(atomic, readonly, GTM_NULLABLE) NSURLRequest *lastChunkRequest; // The status code from the most recently-completed fetch. @property(atomic, assign) NSInteger statusCode; // Exposed for testing only. @property(atomic, readonly, GTM_NULLABLE) dispatch_queue_t delegateCallbackQueue; @property(atomic, readonly, GTM_NULLABLE) GTMSessionFetcherCompletionHandler delegateCompletionHandler; @end @interface GTMSessionFetcher (GTMSessionUploadFetcherMethods) @property(readonly, GTM_NULLABLE) GTMSessionUploadFetcher *parentUploadFetcher; @end GTM_ASSUME_NONNULL_END ================================================ FILE: iOS/Manager/EZShopManager/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m ================================================ /* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif #import "GTMSessionUploadFetcher.h" static NSString *const kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey = @"_upChunk"; static NSString *const kGTMSessionIdentifierUploadFileURLMetadataKey = @"_upFileURL"; static NSString *const kGTMSessionIdentifierUploadFileLengthMetadataKey = @"_upFileLen"; static NSString *const kGTMSessionIdentifierUploadLocationURLMetadataKey = @"_upLocURL"; static NSString *const kGTMSessionIdentifierUploadMIMETypeMetadataKey = @"_uploadMIME"; static NSString *const kGTMSessionIdentifierUploadChunkSizeMetadataKey = @"_upChSize"; static NSString *const kGTMSessionIdentifierUploadCurrentOffsetMetadataKey = @"_upOffset"; static NSString *const kGTMSessionHeaderXGoogUploadChunkGranularity = @"X-Goog-Upload-Chunk-Granularity"; static NSString *const kGTMSessionHeaderXGoogUploadCommand = @"X-Goog-Upload-Command"; static NSString *const kGTMSessionHeaderXGoogUploadContentLength = @"X-Goog-Upload-Content-Length"; static NSString *const kGTMSessionHeaderXGoogUploadContentType = @"X-Goog-Upload-Content-Type"; static NSString *const kGTMSessionHeaderXGoogUploadOffset = @"X-Goog-Upload-Offset"; static NSString *const kGTMSessionHeaderXGoogUploadProtocol = @"X-Goog-Upload-Protocol"; static NSString *const kGTMSessionHeaderXGoogUploadSizeReceived = @"X-Goog-Upload-Size-Received"; static NSString *const kGTMSessionHeaderXGoogUploadStatus = @"X-Goog-Upload-Status"; static NSString *const kGTMSessionHeaderXGoogUploadURL = @"X-Goog-Upload-URL"; // Property of chunk fetchers identifying the parent upload fetcher. Non-retained NSValue. static NSString *const kGTMSessionUploadFetcherChunkParentKey = @"_uploadFetcherChunkParent"; int64_t const kGTMSessionUploadFetcherStandardChunkSize = (int64_t)LLONG_MAX; #if TARGET_OS_IPHONE int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 10 * 1024 * 1024; // 10 MB for iOS, watchOS, tvOS #else int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 100 * 1024 * 1024; // 100 MB for macOS #endif typedef NS_ENUM(NSUInteger, GTMSessionUploadFetcherStatus) { kStatusUnknown, kStatusActive, kStatusFinal, kStatusCancelled, }; NSString *const kGTMSessionFetcherUploadLocationObtainedNotification = @"kGTMSessionFetcherUploadLocationObtainedNotification"; #if !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionFetcher (ProtectedMethods) // Access to non-public method on the parent fetcher class. - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks; - (void)createSessionIdentifierWithMetadata:(NSDictionary *)metadata; - (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(id)target didFinishSelector:(SEL)finishedSelector; - (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue afterUserStopped:(BOOL)afterStopped block:(void (^)(void))block; - (NSTimer *)retryTimer; @property(readwrite, strong) NSData *downloadedData; - (void)releaseCallbacks; - (NSInteger)statusCodeUnsynchronized; @end #endif // !GTMSESSION_BUILD_COMBINED_SOURCES @interface GTMSessionUploadFetcher () // Changing readonly to readwrite. @property(atomic, strong, readwrite) NSURLRequest *lastChunkRequest; @property(atomic, readwrite, assign) int64_t currentOffset; // Internal properties. @property(strong, atomic, GTM_NULLABLE) GTMSessionFetcher *fetcherInFlight; // Synchronized on self. @property(assign, atomic, getter=isSubdataGenerating) BOOL subdataGenerating; @property(assign, atomic) BOOL shouldInitiateOffsetQuery; @property(assign, atomic) int64_t uploadGranularity; @end @implementation GTMSessionUploadFetcher { GTMSessionFetcher *_chunkFetcher; // We'll call through to the delegate's completion handler. GTMSessionFetcherCompletionHandler _delegateCompletionHandler; dispatch_queue_t _delegateCallbackQueue; // The initial fetch's body length and bytes actually sent are // needed for calculating progress during subsequent chunk uploads int64_t _initialBodyLength; int64_t _initialBodySent; // The upload server address for the chunks of this upload session. NSURL *_uploadLocationURL; // _uploadData, _uploadDataProvider, or _uploadFileHandle may be set, but only one. NSData *_uploadData; NSFileHandle *_uploadFileHandle; GTMSessionUploadFetcherDataProvider _uploadDataProvider; NSURL *_uploadFileURL; int64_t _uploadFileLength; NSString *_uploadMIMEType; int64_t _chunkSize; int64_t _uploadGranularity; BOOL _isPaused; BOOL _isRestartedUpload; BOOL _shouldInitiateOffsetQuery; // Tied to useBackgroundSession property, since this property is applicable to chunk fetchers. BOOL _useBackgroundSessionOnChunkFetchers; // We keep the latest offset into the upload data just for progress reporting. int64_t _currentOffset; NSDictionary *_recentChunkReponseHeaders; NSInteger _recentChunkStatusCode; // For waiting, we need to know the fetcher in flight, if any, and if subdata generation // is in progress. GTMSessionFetcher *_fetcherInFlight; BOOL _isSubdataGenerating; } + (void)load { [self uploadFetchersForBackgroundSessions]; } + (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request uploadMIMEType:(NSString *)uploadMIMEType chunkSize:(int64_t)chunkSize fetcherService:(GTMSessionFetcherService *)fetcherService { GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:request fetcherService:fetcherService]; [fetcher setLocationURL:nil uploadMIMEType:uploadMIMEType chunkSize:chunkSize]; return fetcher; } + (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL uploadMIMEType:(NSString *)uploadMIMEType chunkSize:(int64_t)chunkSize fetcherService:(GTMSessionFetcherService *)fetcherService { GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:nil fetcherService:fetcherService]; [fetcher setLocationURL:uploadLocationURL uploadMIMEType:uploadMIMEType chunkSize:chunkSize]; return fetcher; } + (instancetype)uploadFetcherForSessionIdentifierMetadata:(NSDictionary *)metadata { GTMSESSION_ASSERT_DEBUG( [metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue], @"Session identifier metadata is not for an upload fetcher: %@", metadata); NSNumber *uploadFileLengthNum = metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey]; GTMSESSION_ASSERT_DEBUG(uploadFileLengthNum != nil, @"Session metadata missing an UploadFileSize"); if (uploadFileLengthNum == nil) return nil; int64_t uploadFileLength = [uploadFileLengthNum longLongValue]; GTMSESSION_ASSERT_DEBUG(uploadFileLength >= 0, @"Session metadata UploadFileSize is unknown"); NSString *uploadFileURLString = metadata[kGTMSessionIdentifierUploadFileURLMetadataKey]; GTMSESSION_ASSERT_DEBUG(uploadFileURLString, @"Session metadata missing an UploadFileURL"); if (uploadFileURLString == nil) return nil; NSURL *uploadFileURL = [NSURL URLWithString:uploadFileURLString]; // There used to be a call here to NSURL checkResourceIsReachableAndReturnError: to check for the // existence of the file (also tried NSFileManager fileExistsAtPath:). We've determined // empirically that the check can fail at startup even when the upload file does in fact exist. // For now, we'll go ahead and restore the background upload fetcher. If the file doesn't exist, // it will fail later. NSString *uploadLocationURLString = metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey]; NSURL *uploadLocationURL = uploadLocationURLString ? [NSURL URLWithString:uploadLocationURLString] : nil; NSString *uploadMIMEType = metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey]; int64_t uploadChunkSize = [metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] longLongValue]; if (uploadChunkSize <= 0) { uploadChunkSize = kGTMSessionUploadFetcherStandardChunkSize; } int64_t currentOffset = [metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] longLongValue]; GTMSESSION_ASSERT_DEBUG(currentOffset <= uploadFileLength, @"CurrentOffset (%lld) exceeds UploadFileSize (%lld)", currentOffset, uploadFileLength); if (currentOffset > uploadFileLength) return nil; GTMSessionUploadFetcher *uploadFetcher = [self uploadFetcherWithLocation:uploadLocationURL uploadMIMEType:uploadMIMEType chunkSize:uploadChunkSize fetcherService:nil]; // Set the upload file length before setting the upload file URL tries to determine the length. [uploadFetcher setUploadFileLength:uploadFileLength]; uploadFetcher.uploadFileURL = uploadFileURL; uploadFetcher.sessionUserInfo = metadata; uploadFetcher.useBackgroundSession = YES; uploadFetcher.currentOffset = currentOffset; uploadFetcher.allowedInsecureSchemes = @[ @"http" ]; // Allowed on restored upload fetcher. return uploadFetcher; } + (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request fetcherService:(GTMSessionFetcherService *)fetcherService { // Internal utility method for instantiating fetchers GTMSessionUploadFetcher *fetcher; if ([fetcherService isKindOfClass:[GTMSessionFetcherService class]]) { fetcher = [fetcherService fetcherWithRequest:request fetcherClass:self]; } else { fetcher = [self fetcherWithRequest:request]; } fetcher.useBackgroundSession = YES; return fetcher; } + (NSPointerArray *)uploadFetcherPointerArrayForBackgroundSessions { static NSPointerArray *gUploadFetcherPointerArrayForBackgroundSessions = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ gUploadFetcherPointerArrayForBackgroundSessions = [NSPointerArray weakObjectsPointerArray]; }); return gUploadFetcherPointerArrayForBackgroundSessions; } + (instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier { GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); NSArray *uploadFetchersForBackgroundSessions = [self uploadFetchersForBackgroundSessions]; for (GTMSessionUploadFetcher *uploadFetcher in uploadFetchersForBackgroundSessions) { if ([uploadFetcher.chunkFetcher.sessionIdentifier isEqual:sessionIdentifier]) { return uploadFetcher; } } return nil; } + (NSArray *)uploadFetchersForBackgroundSessions { // Collect the background session upload fetchers that are still in memory. NSPointerArray *uploadFetcherPointerArray = [self uploadFetcherPointerArrayForBackgroundSessions]; [uploadFetcherPointerArray compact]; NSMutableSet *restoredSessionIdentifiers = [[NSMutableSet alloc] init]; NSMutableArray *uploadFetchers = [[NSMutableArray alloc] init]; for (GTMSessionUploadFetcher *uploadFetcher in uploadFetcherPointerArray) { NSString *sessionIdentifier = uploadFetcher.chunkFetcher.sessionIdentifier; if (sessionIdentifier) { [restoredSessionIdentifiers addObject:sessionIdentifier]; [uploadFetchers addObject:uploadFetcher]; } } // The system may have other ongoing background upload sessions. Restore upload fetchers for those // too. NSArray *fetchers = [GTMSessionFetcher fetchersForBackgroundSessions]; for (GTMSessionFetcher *fetcher in fetchers) { NSString *sessionIdentifier = fetcher.sessionIdentifier; if (!sessionIdentifier || [restoredSessionIdentifiers containsObject:sessionIdentifier]) { continue; } NSDictionary *sessionIdentifierMetadata = [fetcher sessionIdentifierMetadata]; if (sessionIdentifierMetadata == nil) { continue; } if (![sessionIdentifierMetadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue]) { continue; } GTMSessionUploadFetcher *uploadFetcher = [self uploadFetcherForSessionIdentifierMetadata:sessionIdentifierMetadata]; if (uploadFetcher == nil) { // Something went wrong with this upload fetcher, so kill the restored chunk fetcher. [fetcher stopFetching]; continue; } [uploadFetchers addObject:uploadFetcher]; uploadFetcher->_chunkFetcher = fetcher; uploadFetcher->_fetcherInFlight = fetcher; [uploadFetcher attachSendProgressBlockToChunkFetcher:fetcher]; fetcher.completionHandler = [fetcher completionHandlerWithTarget:uploadFetcher didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; GTMSESSION_LOG_DEBUG(@"%@ restoring upload fetcher %@ for chunk fetcher %@", [self class], uploadFetcher, fetcher); } return uploadFetchers; } - (void)setUploadData:(NSData *)data { BOOL changed = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_uploadData != data) { _uploadData = data; changed = YES; } } if (changed) { [self setupRequestHeaders]; } } - (NSData *)uploadData { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadData; } } - (void)setUploadFileHandle:(NSFileHandle *)fh { BOOL changed = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_uploadFileHandle != fh) { _uploadFileHandle = fh; changed = YES; } } if (changed) { [self setupRequestHeaders]; } } - (NSFileHandle *)uploadFileHandle { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadFileHandle; } } - (void)setUploadFileURL:(NSURL *)uploadURL { BOOL changed = NO; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_uploadFileURL != uploadURL) { _uploadFileURL = uploadURL; changed = YES; } } if (changed) { [self setupRequestHeaders]; } } - (NSURL *)uploadFileURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadFileURL; } } - (void)setUploadFileLength:(int64_t)fullLength { @synchronized(self) { GTMSessionMonitorSynchronized(self); _uploadFileLength = fullLength; } } - (void)setUploadDataLength:(int64_t)fullLength provider:(GTMSessionUploadFetcherDataProvider)block { @synchronized(self) { GTMSessionMonitorSynchronized(self); _uploadDataProvider = [block copy]; _uploadFileLength = fullLength; } [self setupRequestHeaders]; } - (GTMSessionUploadFetcherDataProvider)uploadDataProvider { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadDataProvider; } } - (void)setUploadMIMEType:(NSString *)uploadMIMEType { GTMSESSION_ASSERT_DEBUG(0, @"TODO: disallow setUploadMIMEType by making declaration readonly"); // (and uploadMIMEType, chunksize, currentOffset) @synchronized(self) { GTMSessionMonitorSynchronized(self); _uploadMIMEType = uploadMIMEType; } } - (NSString *)uploadMIMEType { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadMIMEType; } } - (void)setChunkSize:(int64_t)chunkSize { @synchronized(self) { GTMSessionMonitorSynchronized(self); _chunkSize = chunkSize; } } - (int64_t)chunkSize { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _chunkSize; } } - (void)setupRequestHeaders { GTMSessionCheckNotSynchronized(self); #if DEBUG @synchronized(self) { GTMSessionMonitorSynchronized(self); int hasData = (_uploadData != nil) ? 1 : 0; int hasFileHandle = (_uploadFileHandle != nil) ? 1 : 0; int hasFileURL = (_uploadFileURL != nil) ? 1 : 0; int hasUploadDataProvider = (_uploadDataProvider != nil) ? 1 : 0; int numberOfSources = hasData + hasFileHandle + hasFileURL + hasUploadDataProvider; #pragma unused(numberOfSources) GTMSESSION_ASSERT_DEBUG(numberOfSources == 1, @"Need just one upload source (%d)", numberOfSources); } // @synchronized(self) #endif // Add our custom headers to the initial request indicating the data // type and total size to be delivered later in the chunk requests. NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; GTMSESSION_ASSERT_DEBUG((mutableRequest == nil) != (_uploadLocationURL == nil), @"Request and location are mutually exclusive"); if (!mutableRequest) return; NSNumber *lengthNum = @([self fullUploadLength]); [mutableRequest setValue:@"resumable" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol]; [mutableRequest setValue:@"start" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; [mutableRequest setValue:_uploadMIMEType forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentType]; [mutableRequest setValue:lengthNum.stringValue forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength]; NSString *method = mutableRequest.HTTPMethod; if (method == nil || [method caseInsensitiveCompare:@"GET"] == NSOrderedSame) { [mutableRequest setHTTPMethod:@"POST"]; } // Ensure the user agent header identifies this to the upload server as a // GTMSessionUploadFetcher client. The /1 can be incremented in the unlikely circumstance // we need to make a bug fix in the client that the server can recognize. NSString *const kUserAgentStub = @"(GTMSUF/1)"; NSString *userAgent = [mutableRequest valueForHTTPHeaderField:@"User-Agent"]; if (userAgent == nil || [userAgent rangeOfString:kUserAgentStub].location == NSNotFound) { if (userAgent.length == 0) { userAgent = GTMFetcherStandardUserAgentString(nil); } userAgent = [userAgent stringByAppendingFormat:@" %@", kUserAgentStub]; [mutableRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; } [self setRequest:mutableRequest]; } - (void)setLocationURL:(NSURL * GTM_NULLABLE_TYPE)location uploadMIMEType:(NSString *)uploadMIMEType chunkSize:(int64_t)chunkSize { @synchronized(self) { GTMSessionMonitorSynchronized(self); GTMSESSION_ASSERT_DEBUG(chunkSize > 0, @"chunk size is zero"); // When resuming an upload, set the known upload target URL. _uploadLocationURL = location; _uploadMIMEType = uploadMIMEType; _chunkSize = chunkSize; // Indicate that we've not yet determined the file handle's length _uploadFileLength = -1; // Indicate that we've not yet determined the upload fetcher status _recentChunkStatusCode = -1; // If this is restarting an upload begun by another fetcher, // the location is specified but the request is nil _isRestartedUpload = (location != nil); } // @synchronized(self) } - (int64_t)fullUploadLength { int64_t result; @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_uploadData) { result = (int64_t)_uploadData.length; } else { if (_uploadFileLength == -1) { if (_uploadFileHandle) { // First time through, seek to end to determine file length _uploadFileLength = (int64_t)[_uploadFileHandle seekToEndOfFile]; } else if (_uploadDataProvider) { // _uploadFileLength is set when the _uploadDataProvider is set. GTMSESSION_ASSERT_DEBUG(_uploadFileLength >= 0, @"No uploadDataProvider length set"); } else { NSNumber *filesizeNum; NSError *valueError; if ([_uploadFileURL getResourceValue:&filesizeNum forKey:NSURLFileSizeKey error:&valueError]) { _uploadFileLength = filesizeNum.longLongValue; } else { GTMSESSION_ASSERT_DEBUG(NO, @"Cannot get file size: %@\n %@", valueError, _uploadFileURL.path); _uploadFileLength = 0; } } } result = _uploadFileLength; } } // @synchronized(self) return result; } // Make a subdata of the upload data. - (void)generateChunkSubdataWithOffset:(int64_t)offset length:(int64_t)length response:(GTMSessionUploadFetcherDataProviderResponse)response { GTMSessionUploadFetcherDataProvider uploadDataProvider = self.uploadDataProvider; if (uploadDataProvider) { uploadDataProvider(offset, length, response); return; } NSData *uploadData = self.uploadData; if (uploadData) { // NSData provided. NSData *resultData; if (offset == 0 && length == (int64_t)uploadData.length) { resultData = uploadData; } else { int64_t dataLength = (int64_t)uploadData.length; // Ensure our range is valid. b/18007814 if (offset + length > dataLength) { NSString *errorMessage = [NSString stringWithFormat: @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld", offset, length, dataLength]; GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage); response(nil, [self uploadChunkUnavailableErrorWithDescription:errorMessage]); return; } NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); resultData = [uploadData subdataWithRange:range]; } response(resultData, nil); return; } NSURL *uploadFileURL = self.uploadFileURL; if (uploadFileURL) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self generateChunkSubdataFromFileURL:uploadFileURL offset:offset length:length response:response]; }); return; } GTMSESSION_ASSERT_DEBUG(_uploadFileHandle, @"Unexpectedly missing upload data package"); NSFileHandle *uploadFileHandle = self.uploadFileHandle; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self generateChunkSubdataFromFileHandle:uploadFileHandle offset:offset length:length response:response]; }); } - (void)generateChunkSubdataFromFileHandle:(NSFileHandle *)fileHandle offset:(int64_t)offset length:(int64_t)length response:(GTMSessionUploadFetcherDataProviderResponse)response { NSData *resultData; NSError *error; @try { [fileHandle seekToFileOffset:(unsigned long long)offset]; resultData = [fileHandle readDataOfLength:(NSUInteger)length]; } @catch (NSException *exception) { GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileHandle failed to read, %@", exception); error = [self uploadChunkUnavailableErrorWithDescription:exception.description]; } // The response always re-dispatches to the main thread, so we skip doing that here. response(resultData, error); } - (void)generateChunkSubdataFromFileURL:(NSURL *)fileURL offset:(int64_t)offset length:(int64_t)length response:(GTMSessionUploadFetcherDataProviderResponse)response { GTMSessionCheckNotSynchronized(self); NSData *resultData; NSError *error; int64_t fullUploadLength = [self fullUploadLength]; NSData *mappedData = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingMappedAlways + NSDataReadingUncached error:&error]; if (!mappedData) { // We could not create an NSData by memory-mapping the file. #if TARGET_IPHONE_SIMULATOR // NSTemporaryDirectory() can differ in the simulator between app restarts, // yet the contents for the new path remains unchanged, so try the latest temp path. if ([error.domain isEqual:NSCocoaErrorDomain] && (error.code == NSFileReadNoSuchFileError)) { NSString *filename = [fileURL lastPathComponent]; NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename]; NSURL *newFileURL = [NSURL fileURLWithPath:filePath]; if (![newFileURL isEqual:fileURL]) { [self generateChunkSubdataFromFileURL:newFileURL offset:offset length:length response:response]; return; } } #endif // If the file is just too large to create an NSData for, or if for some other reason we can't // map it, create an NSFileHandle instead to read a subset into an NSData. #if DEBUG NSNumber *fileSizeNum; BOOL hasFileSize = [fileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:NULL]; GTMSESSION_LOG_DEBUG(@"Note: uploadFileURL is falling back to creating upload chunks by reading" @" an NSFileHandle since uploadFileURL failed to map the upload file," @" file size %@, %@", hasFileSize ? fileSizeNum : @"unknown", error); #endif NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:fileURL error:&error]; if (fileHandle != nil) { [self generateChunkSubdataFromFileHandle:fileHandle offset:offset length:length response:response]; return; } GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileURL failed to read, %@", error); // Fall through with the error. } else { // Successfully created an NSData by memory-mapping the file. if (offset > 0 || length < fullUploadLength) { NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); resultData = [mappedData subdataWithRange:range]; } else { resultData = mappedData; } } // The response always re-dispatches to the main thread, so we skip re-dispatching here. response(resultData, error); } - (NSError *)uploadChunkUnavailableErrorWithDescription:(NSString *)description { // The description in the userInfo is intended as a clue to programmers, not // for client code to examine or rely on. NSDictionary *userInfo = @{ @"description" : description }; return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain code:GTMSessionFetcherErrorUploadChunkUnavailable userInfo:userInfo]; } - (NSError *)prematureFailureErrorWithUserInfo:(NSDictionary *)userInfo { // An error for if we get an unexpected status from the upload server or // otherwise cannot continue. This is an issue beyond the upload protocol; // there's no way the client can do anything useful except give up. NSError *error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain code:501 // Not implemented userInfo:userInfo]; return error; } + (GTMSessionUploadFetcherStatus)uploadStatusFromResponseHeaders:(NSDictionary *)responseHeaders { NSString *statusString = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus]; if ([statusString isEqual:@"active"]) { return kStatusActive; } if ([statusString isEqual:@"final"]) { return kStatusFinal; } if ([statusString isEqual:@"cancelled"]) { return kStatusCancelled; } return kStatusUnknown; } #pragma mark Method overrides affecting the initial fetch only - (void)setCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { @synchronized(self) { GTMSessionMonitorSynchronized(self); _delegateCompletionHandler = handler; } } - (void)setDelegateCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { @synchronized(self) { GTMSessionMonitorSynchronized(self); _delegateCallbackQueue = queue; } } - (dispatch_queue_t GTM_NULLABLE_TYPE)delegateCallbackQueue { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _delegateCallbackQueue; } } - (BOOL)isRestartedUpload { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _isRestartedUpload; } } - (GTMSessionFetcher * GTM_NULLABLE_TYPE)chunkFetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _chunkFetcher; } } - (void)setChunkFetcher:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); _chunkFetcher = fetcher; } } - (void)setFetcherInFlight:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); _fetcherInFlight = fetcher; } } - (GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcherInFlight { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _fetcherInFlight; } } - (void)beginFetchWithCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { GTMSessionCheckNotSynchronized(self); [self setInitialBodyLength:[self bodyLength]]; // We'll hold onto the superclass's callback queue so we can invoke the handler // even after the superclass has released the queue and its callback handler, as // happens during auth failure. [self setDelegateCallbackQueue:self.callbackQueue]; self.completionHandler = handler; if ([self isRestartedUpload]) { // When restarting an upload, we know the destination location for chunk fetches, // but we need to query to find the initial offset. if (![self isPaused]) { [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; } return; } // We don't want to call into the client's completion block immediately // after the finish of the initial connection (the delegate is called only // when uploading finishes), so we substitute our own completion block to be // called when the initial connection finishes GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@", self.fetcherInFlight); self.fetcherInFlight = self; [super beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { self.fetcherInFlight = nil; // callback BOOL hasTestBlock = (self.testBlock != nil); if (![self isRestartedUpload] && !hasTestBlock) { if (error == nil) { [self beginChunkFetches]; } else { if ([self retryTimer] == nil) { [self invokeFinalCallbackWithData:nil error:error shouldInvalidateLocation:YES]; } } } else { // If there was no initial request, then this fetch is resuming some // other uploadFetcher's initial request, and the superclass's connection // is never used, so at this point we call the user's actual completion // block. if (!hasTestBlock) { [self invokeFinalCallbackWithData:data error:error shouldInvalidateLocation:YES]; } else { // There was a test block, so we won't do chunk fetches, but we simulate obtaining // the data to be uploaded from the upload data provider block or the file handle, // and then call back. [self generateChunkSubdataWithOffset:0 length:[self fullUploadLength] response:^(NSData *generateData, NSError *generateError) { [self invokeFinalCallbackWithData:data error:error shouldInvalidateLocation:YES]; }]; } } }]; } - (void)beginChunkFetches { GTMSessionCheckNotSynchronized(self); #if DEBUG // The initial response of the resumable upload protocol should have an // empty body // // This assert typically happens because the upload create/edit link URL was // not supplied with the request, and the server is thus expecting a non- // resumable request/response. if (self.downloadedData.length > 0) { NSData *downloadedData = self.downloadedData; NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding]; #pragma unused(str) GTMSESSION_ASSERT_DEBUG(NO, @"unexpected response data (uploading to the wrong URL?)\n%@", str); } #endif // We need to get the upload URL from the location header to continue. NSDictionary *responseHeaders = [self responseHeaders]; [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; GTMSessionUploadFetcherStatus uploadStatus = [[self class] uploadStatusFromResponseHeaders:responseHeaders]; GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown, @"beginChunkFetches has unexpected upload status for headers %@", responseHeaders); BOOL isPrematureStop = (uploadStatus == kStatusFinal) || (uploadStatus == kStatusCancelled); NSString *uploadLocationURLStr = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadURL]; BOOL hasUploadLocation = (uploadLocationURLStr.length > 0); if (isPrematureStop || !hasUploadLocation) { GTMSESSION_ASSERT_DEBUG(NO, @"Premature failure: upload-status:\"%@\" location:%@", [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], uploadLocationURLStr); // We cannot continue since we do not know the location to use // as our upload destination. NSDictionary *userInfo = nil; NSData *downloadedData = self.downloadedData; if (downloadedData.length > 0) { userInfo = @{ kGTMSessionFetcherStatusDataKey : downloadedData }; } NSError *failureError = [self prematureFailureErrorWithUserInfo:userInfo]; [self invokeFinalCallbackWithData:nil error:failureError shouldInvalidateLocation:YES]; return; } self.uploadLocationURL = [NSURL URLWithString:uploadLocationURLStr]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName:kGTMSessionFetcherUploadLocationObtainedNotification object:self]; // we've now sent all of the initial post body data, so we need to include // its size in future progress indicator callbacks [self setInitialBodySent:[self initialBodyLength]]; // just in case the user paused us during the initial fetch... if (![self isPaused]) { [self uploadNextChunkWithOffset:0]; } } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { // Overrides the superclass. [self invokeDelegateWithDidSendBytes:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend + [self fullUploadLength]]; } - (BOOL)shouldReleaseCallbacksUponCompletion { // Overrides the superclass. // We don't want the superclass to release the delegate and callback // blocks once the initial fetch has finished // // This is invoked for only successful completion of the connection; // an error always will invoke and release the callbacks return NO; } - (void)invokeFinalCallbackWithData:(NSData *)data error:(NSError *)error shouldInvalidateLocation:(BOOL)shouldInvalidateLocation { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (shouldInvalidateLocation) { _uploadLocationURL = nil; } dispatch_queue_t queue = _delegateCallbackQueue; GTMSessionFetcherCompletionHandler handler = _delegateCompletionHandler; if (queue && handler) { [self invokeOnCallbackQueue:queue afterUserStopped:NO block:^{ handler(data, error); }]; } } // @synchronized(self) [self releaseUploadAndBaseCallbacks]; } - (void)releaseUploadAndBaseCallbacks { @synchronized(self) { GTMSessionMonitorSynchronized(self); _delegateCallbackQueue = nil; _delegateCompletionHandler = nil; _uploadDataProvider = nil; } // Release the base class's callbacks, too, if needed. [self releaseCallbacks]; } - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { GTMSessionCheckNotSynchronized(self); // Clear _fetcherInFlight when stopped. Moved from stopFetching, since that's a public method, // where this method does the work. Fixes issue clearing value when retryBlock included. GTMSessionFetcher *fetcherInFlight = self.fetcherInFlight; if (fetcherInFlight == self) { self.fetcherInFlight = nil; } [super stopFetchReleasingCallbacks:shouldReleaseCallbacks]; if (shouldReleaseCallbacks) { [self releaseUploadAndBaseCallbacks]; } } #pragma mark Chunk fetching methods - (void)uploadNextChunkWithOffset:(int64_t)offset { // use the properties in each chunk fetcher NSDictionary *props = [self properties]; [self uploadNextChunkWithOffset:offset fetcherProperties:props]; } - (void)sendQueryForUploadOffsetWithFetcherProperties:(NSDictionary *)props { GTMSessionFetcher *queryFetcher = [self uploadFetcherWithProperties:props isQueryFetch:YES]; queryFetcher.bodyData = [NSData data]; NSString *originalComment = self.comment; [queryFetcher setCommentWithFormat:@"%@ (query offset)", originalComment ? originalComment : @"upload"]; [queryFetcher setRequestValue:@"query" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; self.fetcherInFlight = queryFetcher; [queryFetcher beginFetchWithDelegate:self didFinishSelector:@selector(queryFetcher:finishedWithData:error:)]; } - (void)queryFetcher:(GTMSessionFetcher *)queryFetcher finishedWithData:(NSData *)data error:(NSError *)error { self.fetcherInFlight = nil; NSDictionary *responseHeaders = [queryFetcher responseHeaders]; NSString *sizeReceivedHeader; GTMSessionUploadFetcherStatus uploadStatus = [[self class] uploadStatusFromResponseHeaders:responseHeaders]; GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown || error != nil, @"query fetcher completion has unexpected upload status for headers %@", responseHeaders); if (error == nil) { sizeReceivedHeader = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadSizeReceived]; if (uploadStatus == kStatusCancelled || (uploadStatus == kStatusActive && sizeReceivedHeader == nil)) { NSDictionary *userInfo = nil; if (data.length > 0) { userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; } error = [self prematureFailureErrorWithUserInfo:userInfo]; } } if (error == nil) { int64_t offset = [sizeReceivedHeader longLongValue]; int64_t fullUploadLength = [self fullUploadLength]; if (offset >= fullUploadLength || uploadStatus == kStatusFinal) { // Handle we're done [self chunkFetcher:queryFetcher finishedWithData:data error:nil]; } else { [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; [self uploadNextChunkWithOffset:offset]; } } else { // Handle query error [self chunkFetcher:queryFetcher finishedWithData:data error:error]; } } - (void)sendCancelUploadWithFetcherProperties:(NSDictionary *)props { GTMSessionFetcher *cancelFetcher = [self uploadFetcherWithProperties:props isQueryFetch:YES]; cancelFetcher.bodyData = [NSData data]; NSString *originalComment = self.comment; [cancelFetcher setCommentWithFormat:@"%@ (cancel)", originalComment ? originalComment : @"upload"]; [cancelFetcher setRequestValue:@"cancel" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; self.fetcherInFlight = cancelFetcher; [cancelFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { self.fetcherInFlight = nil; if (error) { GTMSESSION_LOG_DEBUG(@"cancelFetcher %@", error); } }]; } - (void)uploadNextChunkWithOffset:(int64_t)offset fetcherProperties:(NSDictionary *)props { GTMSessionCheckNotSynchronized(self); // Example chunk headers: // X-Goog-Upload-Command: upload, finalize // X-Goog-Upload-Offset: 0 // Content-Length: 2000000 // Content-Type: image/jpeg // // {bytes 0-1999999} // The chunk upload URL requires no authentication header. GTMSessionFetcher *chunkFetcher = [self uploadFetcherWithProperties:props isQueryFetch:NO]; [self attachSendProgressBlockToChunkFetcher:chunkFetcher]; BOOL isUploadingFileURL = (self.uploadFileURL != nil); // Upload another chunk, meeting server-required granularity. int64_t chunkSize = self.chunkSize; int64_t fullUploadLength = [self fullUploadLength]; BOOL isUploadingFullFile = (offset == 0 && chunkSize >= fullUploadLength); if (!isUploadingFileURL || !isUploadingFullFile) { // We're not uploading the entire file and given the file URL. Since we'll be // allocating a subdata block for a chunk, we need to bound it to something that // won't blow the process's memory. if (chunkSize > kGTMSessionUploadFetcherMaximumDemandBufferSize) { chunkSize = kGTMSessionUploadFetcherMaximumDemandBufferSize; } } int64_t granularity = self.uploadGranularity; if (granularity > 0) { if (chunkSize < granularity) { chunkSize = granularity; } else { chunkSize = chunkSize - (chunkSize % granularity); } } GTMSESSION_ASSERT_DEBUG(offset < fullUploadLength || fullUploadLength == 0, @"offset %lld exceeds data length %lld", offset, fullUploadLength); if (granularity > 0) { offset = offset - (offset % granularity); } // If the chunk size is bigger than the remaining data, or else // it's close enough in size to the remaining data that we'd rather // avoid having a whole extra http fetch for the leftover bit, then make // this chunk size exactly match the remaining data size NSString *command; int64_t thisChunkSize = chunkSize; BOOL isChunkTooBig = (thisChunkSize >= (fullUploadLength - offset)); BOOL isChunkAlmostBigEnough = (fullUploadLength - offset - 2500 < thisChunkSize); BOOL isFinalChunk = isChunkTooBig || isChunkAlmostBigEnough; if (isFinalChunk) { thisChunkSize = fullUploadLength - offset; if (thisChunkSize > 0) { command = @"upload, finalize"; } else { command = @"finalize"; } } else { command = @"upload"; } NSString *lengthStr = @(thisChunkSize).stringValue; NSString *offsetStr = @(offset).stringValue; [chunkFetcher setRequestValue:command forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; [chunkFetcher setRequestValue:lengthStr forHTTPHeaderField:@"Content-Length"]; [chunkFetcher setRequestValue:offsetStr forHTTPHeaderField:kGTMSessionHeaderXGoogUploadOffset]; // Append the range of bytes in this chunk to the fetcher comment. NSString *baseComment = self.comment; [chunkFetcher setCommentWithFormat:@"%@ (%lld-%lld)", baseComment ? baseComment : @"upload", offset, MAX(0, offset + thisChunkSize - 1)]; // The chunk size may have changed, so determine again if we're uploading the full file. isUploadingFullFile = (offset == 0 && thisChunkSize >= fullUploadLength); if (isUploadingFullFile && isUploadingFileURL) { // The data is the full upload file URL. chunkFetcher.bodyFileURL = self.uploadFileURL; [self beginChunkFetcher:chunkFetcher offset:offset]; } else { // Make an NSData for the subset for this upload chunk. self.subdataGenerating = YES; [self generateChunkSubdataWithOffset:offset length:thisChunkSize response:^(NSData *chunkData, NSError *chunkError) { // The subdata methods may leave us on a background thread. dispatch_async(dispatch_get_main_queue(), ^{ self.subdataGenerating = NO; if (chunkData == nil) { NSError *responseError = chunkError; if (!responseError) { responseError = [self uploadChunkUnavailableErrorWithDescription:@"chunkData is nil"]; } [self invokeFinalCallbackWithData:nil error:responseError shouldInvalidateLocation:YES]; return; } BOOL didWriteFile = NO; if (isUploadingFileURL) { // Make a temporary file with the data subset. NSString *tempName = [NSString stringWithFormat:@"GTMUpload_temp_%@", [[NSUUID UUID] UUIDString]]; NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName]; NSError *writeError; didWriteFile = [chunkData writeToFile:tempPath options:NSDataWritingAtomic error:&writeError]; if (didWriteFile) { chunkFetcher.bodyFileURL = [NSURL fileURLWithPath:tempPath]; } else { GTMSESSION_LOG_DEBUG(@"writeToFile failed: %@\n%@", writeError, tempPath); } } if (!didWriteFile) { chunkFetcher.bodyData = [chunkData copy]; } [self beginChunkFetcher:chunkFetcher offset:offset]; }); }]; } } - (void)beginChunkFetcher:(GTMSessionFetcher *)chunkFetcher offset:(int64_t)offset { // Track the current offset for progress reporting self.currentOffset = offset; // Hang on to the fetcher in case we need to cancel it. We set these before beginning the // chunk fetch so the observers notified of chunk fetches can inspect the upload fetcher to // match to the chunk. self.chunkFetcher = chunkFetcher; self.fetcherInFlight = chunkFetcher; // Update the last chunk request, including any request headers. self.lastChunkRequest = chunkFetcher.request; [chunkFetcher beginFetchWithDelegate:self didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; } - (void)attachSendProgressBlockToChunkFetcher:(GTMSessionFetcher *)chunkFetcher { chunkFetcher.sendProgressBlock = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) { // The total bytes expected include the initial body and the full chunked // data, independent of how big this fetcher's chunk is. int64_t initialBodySent = [self bodyLength]; // TODO(grobbins) use [self initialBodySent] int64_t totalSent = initialBodySent + self.currentOffset + totalBytesSent; int64_t totalExpected = initialBodySent + [self fullUploadLength]; [self invokeDelegateWithDidSendBytes:bytesSent totalBytesSent:totalSent totalBytesExpectedToSend:totalExpected]; }; } - (NSDictionary *)uploadSessionIdentifierMetadata { NSMutableDictionary *metadata = [NSMutableDictionary dictionary]; metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] = @YES; GTMSESSION_ASSERT_DEBUG(self.uploadFileURL, @"Invalid upload fetcher to create session identifier for metadata"); metadata[kGTMSessionIdentifierUploadFileURLMetadataKey] = [self.uploadFileURL absoluteString]; metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey] = @([self fullUploadLength]); if (self.uploadLocationURL) { metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey] = [self.uploadLocationURL absoluteString]; } if (self.uploadMIMEType) { metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey] = self.uploadMIMEType; } metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] = @(self.chunkSize); metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] = @(self.currentOffset); return metadata; } - (GTMSessionFetcher *)uploadFetcherWithProperties:(NSDictionary *)properties isQueryFetch:(BOOL)isQueryFetch { GTMSessionCheckNotSynchronized(self); // Common code to make a request for a query command or for a chunk upload. NSURL *uploadLocationURL = self.uploadLocationURL; NSMutableURLRequest *chunkRequest = [NSMutableURLRequest requestWithURL:uploadLocationURL]; [chunkRequest setHTTPMethod:@"PUT"]; // copy the user-agent from the original connection NSURLRequest *origRequest = self.request; NSString *userAgent = [origRequest valueForHTTPHeaderField:@"User-Agent"]; if (userAgent.length > 0) { [chunkRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; } // To avoid timeouts when debugging, copy the timeout of the initial fetcher. NSTimeInterval origTimeout = [origRequest timeoutInterval]; [chunkRequest setTimeoutInterval:origTimeout]; // // Make a new chunk fetcher. // GTMSessionFetcher *chunkFetcher = [GTMSessionFetcher fetcherWithRequest:chunkRequest]; chunkFetcher.callbackQueue = self.callbackQueue; chunkFetcher.sessionUserInfo = self.sessionUserInfo; chunkFetcher.configurationBlock = self.configurationBlock; chunkFetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; chunkFetcher.allowLocalhostRequest = self.allowLocalhostRequest; chunkFetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; chunkFetcher.useUploadTask = !isQueryFetch; if (self.uploadFileURL && !isQueryFetch && self.useBackgroundSession) { [chunkFetcher createSessionIdentifierWithMetadata:[self uploadSessionIdentifierMetadata]]; } // Give the chunk fetcher the same properties as the previous chunk fetcher chunkFetcher.properties = [properties mutableCopy]; [chunkFetcher setProperty:[NSValue valueWithNonretainedObject:self] forKey:kGTMSessionUploadFetcherChunkParentKey]; // copy other fetcher settings to the new fetcher chunkFetcher.retryEnabled = self.retryEnabled; chunkFetcher.maxRetryInterval = self.maxRetryInterval; if ([self isRetryEnabled]) { // We interpose our own retry method both so we can change the request to ask the server to // tell us where to resume the chunk. chunkFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *chunkError, GTMSessionFetcherRetryResponse response){ void (^finish)(BOOL) = ^(BOOL shouldRetry){ // We'll retry by sending an offset query. if (shouldRetry) { self.shouldInitiateOffsetQuery = !isQueryFetch; // We don't know what our actual offset is anymore, but the server will tell us. self.currentOffset = 0; } // We don't actually want to retry this specific fetcher. response(NO); }; GTMSessionFetcherRetryBlock retryBlock = self.retryBlock; if (retryBlock) { // Ask the client, then call the finish block above. retryBlock(suggestedWillRetry, chunkError, finish); } else { finish(suggestedWillRetry); } }; } return chunkFetcher; } - (void)chunkFetcher:(GTMSessionFetcher *)chunkFetcher finishedWithData:(NSData *)data error:(NSError *)error { BOOL hasDestroyedOldChunkFetcher = NO; self.fetcherInFlight = nil; NSDictionary *responseHeaders = [chunkFetcher responseHeaders]; GTMSessionUploadFetcherStatus uploadStatus = [[self class] uploadStatusFromResponseHeaders:responseHeaders]; GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown || error != nil || self.wasCreatedFromBackgroundSession, @"chunk fetcher completion has kStatusUnknown upload status for headers %@ fetcher %@", responseHeaders, self); BOOL isUploadStatusStopped = (uploadStatus == kStatusFinal || uploadStatus == kStatusCancelled); // Check if the fetcher was actually querying. If it failed, do not retry, // as it would enter an infinite retry loop. NSString *uploadCommand = chunkFetcher.request.allHTTPHeaderFields[kGTMSessionHeaderXGoogUploadCommand]; BOOL isQueryFetch = [uploadCommand isEqual:@"query"]; int64_t previousContentLength = [[chunkFetcher.request valueForHTTPHeaderField:@"Content-Length"] longLongValue]; // The Content-Length header may not be present if the chunk fetcher was recreated from // a background session. BOOL hasKnownChunkSize = (previousContentLength > 0); BOOL needsQuery = (!hasKnownChunkSize && !isUploadStatusStopped); if (error || (needsQuery && !isQueryFetch)) { NSInteger status = error.code; // Status 4xx indicates a bad offset in the Google upload protocol. However, do not retry status // 404 per spec, nor if the upload size appears to have been zero (since the server will just // keep asking us to retry.) if (self.shouldInitiateOffsetQuery || (needsQuery && !isQueryFetch) || ([error.domain isEqual:kGTMSessionFetcherStatusDomain] && status >= 400 && status <= 499 && status != 404 && uploadStatus == kStatusActive && previousContentLength > 0)) { self.shouldInitiateOffsetQuery = NO; [self destroyChunkFetcher]; hasDestroyedOldChunkFetcher = YES; [self sendQueryForUploadOffsetWithFetcherProperties:chunkFetcher.properties]; } else { // Some unexpected status has occurred; handle it as we would a regular // object fetcher failure. [self invokeFinalCallbackWithData:data error:error shouldInvalidateLocation:NO]; } } else { // The chunk has uploaded successfully. int64_t newOffset = self.currentOffset + previousContentLength; #if DEBUG // Verify that if we think all of the uploading data has been sent, the server responded with // the "final" upload status. BOOL hasUploadAllData = (newOffset == [self fullUploadLength]); BOOL isFinalStatus = (uploadStatus == kStatusFinal); #pragma unused(hasUploadAllData,isFinalStatus) GTMSESSION_ASSERT_DEBUG(hasUploadAllData == isFinalStatus || !hasKnownChunkSize, @"uploadStatus:%@ newOffset:%zd (%lld + %zd) fullUploadLength:%lld" @" chunkFetcher:%@ requestHeaders:%@ responseHeaders:%@", [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], newOffset, self.currentOffset, previousContentLength, [self fullUploadLength], chunkFetcher, chunkFetcher.request.allHTTPHeaderFields, responseHeaders); #endif if (isUploadStatusStopped) { // This was the last chunk. if (error == nil && uploadStatus == kStatusCancelled) { // Report cancelled status as an error. NSDictionary *userInfo = nil; if (data.length > 0) { userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; } data = nil; error = [self prematureFailureErrorWithUserInfo:userInfo]; } else { // The upload is in final status. // // Take the chunk fetcher's data as the superclass data. self.downloadedData = data; self.statusCode = chunkFetcher.statusCode; } // we're done [self invokeFinalCallbackWithData:data error:error shouldInvalidateLocation:YES]; } else { // Start the next chunk. self.currentOffset = newOffset; // We want to destroy this chunk fetcher before creating the next one, but // we want to pass on its properties NSDictionary *props = [chunkFetcher properties]; // We no longer need to be able to cancel this chunkFetcher. Destroy it // before we create a new chunk fetcher. [self destroyChunkFetcher]; hasDestroyedOldChunkFetcher = YES; [self uploadNextChunkWithOffset:newOffset fetcherProperties:props]; } } if (!hasDestroyedOldChunkFetcher) { [self destroyChunkFetcher]; } } - (void)destroyChunkFetcher { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_fetcherInFlight == _chunkFetcher) { _fetcherInFlight = nil; } [_chunkFetcher stopFetching]; NSURL *chunkFileURL = _chunkFetcher.bodyFileURL; BOOL wasTemporaryUploadFile = ![chunkFileURL isEqual:_uploadFileURL]; if (wasTemporaryUploadFile) { NSError *error; [[NSFileManager defaultManager] removeItemAtURL:chunkFileURL error:&error]; if (error) { GTMSESSION_LOG_DEBUG(@"removingItemAtURL failed: %@\n%@", error, chunkFileURL); } } _recentChunkReponseHeaders = _chunkFetcher.responseHeaders; // To avoid retain cycles, remove all properties except the parent identifier. _chunkFetcher.properties = @{ kGTMSessionUploadFetcherChunkParentKey : [NSValue valueWithNonretainedObject:self] }; _chunkFetcher.retryBlock = nil; _chunkFetcher.sendProgressBlock = nil; _chunkFetcher = nil; } // @synchronized(self) } // This method calculates the proper values to pass to the client's send progress block. // // The actual total bytes sent include the initial body sent, plus the // offset into the batched data prior to the current chunk fetcher - (void)invokeDelegateWithDidSendBytes:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpected { GTMSessionCheckNotSynchronized(self); // Ensure the chunk fetcher survives the callback in case the user pauses the upload process. __block GTMSessionFetcher *holdFetcher = self.chunkFetcher; [self invokeOnCallbackQueue:self.delegateCallbackQueue afterUserStopped:NO block:^{ GTMSessionFetcherSendProgressBlock sendProgressBlock = self.sendProgressBlock; if (sendProgressBlock) { sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpected); } holdFetcher = nil; }]; } - (void)retrieveUploadChunkGranularityFromResponseHeaders:(NSDictionary *)responseHeaders { GTMSessionCheckNotSynchronized(self); // Standard granularity for Google uploads is 256K. NSString *chunkGranularityHeader = [responseHeaders objectForKey:@"X-Goog-Upload-Chunk-Granularity"]; self.uploadGranularity = chunkGranularityHeader.longLongValue; } #pragma mark - - (BOOL)isPaused { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _isPaused; } // @synchronized(self) } - (void)pauseFetching { @synchronized(self) { GTMSessionMonitorSynchronized(self); _isPaused = YES; } // @synchronized(self) // Pausing just means stopping the current chunk from uploading; // when we resume, we will send a query request to the server to // figure out what bytes to resume sending. // // We won't try to cancel the initial data upload, but rather will check // for being paused in beginChunkFetches. [self destroyChunkFetcher]; } - (void)resumeFetching { BOOL wasPaused; @synchronized(self) { GTMSessionMonitorSynchronized(self); wasPaused = _isPaused; _isPaused = NO; } // @synchronized(self) if (wasPaused) { [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; } } - (void)stopFetching { // Overrides the superclass [self destroyChunkFetcher]; // If we think the server is waiting for more data, then tell it there won't be more. if (self.uploadLocationURL) { [self sendCancelUploadWithFetcherProperties:[self properties]]; self.uploadLocationURL = nil; } [super stopFetching]; } #pragma mark - // Public properties. @synthesize currentOffset = _currentOffset, delegateCompletionHandler = _delegateCompletionHandler, chunkFetcher = _chunkFetcher, lastChunkRequest = _lastChunkRequest, subdataGenerating = _subdataGenerating, shouldInitiateOffsetQuery = _shouldInitiateOffsetQuery, uploadGranularity = _uploadGranularity; // Internal properties. @dynamic fetcherInFlight; @dynamic activeFetcher; @dynamic statusCode; @dynamic delegateCallbackQueue; + (void)removePointer:(void *)pointer fromPointerArray:(NSPointerArray *)pointerArray { for (NSUInteger index = 0, count = pointerArray.count; index < count; ++index) { void *pointerAtIndex = [pointerArray pointerAtIndex:index]; if (pointerAtIndex == pointer) { [pointerArray removePointerAtIndex:index]; return; } } } - (BOOL)useBackgroundSession { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _useBackgroundSessionOnChunkFetchers; } // @synchronized(self } - (void)setUseBackgroundSession:(BOOL)useBackgroundSession { @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_useBackgroundSessionOnChunkFetchers != useBackgroundSession) { _useBackgroundSessionOnChunkFetchers = useBackgroundSession; NSPointerArray *uploadFetcherPointerArrayForBackgroundSessions = [[self class] uploadFetcherPointerArrayForBackgroundSessions]; if (_useBackgroundSessionOnChunkFetchers) { [uploadFetcherPointerArrayForBackgroundSessions addPointer:(__bridge void *)self]; } else { [[self class] removePointer:(__bridge void *)self fromPointerArray:uploadFetcherPointerArrayForBackgroundSessions]; } } } // @synchronized(self } - (BOOL)canFetchWithBackgroundSession { // The initial upload fetcher is always a foreground session; the // useBackgroundSession property will apply only to chunk fetchers, // not to queries. return NO; } - (NSDictionary *)responseHeaders { GTMSessionCheckNotSynchronized(self); // Overrides the superclass // If asked for the fetcher's response, use the most recent chunk fetcher's response, // since the original request's response lacks useful information like the actual // Content-Type. NSDictionary *dict = self.chunkFetcher.responseHeaders; if (dict) { return dict; } @synchronized(self) { GTMSessionMonitorSynchronized(self); if (_recentChunkReponseHeaders) { return _recentChunkReponseHeaders; } } // @synchronized(self // No chunk fetcher yet completed, so return whatever we have from the initial fetch. return [super responseHeaders]; } - (NSInteger)statusCodeUnsynchronized { GTMSessionCheckSynchronized(self); if (_recentChunkStatusCode != -1) { // Overrides the superclass to indicate status appropriate to the initial // or latest chunk fetch return _recentChunkStatusCode; } else { return [super statusCodeUnsynchronized]; } } - (void)setStatusCode:(NSInteger)val { @synchronized(self) { GTMSessionMonitorSynchronized(self); _recentChunkStatusCode = val; } } - (int64_t)initialBodyLength { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _initialBodyLength; } } - (void)setInitialBodyLength:(int64_t)length { @synchronized(self) { GTMSessionMonitorSynchronized(self); _initialBodyLength = length; } } - (int64_t)initialBodySent { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _initialBodySent; } } - (void)setInitialBodySent:(int64_t)length { @synchronized(self) { GTMSessionMonitorSynchronized(self); _initialBodySent = length; } } - (NSURL *)uploadLocationURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); return _uploadLocationURL; } } - (void)setUploadLocationURL:(NSURL *)locationURL { @synchronized(self) { GTMSessionMonitorSynchronized(self); _uploadLocationURL = locationURL; } } - (GTMSessionFetcher *)activeFetcher { GTMSessionFetcher *result = self.fetcherInFlight; if (result) return result; return self; } - (BOOL)isFetching { // If there is an active chunk fetcher, then the upload fetcher is considered // to still be fetching. if (self.fetcherInFlight != nil) return YES; return [super isFetching]; } - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; while (self.fetcherInFlight || self.subdataGenerating) { if ([timeoutDate timeIntervalSinceNow] < 0) return NO; if (self.subdataGenerating) { // Allow time for subdata generation. NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001]; [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; } else { // Wait for any chunk or query fetchers that still have pending callbacks or // notifications. BOOL timedOut; if (self.fetcherInFlight == self) { timedOut = ![super waitForCompletionWithTimeout:timeoutInSeconds]; } else { timedOut = ![self.fetcherInFlight waitForCompletionWithTimeout:timeoutInSeconds]; } if (timedOut) return NO; } } return YES; } @end @implementation GTMSessionFetcher (GTMSessionUploadFetcherMethods) - (GTMSessionUploadFetcher *)parentUploadFetcher { NSValue *property = [self propertyForKey:kGTMSessionUploadFetcherChunkParentKey]; if (!property) return nil; GTMSessionUploadFetcher *uploadFetcher = property.nonretainedObjectValue; GTMSESSION_ASSERT_DEBUG([uploadFetcher isKindOfClass:[GTMSessionUploadFetcher class]], @"Unexpected parent upload fetcher class: %@", [uploadFetcher class]); return uploadFetcher; } @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/GoogleToolboxForMac/Foundation/GTMNSData+zlib.h ================================================ // // GTMNSData+zlib.h // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import #import "GTMDefines.h" /// Helpers for dealing w/ zlib inflate/deflate calls. @interface NSData (GTMZLibAdditions) // NOTE: For 64bit, none of these apis handle input sizes >32bits, they will // return nil when given such data. To handle data of that size you really // should be streaming it rather then doing it all in memory. #pragma mark Gzip Compression /// Return an autoreleased NSData w/ the result of gzipping the bytes. // // Uses the default compression level. + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length; + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the payload of |data|. // // Uses the default compression level. + (NSData *)gtm_dataByGzippingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the payload of |data| using |level| compression level. + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; #pragma mark Zlib "Stream" Compression // NOTE: deflate is *NOT* gzip. deflate is a "zlib" stream. pick which one // you really want to create. (the inflate api will handle either) /// Return an autoreleased NSData w/ the result of deflating the bytes. // // Uses the default compression level. + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the payload of |data|. // // Uses the default compression level. + (NSData *)gtm_dataByDeflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the payload of |data| using |level| compression level. + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; #pragma mark Uncompress of Gzip or Zlib /// Return an autoreleased NSData w/ the result of decompressing the bytes. // // The bytes to decompress can be zlib or gzip payloads. + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of decompressing the payload of |data|. // // The data to decompress can be zlib or gzip payloads. + (NSData *)gtm_dataByInflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByInflatingData:(NSData *)data error:(NSError **)error; #pragma mark "Raw" Compression Support // NOTE: raw deflate is *NOT* gzip or deflate. it does not include a header // of any form and should only be used within streams here an external crc/etc. // is done to validate the data. The RawInflate apis can be used on data // processed like this. /// Return an autoreleased NSData w/ the result of *raw* deflating the bytes. // // Uses the default compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the payload of |data|. // // Uses the default compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the payload of |data| using |level| compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* decompressing the bytes. // // The data to decompress, it should *not* have any header (zlib nor gzip). + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* decompressing the payload of |data|. // // The data to decompress, it should *not* have any header (zlib nor gzip). + (NSData *)gtm_dataByRawInflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawInflatingData:(NSData *)data error:(NSError **)error; @end FOUNDATION_EXPORT NSString *const GTMNSDataZlibErrorDomain; FOUNDATION_EXPORT NSString *const GTMNSDataZlibErrorKey; // NSNumber FOUNDATION_EXPORT NSString *const GTMNSDataZlibRemainingBytesKey; // NSNumber typedef NS_ENUM(NSInteger, GTMNSDataZlibError) { GTMNSDataZlibErrorGreaterThan32BitsToCompress = 1024, // An internal zlib error. // GTMNSDataZlibErrorKey will contain the error value. // NSLocalizedDescriptionKey may contain an error string from zlib. // Look in zlib.h for list of errors. GTMNSDataZlibErrorInternal, // There was left over data in the buffer that was not used. // GTMNSDataZlibRemainingBytesKey will contain number of remaining bytes. GTMNSDataZlibErrorDataRemaining }; ================================================ FILE: iOS/Manager/EZShopManager/Pods/GoogleToolboxForMac/Foundation/GTMNSData+zlib.m ================================================ // // GTMNSData+zlib.m // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMNSData+zlib.h" #import #import "GTMDefines.h" #define kChunkSize 1024 NSString *const GTMNSDataZlibErrorDomain = @"com.google.GTMNSDataZlibErrorDomain"; NSString *const GTMNSDataZlibErrorKey = @"GTMNSDataZlibErrorKey"; NSString *const GTMNSDataZlibRemainingBytesKey = @"GTMNSDataZlibRemainingBytesKey"; typedef enum { CompressionModeZlib, CompressionModeGzip, CompressionModeRaw, } CompressionMode; @interface NSData (GTMZlibAdditionsPrivate) + (NSData *)gtm_dataByCompressingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level mode:(CompressionMode)mode error:(NSError **)error; + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length isRawData:(BOOL)isRawData error:(NSError **)error; @end @implementation NSData (GTMZlibAdditionsPrivate) + (NSData *)gtm_dataByCompressingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level mode:(CompressionMode)mode error:(NSError **)error { if (!bytes || !length) { return nil; } #if defined(__LP64__) && __LP64__ // Don't support > 32bit length for 64 bit, see note in header. if (length > UINT_MAX) { if (error) { *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorGreaterThan32BitsToCompress userInfo:nil]; } return nil; } #endif if (level == Z_DEFAULT_COMPRESSION) { // the default value is actually outside the range, so we have to let it // through specifically. } else if (level < Z_BEST_SPEED) { level = Z_BEST_SPEED; } else if (level > Z_BEST_COMPRESSION) { level = Z_BEST_COMPRESSION; } z_stream strm; bzero(&strm, sizeof(z_stream)); int memLevel = 8; // the default int windowBits = 15; // the default switch (mode) { case CompressionModeZlib: // nothing to do break; case CompressionModeGzip: windowBits += 16; // enable gzip header instead of zlib header break; case CompressionModeRaw: windowBits *= -1; // Negative to mean no header. break; } int retCode; if ((retCode = deflateInit2(&strm, level, Z_DEFLATED, windowBits, memLevel, Z_DEFAULT_STRATEGY)) != Z_OK) { // COV_NF_START - no real way to force this in a unittest (we guard all args) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } return nil; // COV_NF_END } // hint the size at 1/4 the input size NSMutableData *result = [NSMutableData dataWithCapacity:(length/4)]; unsigned char output[kChunkSize]; // setup the input strm.avail_in = (unsigned int)length; strm.next_in = (unsigned char*)bytes; // loop to collect the data do { // update what we're passing in strm.avail_out = kChunkSize; strm.next_out = output; retCode = deflate(&strm, Z_FINISH); if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { // COV_NF_START - no real way to force this in a unittest // (in inflate, we can feed bogus/truncated data to test, but an error // here would be some internal issue w/in zlib, and there isn't any real // way to test it) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } deflateEnd(&strm); return nil; // COV_NF_END } // collect what we got unsigned gotBack = kChunkSize - strm.avail_out; if (gotBack > 0) { [result appendBytes:output length:gotBack]; } } while (retCode == Z_OK); // if the loop exits, we used all input and the stream ended _GTMDevAssert(strm.avail_in == 0, @"thought we finished deflate w/o using all input, %u bytes left", strm.avail_in); _GTMDevAssert(retCode == Z_STREAM_END, @"thought we finished deflate w/o getting a result of stream end, code %d", retCode); // clean up deflateEnd(&strm); return result; } // gtm_dataByCompressingBytes:length:compressionLevel:useGzip: + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length isRawData:(BOOL)isRawData error:(NSError **)error { if (!bytes || !length) { return nil; } #if defined(__LP64__) && __LP64__ // Don't support > 32bit length for 64 bit, see note in header. if (length > UINT_MAX) { return nil; } #endif z_stream strm; bzero(&strm, sizeof(z_stream)); // setup the input strm.avail_in = (unsigned int)length; strm.next_in = (unsigned char*)bytes; int windowBits = 15; // 15 to enable any window size if (isRawData) { windowBits *= -1; // make it negative to signal no header. } else { windowBits += 32; // and +32 to enable zlib or gzip header detection. } int retCode; if ((retCode = inflateInit2(&strm, windowBits)) != Z_OK) { // COV_NF_START - no real way to force this in a unittest (we guard all args) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } return nil; // COV_NF_END } // hint the size at 4x the input size NSMutableData *result = [NSMutableData dataWithCapacity:(length*4)]; unsigned char output[kChunkSize]; // loop to collect the data do { // update what we're passing in strm.avail_out = kChunkSize; strm.next_out = output; retCode = inflate(&strm, Z_NO_FLUSH); if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { if (error) { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; if (strm.msg) { NSString *message = [NSString stringWithUTF8String:strm.msg]; if (message) { [userInfo setObject:message forKey:NSLocalizedDescriptionKey]; } } *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } inflateEnd(&strm); return nil; } // collect what we got unsigned gotBack = kChunkSize - strm.avail_out; if (gotBack > 0) { [result appendBytes:output length:gotBack]; } } while (retCode == Z_OK); // make sure there wasn't more data tacked onto the end of a valid compressed // stream. if (strm.avail_in != 0) { if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:strm.avail_in] forKey:GTMNSDataZlibRemainingBytesKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorDataRemaining userInfo:userInfo]; } result = nil; } // the only way out of the loop was by hitting the end of the stream _GTMDevAssert(retCode == Z_STREAM_END, @"thought we finished inflate w/o getting a result of stream end, code %d", retCode); // clean up inflateEnd(&strm); return result; } // gtm_dataByInflatingBytes:length:windowBits: @end @implementation NSData (GTMZLibAdditions) + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByGzippingBytes:bytes length:length error:NULL]; } // gtm_dataByGzippingBytes:length: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingBytes:length:error: + (NSData *)gtm_dataByGzippingData:(NSData *)data { return [self gtm_dataByGzippingData:data error:NULL]; } // gtm_dataByGzippingData: + (NSData *)gtm_dataByGzippingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingData:error: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByGzippingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByGzippingBytes:length:level: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingBytes:length:level:error + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByGzippingData:data compressionLevel:level error:NULL]; } // gtm_dataByGzippingData:level: + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingData:level:error #pragma mark - + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByDeflatingBytes:bytes length:length error:NULL]; } // gtm_dataByDeflatingBytes:length: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingBytes:length:error + (NSData *)gtm_dataByDeflatingData:(NSData *)data { return [self gtm_dataByDeflatingData:data error:NULL]; } // gtm_dataByDeflatingData: + (NSData *)gtm_dataByDeflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingData: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByDeflatingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByDeflatingBytes:length:level: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingBytes:length:level:error: + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByDeflatingData:data compressionLevel:level error:NULL]; } // gtm_dataByDeflatingData:level: + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingData:level:error: #pragma mark - + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByInflatingBytes:bytes length:length error:NULL]; } // gtm_dataByInflatingBytes:length: + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByInflatingBytes:bytes length:length isRawData:NO error:error]; } // gtm_dataByInflatingBytes:length:error: + (NSData *)gtm_dataByInflatingData:(NSData *)data { return [self gtm_dataByInflatingData:data error:NULL]; } // gtm_dataByInflatingData: + (NSData *)gtm_dataByInflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByInflatingBytes:[data bytes] length:[data length] isRawData:NO error:error]; } // gtm_dataByInflatingData: #pragma mark - + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:NULL]; } // gtm_dataByRawDeflatingBytes:length: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingBytes:length:error: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data { return [self gtm_dataByRawDeflatingData:data error:NULL]; } // gtm_dataByRawDeflatingData: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingData:error: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByRawDeflatingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByRawDeflatingBytes:length:compressionLevel: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingBytes:length:compressionLevel:error: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByRawDeflatingData:data compressionLevel:level error:NULL]; } // gtm_dataByRawDeflatingData:compressionLevel: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingData:compressionLevel:error: + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByInflatingBytes:bytes length:length error:NULL]; } // gtm_dataByRawInflatingBytes:length: + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error{ return [self gtm_dataByInflatingBytes:bytes length:length isRawData:YES error:error]; } // gtm_dataByRawInflatingBytes:length:error: + (NSData *)gtm_dataByRawInflatingData:(NSData *)data { return [self gtm_dataByRawInflatingData:data error:NULL]; } // gtm_dataByRawInflatingData: + (NSData *)gtm_dataByRawInflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByInflatingBytes:[data bytes] length:[data length] isRawData:YES error:error]; } // gtm_dataByRawInflatingData:error: @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/GoogleToolboxForMac/GTMDefines.h ================================================ // // GTMDefines.h // // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // // ============================================================================ #include #include #ifdef __OBJC__ #include #endif // __OBJC__ #if TARGET_OS_IPHONE #include #endif // TARGET_OS_IPHONE // ---------------------------------------------------------------------------- // CPP symbols that can be overridden in a prefix to control how the toolbox // is compiled. // ---------------------------------------------------------------------------- // By setting the GTM_CONTAINERS_VALIDATION_FAILED_LOG and // GTM_CONTAINERS_VALIDATION_FAILED_ASSERT macros you can control what happens // when a validation fails. If you implement your own validators, you may want // to control their internals using the same macros for consistency. #ifndef GTM_CONTAINERS_VALIDATION_FAILED_ASSERT #define GTM_CONTAINERS_VALIDATION_FAILED_ASSERT 0 #endif // Ensure __has_feature and __has_extension are safe to use. // See http://clang-analyzer.llvm.org/annotations.html #ifndef __has_feature // Optional. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif // Give ourselves a consistent way to do inlines. Apple's macros even use // a few different actual definitions, so we're based off of the foundation // one. #if !defined(GTM_INLINE) #if (defined (__GNUC__) && (__GNUC__ == 4)) || defined (__clang__) #define GTM_INLINE static __inline__ __attribute__((always_inline)) #else #define GTM_INLINE static __inline__ #endif #endif // Give ourselves a consistent way of doing externs that links up nicely // when mixing objc and objc++ #if !defined (GTM_EXTERN) #if defined __cplusplus #define GTM_EXTERN extern "C" #define GTM_EXTERN_C_BEGIN extern "C" { #define GTM_EXTERN_C_END } #else #define GTM_EXTERN extern #define GTM_EXTERN_C_BEGIN #define GTM_EXTERN_C_END #endif #endif // Give ourselves a consistent way of exporting things if we have visibility // set to hidden. #if !defined (GTM_EXPORT) #define GTM_EXPORT __attribute__((visibility("default"))) #endif // Give ourselves a consistent way of declaring something as unused. This // doesn't use __unused because that is only supported in gcc 4.2 and greater. #if !defined (GTM_UNUSED) #define GTM_UNUSED(x) ((void)(x)) #endif // _GTMDevLog & _GTMDevAssert // // _GTMDevLog & _GTMDevAssert are meant to be a very lightweight shell for // developer level errors. This implementation simply macros to NSLog/NSAssert. // It is not intended to be a general logging/reporting system. // // Please see http://code.google.com/p/google-toolbox-for-mac/wiki/DevLogNAssert // for a little more background on the usage of these macros. // // _GTMDevLog log some error/problem in debug builds // _GTMDevAssert assert if condition isn't met w/in a method/function // in all builds. // // To replace this system, just provide different macro definitions in your // prefix header. Remember, any implementation you provide *must* be thread // safe since this could be called by anything in what ever situtation it has // been placed in. // // We only define the simple macros if nothing else has defined this. #ifndef _GTMDevLog #ifdef DEBUG #define _GTMDevLog(...) NSLog(__VA_ARGS__) #else #define _GTMDevLog(...) do { } while (0) #endif #endif // _GTMDevLog #ifndef _GTMDevAssert // we directly invoke the NSAssert handler so we can pass on the varargs // (NSAssert doesn't have a macro we can use that takes varargs) #if !defined(NS_BLOCK_ASSERTIONS) #define _GTMDevAssert(condition, ...) \ do { \ if (!(condition)) { \ [[NSAssertionHandler currentHandler] \ handleFailureInFunction:(NSString *) \ [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \ file:(NSString *)[NSString stringWithUTF8String:__FILE__] \ lineNumber:__LINE__ \ description:__VA_ARGS__]; \ } \ } while(0) #else // !defined(NS_BLOCK_ASSERTIONS) #define _GTMDevAssert(condition, ...) do { } while (0) #endif // !defined(NS_BLOCK_ASSERTIONS) #endif // _GTMDevAssert // _GTMCompileAssert // // Note: Software for current compilers should just use _Static_assert directly // instead of this macro. // // _GTMCompileAssert is an assert that is meant to fire at compile time if you // want to check things at compile instead of runtime. For example if you // want to check that a wchar is 4 bytes instead of 2 you would use // _GTMCompileAssert(sizeof(wchar_t) == 4, wchar_t_is_4_bytes_on_OS_X) // Note that the second "arg" is not in quotes, and must be a valid processor // symbol in it's own right (no spaces, punctuation etc). // Wrapping this in an #ifndef allows external groups to define their own // compile time assert scheme. #ifndef _GTMCompileAssert #if __has_feature(c_static_assert) || __has_extension(c_static_assert) #define _GTMCompileAssert(test, msg) _Static_assert((test), #msg) #else // Pre-Xcode 7 support. // // We got this technique from here: // http://unixjunkie.blogspot.com/2007/10/better-compile-time-asserts_29.html #define _GTMCompileAssertSymbolInner(line, msg) _GTMCOMPILEASSERT ## line ## __ ## msg #define _GTMCompileAssertSymbol(line, msg) _GTMCompileAssertSymbolInner(line, msg) #define _GTMCompileAssert(test, msg) \ typedef char _GTMCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] #endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) #endif // _GTMCompileAssert // ---------------------------------------------------------------------------- // CPP symbols defined based on the project settings so the GTM code has // simple things to test against w/o scattering the knowledge of project // setting through all the code. // ---------------------------------------------------------------------------- // Provide a single constant CPP symbol that all of GTM uses for ifdefing // iPhone code. #if TARGET_OS_IPHONE // iPhone SDK // For iPhone specific stuff #define GTM_IPHONE_SDK 1 #if TARGET_IPHONE_SIMULATOR #define GTM_IPHONE_DEVICE 0 #define GTM_IPHONE_SIMULATOR 1 #else #define GTM_IPHONE_DEVICE 1 #define GTM_IPHONE_SIMULATOR 0 #endif // TARGET_IPHONE_SIMULATOR // By default, GTM has provided it's own unittesting support, define this // to use the support provided by Xcode, especially for the Xcode4 support // for unittesting. #ifndef GTM_USING_XCTEST #define GTM_USING_XCTEST 0 #endif #define GTM_MACOS_SDK 0 #else // For MacOS specific stuff #define GTM_MACOS_SDK 1 #define GTM_IPHONE_SDK 0 #define GTM_IPHONE_SIMULATOR 0 #define GTM_IPHONE_DEVICE 0 #ifndef GTM_USING_XCTEST #define GTM_USING_XCTEST 0 #endif #endif // Some of our own availability macros #if GTM_MACOS_SDK #define GTM_AVAILABLE_ONLY_ON_IPHONE UNAVAILABLE_ATTRIBUTE #define GTM_AVAILABLE_ONLY_ON_MACOS #else #define GTM_AVAILABLE_ONLY_ON_IPHONE #define GTM_AVAILABLE_ONLY_ON_MACOS UNAVAILABLE_ATTRIBUTE #endif // GC was dropped by Apple, define the old constant incase anyone still keys // off of it. #ifndef GTM_SUPPORT_GC #define GTM_SUPPORT_GC 0 #endif // Some support for advanced clang static analysis functionality #ifndef NS_RETURNS_RETAINED #if __has_feature(attribute_ns_returns_retained) #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained)) #else #define NS_RETURNS_RETAINED #endif #endif #ifndef NS_RETURNS_NOT_RETAINED #if __has_feature(attribute_ns_returns_not_retained) #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) #else #define NS_RETURNS_NOT_RETAINED #endif #endif #ifndef CF_RETURNS_RETAINED #if __has_feature(attribute_cf_returns_retained) #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) #else #define CF_RETURNS_RETAINED #endif #endif #ifndef CF_RETURNS_NOT_RETAINED #if __has_feature(attribute_cf_returns_not_retained) #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained)) #else #define CF_RETURNS_NOT_RETAINED #endif #endif #ifndef NS_CONSUMED #if __has_feature(attribute_ns_consumed) #define NS_CONSUMED __attribute__((ns_consumed)) #else #define NS_CONSUMED #endif #endif #ifndef CF_CONSUMED #if __has_feature(attribute_cf_consumed) #define CF_CONSUMED __attribute__((cf_consumed)) #else #define CF_CONSUMED #endif #endif #ifndef NS_CONSUMES_SELF #if __has_feature(attribute_ns_consumes_self) #define NS_CONSUMES_SELF __attribute__((ns_consumes_self)) #else #define NS_CONSUMES_SELF #endif #endif #ifndef GTM_NONNULL #if defined(__has_attribute) #if __has_attribute(nonnull) #define GTM_NONNULL(x) __attribute__((nonnull x)) #else #define GTM_NONNULL(x) #endif #else #define GTM_NONNULL(x) #endif #endif // Invalidates the initializer from which it's called. #ifndef GTMInvalidateInitializer #if __has_feature(objc_arc) #define GTMInvalidateInitializer() \ do { \ [self class]; /* Avoid warning of dead store to |self|. */ \ _GTMDevAssert(NO, @"Invalid initializer."); \ return nil; \ } while (0) #else #define GTMInvalidateInitializer() \ do { \ [self release]; \ _GTMDevAssert(NO, @"Invalid initializer."); \ return nil; \ } while (0) #endif #endif #ifndef GTMCFAutorelease // GTMCFAutorelease returns an id. In contrast, Apple's CFAutorelease returns // a CFTypeRef. #if __has_feature(objc_arc) #define GTMCFAutorelease(x) CFBridgingRelease(x) #else #define GTMCFAutorelease(x) ([(id)x autorelease]) #endif #endif #ifdef __OBJC__ // Macro to allow you to create NSStrings out of other macros. // #define FOO foo // NSString *fooString = GTM_NSSTRINGIFY(FOO); #if !defined (GTM_NSSTRINGIFY) #define GTM_NSSTRINGIFY_INNER(x) @#x #define GTM_NSSTRINGIFY(x) GTM_NSSTRINGIFY_INNER(x) #endif // Macro to allow fast enumeration when building for 10.5 or later, and // reliance on NSEnumerator for 10.4. Remember, NSDictionary w/ FastEnumeration // does keys, so pick the right thing, nothing is done on the FastEnumeration // side to be sure you're getting what you wanted. #ifndef GTM_FOREACH_OBJECT #if TARGET_OS_IPHONE || !(MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) #define GTM_FOREACH_ENUMEREE(element, enumeration) \ for (element in enumeration) #define GTM_FOREACH_OBJECT(element, collection) \ for (element in collection) #define GTM_FOREACH_KEY(element, collection) \ for (element in collection) #else #define GTM_FOREACH_ENUMEREE(element, enumeration) \ for (NSEnumerator *_ ## element ## _enum = enumeration; \ (element = [_ ## element ## _enum nextObject]) != nil; ) #define GTM_FOREACH_OBJECT(element, collection) \ GTM_FOREACH_ENUMEREE(element, [collection objectEnumerator]) #define GTM_FOREACH_KEY(element, collection) \ GTM_FOREACH_ENUMEREE(element, [collection keyEnumerator]) #endif #endif // ============================================================================ // GTM_SEL_STRING is for specifying selector (usually property) names to KVC // or KVO methods. // In debug it will generate warnings for undeclared selectors if // -Wunknown-selector is turned on. // In release it will have no runtime overhead. #ifndef GTM_SEL_STRING #ifdef DEBUG #define GTM_SEL_STRING(selName) NSStringFromSelector(@selector(selName)) #else #define GTM_SEL_STRING(selName) @#selName #endif // DEBUG #endif // GTM_SEL_STRING #ifndef GTM_WEAK #if __has_feature(objc_arc_weak) // With ARC enabled, __weak means a reference that isn't implicitly // retained. __weak objects are accessed through runtime functions, so // they are zeroed out, but this requires OS X 10.7+. // At clang r251041+, ARC-style zeroing weak references even work in // non-ARC mode. #define GTM_WEAK __weak #elif __has_feature(objc_arc) // ARC, but targeting 10.6 or older, where zeroing weak references don't // exist. #define GTM_WEAK __unsafe_unretained #else // With manual reference counting, __weak used to be silently ignored. // clang r251041 gives it the ARC semantics instead. This means they // now require a deployment target of 10.7, while some clients of GTM // still target 10.6. In these cases, expand to __unsafe_unretained instead #define GTM_WEAK #endif #endif #endif // __OBJC__ ================================================ FILE: iOS/Manager/EZShopManager/Pods/GoogleToolboxForMac/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: iOS/Manager/EZShopManager/Pods/GoogleToolboxForMac/README.md ================================================ # GTM: Google Toolbox for Mac # **Project site**
**Discussion group** # Google Toolbox for Mac # A collection of source from different Google projects that may be of use to developers working other iOS or OS X projects. If you find a problem/bug or want a new feature to be included in the Google Toolbox for Mac, please join the [discussion group](http://groups.google.com/group/google-toolbox-for-mac) or submit an [issue](https://github.com/google/google-toolbox-for-mac/issues). ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/README.md ================================================

Kingfisher

codebeat badge

Kingfisher is a lightweight, pure-Swift library for downloading and caching images from the web. This project is heavily inspired by the popular [SDWebImage](https://github.com/rs/SDWebImage). It provides you a chance to use a pure-Swift alternative in your next app. ## Features - [x] Asynchronous image downloading and caching. - [x] `URLSession`-based networking. Basic image processors and filters supplied. - [x] Multiple-layer cache for both memory and disk. - [x] Cancelable downloading and processing tasks to improve performance. - [x] Independent components. Use the downloader or caching system separately as you need. - [x] Prefetching images and showing them from cache later when necessary. - [x] Extensions for `UIImageView`, `NSImage` and `UIButton` to directly set an image from a URL. - [x] Built-in transition animation when setting images. - [x] Extensible image processing and image format support. The simplest use-case is setting an image to an image view with the `UIImageView` extension: ```swift let url = URL(string: "url_of_your_image") imageView.kf.setImage(with: url) ``` Kingfisher will download the image from `url`, send it to both the memory cache and the disk cache, and display it in `imageView`. When you use the same code later, the image will be retrieved from cache and shown immediately. ## Requirements - iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ - Swift 3 (Kingfisher 3.x), Swift 2.3 (Kingfisher 2.x) Main development of Kingfisher will support Swift 3. Only critical bug fixes will be made for Kingfisher 2.x. [Kingfisher 3.0 Migration Guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information. ## Next Steps We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there. * [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project. * [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher! * [API Reference](http://cocoadocs.org/docsets/Kingfisher/) - Lastly, please remember to read the full whenever you may need a more detailed reference. ## Other ### Future of Kingfisher I want to keep Kingfisher lightweight. This framework will focus on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better. ### About the logo The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions? ### Contact Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, just [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well. ### License Kingfisher is released under the MIT license. See LICENSE for details. ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/AnimatedImageView.swift ================================================ // // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2017 Reda Lemeden. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. open class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. public var runLoopMode = RunLoopMode.commonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var isDisplayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { if self.isAnimating { return } else { displayLink.isPaused = false } } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.cgImage } else { layer.contents = image?.cgImage } } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show GIF. override func shouldPreloadAllGIF() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf.imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) animator?.needsPrescaling = needsPrescaling animator?.prepareFramesAsynchronously() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false { layer.setNeedsDisplay() } } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: TimeInterval static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) } // MARK: - Animator class Animator { // MARK: Private property fileprivate let size: CGSize fileprivate let maxFrameCount: Int fileprivate let imageSource: CGImageSource fileprivate var animatedFrames = [AnimatedFrame]() fileprivate let maxTimeStep: TimeInterval = 1.0 fileprivate var frameCount = 0 fileprivate var currentFrameIndex = 0 fileprivate var currentPreloadIndex = 0 fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 fileprivate var needsPrescaling = true /// Loop count of animatd image. private var loopCount = 0 var currentFrame: UIImage? { return frame(at: currentFrameIndex) } var contentMode = UIViewContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - parameter framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) { self.imageSource = source self.contentMode = mode self.size = size self.maxFrameCount = count } func frame(at index: Int) -> Image? { return animatedFrames[safe: index]?.image } func prepareFramesAsynchronously() { preloadQueue.async { [weak self] in self?.prepareFrames() } } private func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0.. AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null } let defaultGIFFrameDuration = 0.100 let frameDuration = imageSource.kf.gifProperties(at: index).map { gifInfo -> Double in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime ?? 0.0 /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See and for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : defaultGIFFrameDuration } ?? defaultGIFFrameDuration let image = Image(cgImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf.resize(to: size, for: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndex currentFrameIndex += 1 currentFrameIndex = currentFrameIndex % animatedFrames.count if animatedFrames.count < frameCount { preloadFrameAsynchronously(at: lastFrameIndex) } return true } private func preloadFrameAsynchronously(at index: Int) { preloadQueue.async { [weak self] in self?.preloadFrame(at: index) } } private func preloadFrame(at index: Int) { animatedFrames[index] = prepareFrame(at: currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } } extension CGImageSource: KingfisherCompatible { } extension Kingfisher where Base: CGImageSource { func gifProperties(at index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] } } extension Array { subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } private func pure(_ value: T) -> [T] { return [value] } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Box.swift ================================================ // // Box.swift // Kingfisher // // Created by WANG WEI on 2016/09/12. // Copyright © 2016年 Wei Wang. All rights reserved. // import Foundation class Box { let value: T init(value: T) { self.value = value } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/CacheSerializer.swift ================================================ // // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. public protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. public struct DefaultCacheSerializer: CacheSerializer { public static let `default` = DefaultCacheSerializer() private init() {} public func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher.image( data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData, onlyFirstFrame: options.onlyLoadFirstFrame) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Filter.swift ================================================ // // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage import Accelerate // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Transformer method which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Supply a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Wrapper for a `Transformer` of CIImage filters. public struct Filter { let transform: Transformer public init(tranform: @escaping Transformer) { self.transform = tranform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let colorImage = colorFilter.outputImage let filter = CIFilter(name: "CISourceOverCompositing")! filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) return filter.outputImage?.cropping(to: input.extent) } } public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { brightness, contrast, saturation, inputEV in Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor) let paramsExposure = [kCIInputEVKey: inputEV] return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure) } } } extension Kingfisher where Base: Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } } public extension Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.", renamed: "kf.apply") public func kf_apply(_ filter: Filter) -> Image { return kf.apply(filter) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Image.swift ================================================ // // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? #endif private var animatedImageDataKey: Void? import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Kingfisher where Base: Image { fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CGFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: - Image Conversion extension Kingfisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // No need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Kingfisher where Base: Image { // MARK: - PNG public func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: - JPEG public func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF public func gifRepresentation() -> Data? { return animatedImageData } } // MARK: - Create images from data extension Kingfisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary?) -> Double { let gifDefaultFrameDuration = 0.100 guard let gifInfo = gifInfo else { return gifDefaultFrameDuration } let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { return nil } let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary gifDuration += frameDuration(from: gifInfo) } images.append(Kingfisher.image(cgImage: imageRef, scale: scale, refImage: nil)) if onlyFirstFrame { break } } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image: Image? if onlyFirstFrame { image = images.first } else { image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration } image?.kf.animatedImageData = data return image #else let image: Image? if preloadAll || onlyFirstFrame { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } image = onlyFirstFrame ? images.first : Kingfisher.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) } else { image = Image(data: data) image?.kf.imageSource = ImageSource(ref: imageSource) } image?.kf.animatedImageData = data return image #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Kingfisher.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Kingfisher.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Kingfisher where Base: Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: let newSize = self.size.kf.constrained(size) return resize(to: newSize) case .scaleAspectFill: let newSize = self.size.kf.filling(size) return resize(to: newSize) default: return resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func resize(to size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return base #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = Float(max(radius, 2.0)) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. var targetRadius = floor(s * 3.0 * sqrt(2 * Float.pi) / 4.0 + 0.5) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = vImagePixelCount(context.width) let height = vImagePixelCount(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } guard let context = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = createEffectBuffer(context) guard let outContext = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } var outBuffer = createEffectBuffer(outContext) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Kingfisher where Base: Image { var decoded: Image? { return decoded(scale: scale) } func decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = beginContext() else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return base } defer { endContext() } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Kingfisher.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingfisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } public struct CGSizeProxy { fileprivate let base: CGSize init(proxy: CGSize) { base = proxy } } extension CGSize: KingfisherCompatible { public typealias CompatibleType = CGSizeProxy public var kf: CGSizeProxy { return CGSizeProxy(proxy: self) } } extension CGSizeProxy { func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension Kingfisher where Base: Image { func beginContext() -> CGContext? { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return nil } rep.size = size NSGraphicsContext.saveGraphicsState() guard let context = NSGraphicsContext(bitmapImageRep: rep) else { assertionFailure("[Kingfisher] Image contenxt cannot be created.") return nil } NSGraphicsContext.setCurrent(context) return context.cgContext #else UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.scaleBy(x: 1.0, y: -1.0) context?.translateBy(x: 0, y: -size.height) return context #endif } func endContext() { #if os(macOS) NSGraphicsContext.restoreGraphicsState() #else UIGraphicsEndImageContext() #endif } func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return base } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension Float { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Deprecated. Only for back compatibility. extension Image { /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", renamed: "kf.normalized") public func kf_normalized() -> Image { return kf.normalized } // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", renamed: "kf.image") public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return kf.image(withRoundRadius: radius, fit: size) } // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", renamed: "kf.resize") public func kf_resize(to size: CGSize) -> Image { return kf.resize(to: size) } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", renamed: "kf.blurred") public func kf_blurred(withRadius radius: CGFloat) -> Image { return kf.blurred(withRadius: radius) } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", renamed: "kf.overlaying") public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { return kf.overlaying(with: color, fraction: fraction) } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", renamed: "kf.tinted") public func kf_tinted(with color: Color) -> Image { return kf.tinted(with: color) } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", renamed: "kf.adjusted") public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) } } extension Kingfisher where Base: Image { @available(*, deprecated, message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)") public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return image(withRoundRadius: radius, fit: size) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImageCache.swift ================================================ // // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif public extension Notification.Name { /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public static var KingfisherDidCleanDiskCache = Notification.Name.init("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") } /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = DispatchWorkItem /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case none, memory, disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, /// you can create your own cache object and configure it as your need. You could use an `ImageCache` /// object to manipulate memory and disk cache for Kingfisher. open class ImageCache { //Memory fileprivate let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of /// all cached images in memory. /// Default is unlimited. Memory cache will be purged automatically when a /// memory warning notification is received. open var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk fileprivate let ioQueue: DispatchQueue fileprivate var fileManager: FileManager! ///The disk cache location. open let diskCachePath: String /// The default file extension appended to cached files. open var pathExtension: String? /// The longest time duration in second of the cache being stored in disk. /// Default is 1 week (60 * 60 * 24 * 7 seconds). /// Setting this to a negative value will make the disk cache never expiring. open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// The largest disk size can be taken for the cache. It is the total /// allocated size of cached files in bytes. /// Default is no limit. open var maxDiskCacheSize: UInt = 0 fileprivate let processQueue: DispatchQueue /// The default cache. public static let `default` = ImageCache(name: "default") /// Closure that defines the disk cache path from a given path and cacheName. public typealias DiskCachePathClosure = (String?, String) -> String /// The default DiskCachePathClosure public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String { let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! return (dstPath as NSString).appendingPathComponent(cacheName) } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string. - parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value), the `.cachesDirectory` in of your app will be used. - parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates the final disk cache path. You could use it to fully customize your cache path. - returns: The cache object. */ public init(name: String, path: String? = nil, diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)" memoryCache.name = cacheName diskCachePath = diskCachePathClosure(path, cacheName) let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)" ioQueue = DispatchQueue(label: ioQueueName) let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)" processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent) ioQueue.sync { fileManager = FileManager() } #if !os(macOS) && !os(watchOS) NotificationCenter.default.addObserver( self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(cleanExpiredDiskCache), name: .UIApplicationWillTerminate, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil) #endif } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Store & Remove /** Store an image to cache. It will be saved to both memory and disk. It is an async operation. - parameter image: The image to be stored. - parameter original: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. This identifier will be used to generate a corresponding key for the combination of `key` and processor. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when store operation completes. */ open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf.imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { DispatchQueue.main.async { handler() } } } if toDisk { ioQueue.async { if let data = serializer.data(with: image, original: original) { if !self.fileManager.fileExists(atPath: self.diskCachePath) { do { try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil) } callHandlerInMainQueue() } } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation. - parameter key: Key for the image. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. This identifier will be used to generate a corresponding key for the combination of `key` and processor. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromDisk: Bool = true, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) memoryCache.removeObject(forKey: computedKey as NSString) func callHandlerInMainQueue() { if let handler = completionHandler { DispatchQueue.main.async { handler() } } } if fromDisk { ioQueue.async{ do { try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey)) } catch _ {} callHandlerInMainQueue() } } else { callHandlerInMainQueue() } } // MARK: - Get data from cache /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ @discardableResult open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? let options = options ?? KingfisherEmptyOptionsInfo if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) { options.callbackDispatchQueue.safeAsync { completionHandler(image, .memory) } } else { var sSelf: ImageCache! = self block = DispatchWorkItem(block: { // Begin to load image from disk if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) { if options.backgroundDecode { sSelf.processQueue.async { let result = image.kf.decoded(scale: options.scaleFactor) sSelf.store(result, forKey: key, processorIdentifier: options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: false, completionHandler: nil) options.callbackDispatchQueue.safeAsync { completionHandler(result, .memory) sSelf = nil } } } else { sSelf.store(image, forKey: key, processorIdentifier: options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: false, completionHandler: nil ) options.callbackDispatchQueue.safeAsync { completionHandler(image, .disk) sSelf = nil } } } else { // No image found from either memory or disk options.callbackDispatchQueue.safeAsync { completionHandler(nil, .none) sSelf = nil } } }) sSelf.ioQueue.async(execute: block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ open func retrieveImageInMemoryCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo let computedKey = key.computedKey(with: options.processor.identifier) return memoryCache.object(forKey: computedKey as NSString) as? Image } /** Get an image for a key from disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo let computedKey = key.computedKey(with: options.processor.identifier) return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options) } // MARK: - Clear & Clean /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ open func clearDiskCache(completion handler: (()->())? = nil) { ioQueue.async { do { try self.fileManager.removeItem(atPath: self.diskCachePath) try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let handler = handler { DispatchQueue.main.async { handler() } } } } /** Clean expired disk cache. This is an async operation. */ @objc fileprivate func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ open func cleanExpiredDiskCache(completion handler: (()->())? = nil) { // Do things in cocurrent io queue ioQueue.async { var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false) for fileURL in URLsToDelete { do { try self.fileManager.removeItem(at: fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue { resourceValue1, resourceValue2 -> Bool in if let date1 = resourceValue1.contentAccessDate, let date2 = resourceValue2.contentAccessDate { return date1.compare(date2) == .orderedAscending } // Not valid date information. This should not happen. Just in case. return true } for fileURL in sortedFiles { do { try self.fileManager.removeItem(at: fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize { diskCacheSize -= UInt(fileSize) } if diskCacheSize < targetSize { break } } } DispatchQueue.main.async { if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map { $0.lastPathComponent } NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } handler?() } } } fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) { let diskCacheURL = URL(fileURLWithPath: diskCachePath) let resourceKeys: Set = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey] let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond) var cachedFiles = [URL: URLResourceValues]() var urlsToDelete = [URL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumerator(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles, errorHandler: nil), let urls = fileEnumerator.allObjects as? [URL] { for fileUrl in urls { do { let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys) // If it is a Directory. Continue to next file URL. if resourceValues.isDirectory == true { continue } // If this file is expired, add it to URLsToDelete if !onlyForCacheSize, let expiredDate = expiredDate, let lastAccessData = resourceValues.contentAccessDate, (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate { urlsToDelete.append(fileUrl) continue } if let fileSize = resourceValues.totalFileAllocatedSize { diskCacheSize += UInt(fileSize) if !onlyForCacheSize { cachedFiles[fileUrl] = resourceValues } } } catch _ { } } } return (urlsToDelete, diskCacheSize, cachedFiles) } #if !os(macOS) && !os(watchOS) /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = Kingfisher.shared else { return } func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTask { endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCache { endBackgroundTask(&backgroundTask!) } } #endif // MARK: - Check cache status /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult { let computedKey = key.computedKey(with: identifier) if memoryCache.object(forKey: computedKey as NSString) != nil { return CacheCheckResult(cached: true, cacheType: .memory) } let filePath = cachePath(forComputedKey: computedKey) var diskCached = false ioQueue.sync { diskCached = fileManager.fileExists(atPath: filePath) } if diskCached { return CacheCheckResult(cached: true, cacheType: .disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. - returns: Corresponding hash. */ open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String { let computedKey = key.computedKey(with: identifier) return cacheFileName(forComputedKey: computedKey) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) { ioQueue.async { let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true) DispatchQueue.main.async { handler(diskCacheSize) } } } /** Get the cache path for the key. It is useful for projects with UIWebView or anyone that needs access to the local file path. i.e. Replace the `` tag in your HTML. - Note: This method does not guarantee there is an image already cached in the path. It just returns the path that the image should be. You could use `isImageCached(forKey:)` method to check whether the image is cached under that key. */ open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String { let computedKey = key.computedKey(with: identifier) return cachePath(forComputedKey: computedKey) } open func cachePath(forComputedKey key: String) -> String { let fileName = cacheFileName(forComputedKey: key) return (diskCachePath as NSString).appendingPathComponent(fileName) } } // MARK: - Internal Helper extension ImageCache { func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? { if let data = diskImageData(forComputedKey: key) { return serializer.image(with: data, options: options) } else { return nil } } func diskImageData(forComputedKey key: String) -> Data? { let filePath = cachePath(forComputedKey: key) return (try? Data(contentsOf: URL(fileURLWithPath: filePath))) } func cacheFileName(forComputedKey key: String) -> String { if let ext = self.pathExtension { return (key.kf.md5 as NSString).appendingPathExtension(ext)! } return key.kf.md5 } } extension Kingfisher where Base: Image { var imageCost: Int { return images == nil ? Int(size.height * size.width * scale * scale) : Int(size.height * size.width * scale * scale) * images!.count } } extension Dictionary { func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(macOS) && !os(watchOS) // MARK: - For App Extensions extension UIApplication: KingfisherCompatible { } extension Kingfisher where Base: UIApplication { public static var shared: UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard Base.responds(to: selector) else { return nil } return Base.perform(selector).takeUnretainedValue() as? UIApplication } } #endif extension String { func computedKey(with identifier: String) -> String { if identifier.isEmpty { return self } else { return appending("@\(identifier)") } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImageDownloader.swift ================================================ // // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: URLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var url: URL? { return internalTask.originalRequest?.url } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } ///The code of errors which `ImageDownloader` might encountered. public enum KingfisherError: Int { /// badData: The downloaded data is not an image or the data is corrupted. case badData = 10000 /// notModified: The remote server responsed a 304 code. No image data downloaded. case notModified = 10001 /// The HTTP status code in response is not valid. If an invalid /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` /// in `userInfo` to see the code. case invalidStatusCode = 10002 /// notCached: The image rquested is not in cache but .onlyFromCache is activated. case notCached = 10003 /// The URL is invalid. case invalidURL = 20000 /// The downloading task is cancelled before started. case downloadCancelledBeforeStarting = 30000 } /// Key will be used in the `userInfo` of `.invalidStatusCode` public let KingfisherErrorStatusCodeKey = "statusCode" /// Protocol of `ImageDownloader`. public protocol ImageDownloaderDelegate: class { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter url: URL of the original request URL. - parameter response: The response object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) /** Check if a received HTTP status code is valid or not. By default, a status code between 200 to 400 (excluded) is considered as valid. If an invalid code is received, the downloader will raise an .invalidStatusCode error. It has a `userInfo` which includes this statusCode and localizedString error message. - parameter code: The received HTTP status code. - parameter downloader: The `ImageDownloader` object asking for validate status code. - returns: Whether this HTTP status code is valid or not. - Note: If the default 200 to 400 valid code does not suit your need, you can implement this method to change that behavior. */ func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool } extension ImageDownloaderDelegate { public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { return (200..<400).contains(code) } } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponsable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { class ImageFetchLoad { var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? } // MARK: - Public property /// The duration before the download is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) } } /// Whether the download requests should use pipeling or not. Default is false. open var requestsUsePipeling = false fileprivate let sessionHandler: ImageDownloaderSessionHandler fileprivate var session: URLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? // MARK: - Internal property let barrierQueue: DispatchQueue let processQueue: DispatchQueue typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) var fetchLoads = [URL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public static let `default` = ImageDownloader(name: "default") /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) sessionHandler = ImageDownloaderSessionHandler() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) } func fetchLoad(for url: URL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? barrierQueue.sync { fetchLoad = fetchLoads[url] } return fetchLoad } /** Download an image with a URL and option. - parameter url: Target URL. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ @discardableResult open func downloadImage(with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? { return downloadImage(with: url, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } } // MARK: - Download method extension ImageDownloader { func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask?, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) request.httpShouldUsePipelining = requestsUsePipeling if let modifier = options?.modifier { guard let r = modifier.modified(for: request) else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } request = r } // There is a possiblility that request modifier changed the url to `nil` or empty. guard let url = request.url, !url.absoluteString.isEmpty else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) return nil } var downloadTask: RetrieveImageDownloadTask? setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTask(with: request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority dataTask.resume() // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } // A single key may have multiple callbacks. Only download once. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: ((URLSession, ImageFetchLoad) -> Void)) { barrierQueue.sync(flags: .barrier) { let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) fetchLoads[url] = loadObjectForURL if let session = session { started(session, loadObjectForURL) } } } func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { barrierQueue.sync { if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func clean(for url: URL) { barrierQueue.sync(flags: .barrier) { fetchLoads.removeValue(forKey: url) return } } } // MARK: - NSURLSessionDataDelegate /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. // See https://github.com/onevcat/Kingfisher/issues/235 class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let downloader = downloadHolder else { completionHandler(.cancel) return } if let statusCode = (response as? HTTPURLResponse)?.statusCode, let url = dataTask.originalRequest?.url, !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) callCompletionHandlerFailure(error: error, url: url) } completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let downloader = downloadHolder else { return } if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { fetchLoad.responseData.append(data) if let expectedLength = dataTask.response?.expectedContentLength { for content in fetchLoad.contents { DispatchQueue.main.async { content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) } } } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { callCompletionHandlerFailure(error: error!, url: url) return } processImage(for: task, url: url) } /** This method is exposed since the compiler requests. Do not call it. */ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) } private func cleanFetchLoad(for url: URL) { guard let downloader = downloadHolder else { return } downloader.clean(for: url) if downloader.fetchLoads.isEmpty { downloadHolder = nil } } private func callCompletionHandlerFailure(error: Error, url: URL) { guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { return } // We need to clean the fetch load first, before actually calling completion handler. cleanFetchLoad(for: url) for content in fetchLoad.contents { content.options.callbackDispatchQueue.safeAsync { content.callback.completionHandler?(nil, error as NSError, url, nil) } } } private func processImage(for task: URLSessionTask, url: URL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. downloader.processQueue.async { guard let fetchLoad = downloader.fetchLoad(for: url) else { return } self.cleanFetchLoad(for: url) let data = fetchLoad.responseData as Data // Cache the processed images. So we do not need to re-process the image if using the same processor. // Key is the identifier of processor. var imageCache: [String: Image] = [:] for content in fetchLoad.contents { let options = content.options let completionHandler = content.callback.completionHandler let callbackQueue = options.callbackDispatchQueue let processor = options.processor var image = imageCache[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: options) // Add the processed image to cache. // If `image` is nil, nothing will happen (since the key is not existing before). imageCache[processor.identifier] = image } if let image = image { downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) if options.backgroundDecode { let decodedImage = image.kf.decoded(scale: options.scaleFactor) callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } } else { callbackQueue.safeAsync { completionHandler?(image, nil, url, data) } } } else { if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) completionHandler?(nil, notModified, url, nil) continue } let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } } } } } } // Placeholder. For retrieving extension methods of ImageDownloaderDelegate extension ImageDownloader: ImageDownloaderDelegate {} ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImagePrefetcher.swift ================================================ // // ImagePrefetcher.swift // Kingfisher // // Created by Claire Knight on 24/02/2016 // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// Completion block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. /// This is useful when you know a list of image resources and want to download them before showing. public class ImagePrefetcher { /// The maximum concurrent downloads to use when prefetching images. Default is 5. public var maxConcurrentDownloads = 5 private let prefetchResources: [Resource] private let optionsInfo: KingfisherOptionsInfo private var progressBlock: PrefetcherProgressBlock? private var completionHandler: PrefetcherCompletionHandler? private var tasks = [URL: RetrieveImageDownloadTask]() private var pendingResources: ArraySlice private var skippedResources = [Resource]() private var completedResources = [Resource]() private var failedResources = [Resource]() private var stopped = false // The created manager used for prefetch. We will use the helper method in manager. private let manager: KingfisherManager private var finished: Bool { return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty } /** Init an image prefetcher with an array of URLs. The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter urls: The URLs which should be prefetched. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public convenience init(urls: [URL], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Init an image prefetcher with an array of resources. The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter resources: The resources which should be prefetched. See `Resource` type for more. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public init(resources: [Resource], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { prefetchResources = resources pendingResources = ArraySlice(resources) // We want all callbacks from main queue, so we ignore the call back queue in options let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil)) self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo let cache = self.optionsInfo.targetCache let downloader = self.optionsInfo.downloader manager = KingfisherManager(downloader: downloader, cache: cache) self.progressBlock = progressBlock self.completionHandler = completionHandler } /** Start to download the resources and cache them. This can be useful for background downloading of assets that are required for later use in an app. This code will not try and update any UI with the results of the process. */ public func start() { // Since we want to handle the resources cancellation in main thread only. DispatchQueue.main.safeAsync { guard !self.stopped else { assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") self.handleComplete() return } guard self.maxConcurrentDownloads > 0 else { assertionFailure("There should be concurrent downloads value should be at least 1.") self.handleComplete() return } guard self.prefetchResources.count > 0 else { self.handleComplete() return } let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads) for _ in 0 ..< initialConcurentDownloads { if let resource = self.pendingResources.popFirst() { self.startPrefetching(resource) } } } } /** Stop current downloading progress, and cancel any future prefetching activity that might be occuring. */ public func stop() { DispatchQueue.main.safeAsync { if self.finished { return } self.stopped = true self.tasks.forEach { (_, task) -> () in task.cancel() } } } func downloadAndCache(_ resource: Resource) { let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in self.tasks.removeValue(forKey: resource.downloadURL) if let _ = error { self.failedResources.append(resource) } else { self.completedResources.append(resource) } self.reportProgress() if self.stopped { if self.tasks.isEmpty { self.failedResources.append(contentsOf: self.pendingResources) self.handleComplete() } } else { self.reportCompletionOrStartNext() } } let downloadTask = manager.downloadAndCacheImage( with: resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: downloadTaskCompletionHandler, options: optionsInfo) if let downloadTask = downloadTask { tasks[resource.downloadURL] = downloadTask } } func append(cached resource: Resource) { skippedResources.append(resource) reportProgress() reportCompletionOrStartNext() } func startPrefetching(_ resource: Resource) { if optionsInfo.forceRefresh { downloadAndCache(resource) } else { let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey, processorIdentifier: optionsInfo.processor.identifier).cached if alreadyInCache { append(cached: resource) } else { downloadAndCache(resource) } } } func reportProgress() { progressBlock?(skippedResources, failedResources, completedResources) } func reportCompletionOrStartNext() { if let resource = pendingResources.popFirst() { startPrefetching(resource) } else { guard tasks.isEmpty else { return } handleComplete() } } func handleComplete() { completionHandler?(skippedResources, failedResources, completedResources) completionHandler = nil progressBlock = nil } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImageProcessor.swift ================================================ // // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics /// The item which could be processed by an `ImageProcessor` /// /// - image: Input image /// - data: Input data public enum ImageProcessItem { case image(Image) case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retriving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrived with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already taken by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation /// string of your own for the identifier. var identifier: String { get } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: The return value will be `nil` if processing failed while converting data to image. /// If input item is already an image and there is any errors in processing, the input /// image itself will be returned. /// - Note: Most processor only supports CG-based images. /// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? } typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?) public extension ImageProcessor { /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - parameter another: An `ImageProcessor` you want to append to `self`. /// /// - returns: The new `ImageProcessor`. It will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } fileprivate struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return p(item, options) } } /// The default processor. It convert the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() public let identifier = "" /// Initialize a `DefaultImageProcessor` /// /// - returns: An initialized `DefaultImageProcessor`. public init() {} public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image case .data(let data): return Kingfisher.image( data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData, onlyFirstFrame: options.onlyLoadFirstFrame) } } } /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. public struct RoundCornerImageProcessor: ImageProcessor { public let identifier: String /// Corner radius will be applied in processing. public let cornerRadius: CGFloat /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Initialize a `RoundCornerImageProcessor` /// /// - parameter cornerRadius: Corner radius will be applied in processing. /// - parameter targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// /// - returns: An initialized `RoundCornerImageProcessor`. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) { self.cornerRadius = cornerRadius self.targetSize = targetSize if let size = targetSize { self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))" } else { self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))" } } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let size = targetSize ?? image.kf.size return image.kf.image(withRoundRadius: cornerRadius, fit: size) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for resizing images. Only CG-based images are supported in macOS. public struct ResizingImageProcessor: ImageProcessor { public let identifier: String /// Target size of output image should be. public let targetSize: CGSize /// Initialize a `ResizingImageProcessor` /// /// - parameter targetSize: Target size of output image should be. /// /// - returns: An initialized `ResizingImageProcessor`. public init(targetSize: CGSize) { self.targetSize = targetSize self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.resize(to: targetSize) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Initialize a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. /// /// - returns: An initialized `BlurImageProcessor`. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.blurred(withRadius: radius) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { public var identifier: String /// Overlay color will be used to overlay the input image. public let overlay: Color /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Initialize an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An initialized `OverlayImageProcessor`. public init(overlay: Color, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.overlaying(with: overlay, fraction: fraction) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { public let identifier: String /// Tint color will be used to tint the input image. public let tint: Color /// Initialize a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. /// /// - returns: An initialized `TintImageProcessor`. public init(tint: Color) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.tinted(with: tint) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Initialize a `ColorControlsProcessor` /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An initialized `ColorControlsProcessor` public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Initialize a `BlackWhiteProcessor` /// /// - returns: An initialized `BlackWhiteProcessor` public init() {} public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally. /// /// - parameter left: First processor. /// - parameter right: Second processor. /// /// - returns: The concatenated processor. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } fileprivate extension Color { var hex: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImageTransition.swift ================================================ // // ImageTransition.swift // Kingfisher // // Created by Wei Wang on 15/9/18. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) // Not implemented for macOS and watchOS yet. import AppKit /// Image transition is not supported on macOS. public enum ImageTransition { case none var duration: TimeInterval { return 0 } } #elseif os(watchOS) import UIKit /// Image transition is not supported on watchOS. public enum ImageTransition { case none var duration: TimeInterval { return 0 } } #else import UIKit /** Transition effect which will be used when an image downloaded and set by `UIImageView` extension API in Kingfisher. You can assign an enum value with transition duration as an item in `KingfisherOptionsInfo` to enable the animation transition. Apple's UIViewAnimationOptions is used under the hood. For custom transition, you should specified your own transition options, animations and comletion handler as well. */ public enum ImageTransition { /// No animation transistion. case none /// Fade in the loaded image. case fade(TimeInterval) /// Flip from left transition. case flipFromLeft(TimeInterval) /// Flip from right transition. case flipFromRight(TimeInterval) /// Flip from top transition. case flipFromTop(TimeInterval) /// Flip from bottom transition. case flipFromBottom(TimeInterval) /// Custom transition. case custom(duration: TimeInterval, options: UIViewAnimationOptions, animations: ((UIImageView, UIImage) -> Void)?, completion: ((Bool) -> Void)?) var duration: TimeInterval { switch self { case .none: return 0 case .fade(let duration): return duration case .flipFromLeft(let duration): return duration case .flipFromRight(let duration): return duration case .flipFromTop(let duration): return duration case .flipFromBottom(let duration): return duration case .custom(let duration, _, _, _): return duration } } var animationOptions: UIViewAnimationOptions { switch self { case .none: return [] case .fade(_): return .transitionCrossDissolve case .flipFromLeft(_): return .transitionFlipFromLeft case .flipFromRight(_): return .transitionFlipFromRight case .flipFromTop(_): return .transitionFlipFromTop case .flipFromBottom(_): return .transitionFlipFromBottom case .custom(_, let options, _, _): return options } } var animations: ((UIImageView, UIImage) -> Void)? { switch self { case .custom(_, _, let animations, _): return animations default: return { $0.image = $1 } } } var completion: ((Bool) -> Void)? { switch self { case .custom(_, _, _, let completion): return completion default: return nil } } } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift ================================================ // // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif // MARK: - Extension methods. /** * Set image to use from web. */ extension Kingfisher where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.image = placeholder completionHandler?(nil, nil, .none, nil) return .empty } var options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.image = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) if base.shouldPreloadAllGIF() { options.append(.preloadAllGIFData) } let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { return } self.setImageTask(nil) guard let image = image else { maybeIndicator?.stopAnimatingView() completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { maybeIndicator?.stopAnimatingView() strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } #if !os(macOS) UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) #endif } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { newIndicator.view.frame = base.frame newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") @discardableResult public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") public var kf_indicatorType: IndicatorType { get { return kf.indicatorType } set { kf.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `kf_indicatorType` is `.none`. public private(set) var kf_indicator: Indicator? { get { return kf.indicator } set { kf.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } } extension ImageView { func shouldPreloadAllGIF() -> Bool { return true } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Indicator.swift ================================================ // // Indicator.swift // Kingfisher // // Created by João D. Moreira on 30/08/16. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif #if os(macOS) public typealias IndicatorView = NSView #else public typealias IndicatorView = UIView #endif public enum IndicatorType { /// No indicator. case none /// Use system activity indicator. case activity /// Use an image as indicator. GIF is supported. case image(imageData: Data) /// Use a custom indicator, which conforms to the `Indicator` protocol. case custom(indicator: Indicator) } // MARK: - Indicator Protocol public protocol Indicator { func startAnimatingView() func stopAnimatingView() var viewCenter: CGPoint { get set } var view: IndicatorView { get } } extension Indicator { #if os(macOS) public var viewCenter: CGPoint { get { let frame = view.frame return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) } set { let frame = view.frame let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, y: newValue.y - frame.size.height / 2.0, width: frame.size.width, height: frame.size.height) view.frame = newFrame } } #else public var viewCenter: CGPoint { get { return view.center } set { view.center = newValue } } #endif } // MARK: - ActivityIndicator // Displays a NSProgressIndicator / UIActivityIndicatorView struct ActivityIndicator: Indicator { #if os(macOS) private let activityIndicatorView: NSProgressIndicator #else private let activityIndicatorView: UIActivityIndicatorView #endif var view: IndicatorView { return activityIndicatorView } func startAnimatingView() { #if os(macOS) activityIndicatorView.startAnimation(nil) #else activityIndicatorView.startAnimating() #endif activityIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) activityIndicatorView.stopAnimation(nil) #else activityIndicatorView.stopAnimating() #endif activityIndicatorView.isHidden = true } init() { #if os(macOS) activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) activityIndicatorView.controlSize = .small activityIndicatorView.style = .spinningStyle #else #if os(tvOS) let indicatorStyle = UIActivityIndicatorViewStyle.white #else let indicatorStyle = UIActivityIndicatorViewStyle.gray #endif activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } } // MARK: - ImageIndicator // Displays an ImageView. Supports gif struct ImageIndicator: Indicator { private let animatedImageIndicatorView: ImageView var view: IndicatorView { return animatedImageIndicatorView } init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) { var options = options // Use normal image view to show gif, so we need to preload all gif data. if !options.preloadAllGIFData { options.append(.preloadAllGIFData) } guard let image = processor.process(item: .data(data), options: options) else { return nil } animatedImageIndicatorView = ImageView() animatedImageIndicatorView.image = image #if os(macOS) // Need for gif to animate on macOS self.animatedImageIndicatorView.imageScaling = .scaleNone self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true #else animatedImageIndicatorView.contentMode = .center animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } func startAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = true #else animatedImageIndicatorView.startAnimating() #endif animatedImageIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = false #else animatedImageIndicatorView.stopAnimating() #endif animatedImageIndicatorView.isHidden = true } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Kingfisher.h ================================================ // // Kingfisher.h // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import //! Project version number for Kingfisher. FOUNDATION_EXPORT double KingfisherVersionNumber; //! Project version string for Kingfisher. FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Kingfisher.swift ================================================ // // Kingfisher.swift // Kingfisher // // Created by Wei Wang on 16/9/14. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import ImageIO #if os(macOS) import AppKit public typealias Image = NSImage public typealias Color = NSColor public typealias ImageView = NSImageView typealias Button = NSButton #else import UIKit public typealias Image = UIImage public typealias Color = UIColor #if !os(watchOS) public typealias ImageView = UIImageView typealias Button = UIButton #endif #endif public final class Kingfisher { public let base: Base public init(_ base: Base) { self.base = base } } /** A type that has Kingfisher extensions. */ public protocol KingfisherCompatible { associatedtype CompatibleType var kf: CompatibleType { get } } public extension KingfisherCompatible { public var kf: Kingfisher { get { return Kingfisher(self) } } } extension Image: KingfisherCompatible { } #if !os(watchOS) extension ImageView: KingfisherCompatible { } extension Button: KingfisherCompatible { } #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/KingfisherManager.swift ================================================ // // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> ()) public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ()) /// RetrieveImageTask represents a task of image retrieving process. /// It contains an async task of getting image from disk and from network. public class RetrieveImageTask { public static let empty = RetrieveImageTask() // If task is canceled before the download task started (which means the `downloadTask` is nil), // the download task should not begin. var cancelledBeforeDownloadStarting: Bool = false /// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task. @available(*, deprecated, message: "diskRetrieveTask is not in use anymore. You cannot cancel a disk retrieve task anymore once it started.") public var diskRetrieveTask: RetrieveImageDiskTask? /// The network retrieve task in this image task. public var downloadTask: RetrieveImageDownloadTask? /** Cancel current task. If this task is already done, do nothing. */ public func cancel() { if let downloadTask = downloadTask { downloadTask.cancel() } else { cancelledBeforeDownloadStarting = true } } } /// Error domain of Kingfisher public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Shared manager used by the extensions across Kingfisher. public static let shared = KingfisherManager() /// Cache used by this manager public var cache: ImageCache /// Downloader used by this manager public var downloader: ImageDownloader convenience init() { self.init(downloader: .default, cache: .default) } init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache } /** Get an image with resource. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI. - parameter completionHandler: Called when the whole retrieving process finished. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. */ @discardableResult public func retrieveImage(with resource: Resource, options: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let task = RetrieveImageTask() if let options = options, options.forceRefresh { _ = downloadAndCacheImage( with: resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options) } else { tryToRetrieveImageFromCache( forKey: resource.cacheKey, with: resource.downloadURL, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options) } return task } @discardableResult func downloadAndCacheImage(with url: URL, forKey key: String, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask? { let options = options ?? KingfisherEmptyOptionsInfo let downloader = options.downloader return downloader.downloadImage(with: url, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { receivedSize, totalSize in progressBlock?(receivedSize, totalSize) }, completionHandler: { image, error, imageURL, originalData in let targetCache = options.targetCache if let error = error, error.code == KingfisherError.notModified.rawValue { // Not modified. Try to find the image from cache. // (The image should be in cache. It should be guaranteed by the framework users.) targetCache.retrieveImage(forKey: key, options: options, completionHandler: { (cacheImage, cacheType) -> () in completionHandler?(cacheImage, nil, cacheType, url) }) return } if let image = image, let originalData = originalData { targetCache.store(image, original: originalData, forKey: key, processorIdentifier:options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: !options.cacheMemoryOnly, completionHandler: nil) } completionHandler?(image, error, .none, url) }) } func tryToRetrieveImageFromCache(forKey key: String, with url: URL, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: KingfisherOptionsInfo?) { let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in completionHandler?(image, error, cacheType, imageURL) } let targetCache = options?.targetCache ?? cache targetCache.retrieveImage(forKey: key, options: options, completionHandler: { image, cacheType in if image != nil { diskTaskCompletionHandler(image, nil, cacheType, url) } else if let options = options, options.onlyFromCache { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notCached.rawValue, userInfo: nil) diskTaskCompletionHandler(nil, error, .none, url) } else { self.downloadAndCacheImage( with: url, forKey: key, retrieveImageTask: retrieveImageTask, progressBlock: progressBlock, completionHandler: diskTaskCompletionHandler, options: options) } } ) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift ================================================ // // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /** * KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. */ public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() /** Items could be added into KingfisherOptionsInfo. */ public enum KingfisherOptionsInfoItem { /// The associated value of this member should be an ImageCache object. Kingfisher will use the specified /// cache object when handling related operations, including trying to retrieve the cached images and store /// the downloaded image to it. case targetCache(ImageCache) /// The associated value of this member should be an ImageDownloader object. Kingfisher will use this /// downloader to download the images. case downloader(ImageDownloader) /// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `ForceTransition` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. case downloadPriority(Float) /// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `Transition` option for more. case forceTransition /// If set, `Kingfisher` will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, `Kingfisher` will only try to retrieve the image from cache not from network. case onlyFromCache /// Decode the image in background thread before using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. case callbackDispatchQueue(DispatchQueue?) /// The associated value of this member will be used as the scale factor when converting retrieved data to an image. /// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing /// with 2x or 3x retina images. case scaleFactor(CGFloat) /// Whether all the GIF data should be preloaded. Default it false, which means following frames will be /// loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly /// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload /// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use /// corresponding image view type instead of setting this option. case preloadAllGIFData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the request. You can modify the request for some customizing purpose, /// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request /// will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the /// image view. `DefaultImageProcessor.default` will be used by default. case processor(ImageProcessor) /// Supply an `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// `DefaultCacheSerializer.default` will be used by default. case cacheSerializer(CacheSerializer) /// Keep the existing image while setting another image to an image view. /// By setting this option, the placeholder image parameter of imageview extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from a GIF file as a single image. /// Loading a lot of GIFs may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a GIF image. /// This option will be ignored if the target image is not GIF. case onlyLoadFirstFrame } precedencegroup ItemComparisonPrecedence { associativity: none higherThan: LogicalConjunctionPrecedence } infix operator <== : ItemComparisonPrecedence // This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { switch (lhs, rhs) { case (.targetCache(_), .targetCache(_)): return true case (.downloader(_), .downloader(_)): return true case (.transition(_), .transition(_)): return true case (.downloadPriority(_), .downloadPriority(_)): return true case (.forceRefresh, .forceRefresh): return true case (.forceTransition, .forceTransition): return true case (.cacheMemoryOnly, .cacheMemoryOnly): return true case (.onlyFromCache, .onlyFromCache): return true case (.backgroundDecode, .backgroundDecode): return true case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true case (.scaleFactor(_), .scaleFactor(_)): return true case (.preloadAllGIFData, .preloadAllGIFData): return true case (.requestModifier(_), .requestModifier(_)): return true case (.processor(_), .processor(_)): return true case (.cacheSerializer(_), .cacheSerializer(_)): return true case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true default: return false } } extension Collection where Iterator.Element == KingfisherOptionsInfoItem { func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? { return index { $0 <== target }.flatMap { self[$0] } } func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] { return self.filter { !($0 <== target) } } } public extension Collection where Iterator.Element == KingfisherOptionsInfoItem { /// The target `ImageCache` which is used. public var targetCache: ImageCache { if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)), case .targetCache(let cache) = item { return cache } return ImageCache.default } /// The `ImageDownloader` which is specified. public var downloader: ImageDownloader { if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)), case .downloader(let downloader) = item { return downloader } return ImageDownloader.default } /// Member for animation transition when using UIImageView. public var transition: ImageTransition { if let item = firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = item { return transition } return ImageTransition.none } /// A `Float` value set as the priority of image download task. The value for it should be /// between 0.0~1.0. public var downloadPriority: Float { if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)), case .downloadPriority(let priority) = item { return priority } return URLSessionTask.defaultPriority } /// Whether an image will be always downloaded again or not. public var forceRefresh: Bool { return contains{ $0 <== .forceRefresh } } /// Whether the transition should always happen or not. public var forceTransition: Bool { return contains{ $0 <== .forceTransition } } /// Whether cache the image only in memory or not. public var cacheMemoryOnly: Bool { return contains{ $0 <== .cacheMemoryOnly } } /// Whether only load the images from cache or not. public var onlyFromCache: Bool { return contains{ $0 <== .onlyFromCache } } /// Whether the image should be decoded in background or not. public var backgroundDecode: Bool { return contains{ $0 <== .backgroundDecode } } /// Whether the image data should be all loaded at once if it is a GIF. public var preloadAllGIFData: Bool { return contains { $0 <== .preloadAllGIFData } } /// The queue of callbacks should happen from Kingfisher. public var callbackDispatchQueue: DispatchQueue { if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)), case .callbackDispatchQueue(let queue) = item { return queue ?? DispatchQueue.main } return DispatchQueue.main } /// The scale factor which should be used for the image. public var scaleFactor: CGFloat { if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)), case .scaleFactor(let scale) = item { return scale } return 1.0 } /// The `ImageDownloadRequestModifier` will be used before sending a download request. public var modifier: ImageDownloadRequestModifier { if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)), case .requestModifier(let modifier) = item { return modifier } return NoModifier.default } /// `ImageProcessor` for processing when the downloading finishes. public var processor: ImageProcessor { if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)), case .processor(let processor) = item { return processor } return DefaultImageProcessor.default } /// `CacheSerializer` to convert image to data for storing in cache. public var cacheSerializer: CacheSerializer { if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)), case .cacheSerializer(let cacheSerializer) = item { return cacheSerializer } return DefaultCacheSerializer.default } /// Keep the existing image while setting another image to an image view. /// Or the placeholder will be used while downloading. public var keepCurrentImageWhileLoading: Bool { return contains { $0 <== .keepCurrentImageWhileLoading } } public var onlyLoadFirstFrame: Bool { return contains { $0 <== .onlyLoadFirstFrame } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/RequestModifier.swift ================================================ // // RequestModifier.swift // Kingfisher // // Created by Wei Wang on 2016/09/05. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Request modifier of image downloader. public protocol ImageDownloadRequestModifier { func modified(for request: URLRequest) -> URLRequest? } struct NoModifier: ImageDownloadRequestModifier { static let `default` = NoModifier() private init() {} func modified(for request: URLRequest) -> URLRequest? { return request } } public struct AnyModifier: ImageDownloadRequestModifier { let block: (URLRequest) -> URLRequest? public func modified(for request: URLRequest) -> URLRequest? { return block(request) } public init(modify: @escaping (URLRequest) -> URLRequest? ) { block = modify } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/Resource.swift ================================================ // // Resource.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// `Resource` protocol defines how to download and cache a resource from network. public protocol Resource { /// The key used in cache. var cacheKey: String { get } /// The target image URL. var downloadURL: URL { get } } /** ImageResource is a simple combination of `downloadURL` and `cacheKey`. When passed to image view set methods, Kingfisher will try to download the target image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache. */ public struct ImageResource: Resource { /// The key used in cache. public let cacheKey: String /// The target image URL. public let downloadURL: URL /** Create a resource. - parameter downloadURL: The target image URL. - parameter cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key. - returns: A resource. */ public init(downloadURL: URL, cacheKey: String? = nil) { self.downloadURL = downloadURL self.cacheKey = cacheKey ?? downloadURL.absoluteString } } /** URL conforms to `Resource` in Kingfisher. The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`. If you need customize the url and/or cache key, use `ImageResource` instead. */ extension URL: Resource { public var cacheKey: String { return absoluteString } public var downloadURL: URL { return self } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/String+MD5.swift ================================================ // // String+MD5.swift // Kingfisher // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset and modified version of CryptoSwift as an alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation public struct StringProxy { fileprivate let base: String init(proxy: String) { base = proxy } } extension String: KingfisherCompatible { public typealias CompatibleType = StringProxy public var kf: CompatibleType { return StringProxy(proxy: self) } } extension StringProxy { var md5: String { if let data = base.data(using: .utf8, allowLossyConversion: true) { let message = data.withUnsafeBytes { bytes -> [UInt8] in return Array(UnsafeBufferPointer(start: bytes, count: data.count)) } let MD5Calculator = MD5(message) let MD5Data = MD5Calculator.calculate() let MD5String = NSMutableString() for c in MD5Data { MD5String.appendFormat("%02x", c) } return MD5String as String } else { return base } } } /** array of bytes, little-endian representation */ func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout.size * 8) let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) valuePointer.pointee = value let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0...size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } return bytes } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(_ arrayOfBytes: [UInt8]) { append(arrayOfBytes, length: arrayOfBytes.count) } } protocol HashProtocol { var message: Array { get } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len: Int) -> Array } extension HashProtocol { func prepare(_ len: Int) -> Array { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array(repeating: 0, count: counter) return tmpMessage } } func toUInt32Array(_ slice: ArraySlice) -> Array { var result = Array() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout.size) { let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 let d3 = UInt32(slice[idx]) let val: UInt32 = d0 | d1 | d2 | d3 result.append(val) } return result } struct BytesIterator: IteratorProtocol { let chunkSize: Int let data: [UInt8] init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } var offset = 0 mutating func next() -> ArraySlice? { let end = min(chunkSize, data.count - offset) let result = data[offset.. 0 ? result : nil } } struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] func makeIterator() -> BytesIterator { return BytesIterator(chunkSize: chunkSize, data: data) } } func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5: HashProtocol { static let size = 16 // 128 / 8 let message: [UInt8] init (_ message: [UInt8]) { self.message = message } /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> [UInt8] { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // hash values var hh = hashes // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reversed() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian let r1 = UInt8(itemLE & 0xff) let r2 = UInt8((itemLE >> 8) & 0xff) let r3 = UInt8((itemLE >> 16) & 0xff) let r4 = UInt8((itemLE >> 24) & 0xff) result += [r1, r2, r3, r4] } return result } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/ThreadHelper.swift ================================================ // // ThreadHelper.swift // Kingfisher // // Created by Wei Wang on 15/10/9. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension DispatchQueue { // This method will dispatch the `block` to self. // If `self` is the main queue, and current thread is main thread, the block // will be invoked immediately instead of being dispatched. func safeAsync(_ block: @escaping ()->()) { if self === DispatchQueue.main && Thread.isMainThread { block() } else { async { block() } } } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift ================================================ // // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: - Set Images /** * Set image to use in button from web for a specified state. */ extension Kingfisher where Base: UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setImage(placeholder, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } setWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL(for: state) else { return } self.setImageTask(nil) if image != nil { strongBase.setImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelImageDownloadTask() { imageTask?.cancel() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setBackgroundImage(placeholder, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } setBackgroundWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.backgroundWebURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: { [weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else { return } self.setBackgroundImageTask(nil) if image != nil { strongBase.setBackgroundImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setBackgroundImageTask(task) return task } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ public func webURL(for state: UIControlState) -> URL? { return webURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setWebURL(_ url: URL, for state: UIControlState) { webURLs[NSNumber(value:state.rawValue)] = url } fileprivate var webURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setWebURLs(dictionary!) } return dictionary! } fileprivate func setWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var lastBackgroundURLKey: Void? private var backgroundImageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ public func backgroundWebURL(for state: UIControlState) -> URL? { return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setBackgroundWebURL(_ url: URL, for state: UIControlState) { backgroundWebURLs[NSNumber(value:state.rawValue)] = url } fileprivate var backgroundWebURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setBackgroundWebURLs(dictionary!) } return dictionary! } fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var backgroundImageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask } fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web for a specified state. Deprecated. Use `kf` namespacing instead. */ extension UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setImage` instead.", renamed: "kf.setImage") public func kf_setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", renamed: "kf.cancelImageDownloadTask") public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setBackgroundImage` instead.", renamed: "kf.setBackgroundImage") public func kf_setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelBackgroundImageDownloadTask` instead.", renamed: "kf.cancelBackgroundImageDownloadTask") public func kf_cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() } /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.webURL` instead.", renamed: "kf.webURL") public func kf_webURL(for state: UIControlState) -> URL? { return kf.webURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL, for state: UIControlState) { kf.setWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.webURLs") fileprivate var kf_webURLs: NSMutableDictionary { return kf.webURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURLs") fileprivate func kf_setWebURLs(_ URLs: NSMutableDictionary) { kf.setWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.backgroundWebURL` instead.", renamed: "kf.backgroundWebURL") public func kf_backgroundWebURL(for state: UIControlState) -> URL? { return kf.backgroundWebURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURL") fileprivate func kf_setBackgroundWebURL(_ url: URL, for state: UIControlState) { kf.setBackgroundWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundWebURLs") fileprivate var kf_backgroundWebURLs: NSMutableDictionary { return kf.backgroundWebURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURLs") fileprivate func kf_setBackgroundWebURLs(_ URLs: NSMutableDictionary) { kf.setBackgroundWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundImageTask") fileprivate var kf_backgroundImageTask: RetrieveImageTask? { return kf.backgroundImageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundImageTask") fileprivate func kf_setBackgroundImageTask(_ task: RetrieveImageTask?) { return kf.setBackgroundImageTask(task) } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 07340F15BACBA601736DBB2ABF1ABC35 /* GTMSessionFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = EF510C5C44749955F9CA9F68C93E84AA /* GTMSessionFetcherLogging.m */; }; 0E9CC28AC8E34FE8E1C87E933E04BC7A /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CB0604F87731544C696F0B592649AA8 /* ImageProcessor.swift */; }; 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = F264450BCD24170A6D1F447D15D3329E /* Timeline.swift */; }; 11AA8FD8D4B19499BFCB2D377A551C52 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; 179523942E7D1E3EB210EF05E2C7AE79 /* Kingfisher.h in Headers */ = {isa = PBXBuildFile; fileRef = 3454A48478AB5AB1DBCF0CA6F9FBAF27 /* Kingfisher.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2346245F9A93834CD80C223F0017FF4F /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1ED67707C258751E7888DAC2AB3D8501 /* GTMSessionFetcherLogging.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E5B4DD8EAADF645387F3252B34BE8FC /* GTMSessionFetcherLogging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 1F9B999DFAA1052294448B64C77434B1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; 20FFCB796689940613A141013D758B10 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CFBF738505191686DEB5C2AEF35C27F5 /* SwiftyJSON-dummy.m */; }; 2E5E570FFC49EF98550401421A243C0F /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2951BC25B1835D75AECC8B20A6E3DF8E /* CacheSerializer.swift */; }; 3159D7CAFD56B809F40CA3330DA10889 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; 33395912F2FFA355C4C36B7EDEAA3DA7 /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 799F802B9F667245AC0CB5CB447BFEBA /* ImageView+Kingfisher.swift */; }; 33A14E817C0FA585D5DA3A55E453299D /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC042492701A8DFA11553FF585008EF3 /* Image.swift */; }; 3414E1D9CB15149A296E16C45967B021 /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DA8B8454898A573AEE021BBCCCCD143 /* ImagePrefetcher.swift */; }; 342AE33215135AD56B73580012DC22AB /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89089346B32E549C5B99D39FA9ACA5BC /* AnimatedImageView.swift */; }; 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1A4B83783C220587D425BBBBD0444C2 /* TaskDelegate.swift */; }; 378B44CAA91C2106076668FDE72E1E02 /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A38F6A6EA5A8880D4DC2937F4AE7C97F /* KingfisherOptionsInfo.swift */; }; 4089E39F76F86466B8DDD39A1C1ABB6B /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA819FB7D60198C9D6AE90D5D053D425 /* Filter.swift */; }; 4E59744DDACFECB37D3531E504228AA1 /* AlamofireSwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 86A2747BB7F197C79A0FCE2C29D0B410 /* AlamofireSwiftyJSON-dummy.m */; }; 5068EA401BAAC807CB5699005DEF8E03 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C3E0CB87443BDB91ADEF4CE8C5C0C397 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 52A280AB4852FDE92DF09B5E79D5C2AA /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6A2442F555DBAE35E5F6E231833C844 /* Indicator.swift */; }; 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EE659DB710D9E62DD6109E00FC46206 /* Request.swift */; }; 541C5362289CC44D4F067D097F231250 /* GTMDefines.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BEADEDE363617FE082CB5F6973FA5B0 /* GTMDefines.h */; settings = {ATTRIBUTES = (Public, ); }; }; 59BE44195191D46A245AAB3F8B5BA4A4 /* AlamofireSwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66624E1C86E4CCD2A291EC8E8E7D3634 /* AlamofireSwiftyJSON.swift */; }; 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = AED0D9C7D5FD128D10ED1745822239BF /* DispatchQueue+Alamofire.swift */; }; 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 670AD4A083DB504909A6A05101A6CB4D /* ServerTrustPolicy.swift */; }; 64F31B70A6E5E6963518A01C285B435F /* GTMSessionFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 54B667E2B8DE34643E534A0D0915FF06 /* GTMSessionFetcher.m */; }; 65B56BD3DBC9B81BB008219D0BA735A9 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 013BA0684E637571DD07340A640F13CA /* Security.framework */; }; 6A375593407BC7937234B2B6A0811760 /* Kingfisher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8E3894F582965F5827889B1F4B1CB608 /* Kingfisher-dummy.m */; }; 6CD63E1564618B6213B98E0ABBC3127C /* ThreadHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE5BB80E5E84F419579A7001030E3265 /* ThreadHelper.swift */; }; 6DA770087D354CDCD3889CDAE7C4C698 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = B17BF2027EE9BFAB3C7CEEBEAAF58228 /* Box.swift */; }; 6DC7F9312F5A2D7036531D58527AC26F /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 510ECC66DCD1AA79705F4ABAF7D9E075 /* SwiftyJSON.framework */; }; 6EA6DFC4473A9B2DB6B8A42EA986BA5B /* GTMSessionFetcher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 542FE9CA3B7A965BA9F504EBD781BFD4 /* GTMSessionFetcher-dummy.m */; }; 7636F846675C9F4ED96E00C6C19A4890 /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B59802982DD964621F5DD86AF4E78F4 /* KingfisherManager.swift */; }; 77C5A81B67F4C3A2890826E534AF53DD /* AlamofireSwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D1A028287B84581187D3CDCD7FD46B04 /* AlamofireSwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2DFB26D4B25C9812B1FD794EFFEEE80 /* SessionDelegate.swift */; }; 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3AB5B801C205E4F90FFACA25BBC3E86 /* Result.swift */; }; 81E4B6988FF26F9249B79C6C8CC667B4 /* GoogleToolboxForMac-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 61CD56F3E99371C68F1F8737CCC9A538 /* GoogleToolboxForMac-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 86B7DA678C8705523C300947117C0706 /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AE73D882FCDED1B3A8E1CC8CC802BCE /* ImageTransition.swift */; }; 87C5C03722DEBE6F410B3C5B6460FE3C /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0E7C5B691EDA273ED6B83F0BEB9CED56 /* Alamofire.framework */; }; 87D4CADFC296262AF19DBE6F6D0188B4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; 8852FD9AFC242520924D98BE9C4E2477 /* GTMSessionFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = EBF49C23970297B78CFAFC66AD58AB9D /* GTMSessionFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8DA7E6883118CB3C8132B64D3D43AE0B /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8AB51ABDCA6B7ED9C3FA29D3AA4FEE5 /* Resource.swift */; }; 92136C6584624998D5005F46C70A628B /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F089943DCDE784E6E45EC5EEFD5FE392 /* CFNetwork.framework */; }; 95C69447F517DB81437EDE0003486963 /* GTMSessionFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 752644C15903325B219E9EB48AD16310 /* GTMSessionFetcherService.m */; }; 9C99E45B90BD95712D9878994BFC8B88 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = E151C2C3314986F6898291A407869ADF /* AFError.swift */; }; 9F826F893E86EB86591B637A1CE4B13A /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40EC4D2DE7D2830C7A648DBB48DA3850 /* String+MD5.swift */; }; A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 864714FA4CBEF3E0051C8CC002FBB4BB /* NetworkReachabilityManager.swift */; }; A5CE453D368326CCFE2ECA3034306EAA /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = A82B6FF091EBF87F734CD72D3028EF59 /* SwiftyJSON.swift */; }; A8F35D1EBAEF99D38F02A0B8CA5D8FBE /* Kingfisher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 0C8781363A3B93B1AA17A12E038BFCBB /* Kingfisher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 433044AEACC2C6281023025DE8694B42 /* Alamofire-dummy.m */; }; AB17FFF3EEFA547806EEA1923644C52E /* Pods-EZShopManager-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3027BDD9FF6088C9F5D585396DAE8416 /* Pods-EZShopManager-dummy.m */; }; AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7CB49B79B764E44245789F1BC117B93 /* SessionManager.swift */; }; B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90D10815AC332484EA70AF47C5876F85 /* MultipartFormData.swift */; }; BA64D4B770560972108CAE92C485D105 /* Pods-EZShopManager-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = C67D197CB86FBE72AC9B65FE95C0CBA9 /* Pods-EZShopManager-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B64078ACED8B96EC58AA8844BB776A35 /* Validation.swift */; }; BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B954FBDBAD38CB415660E2973C4347 /* ParameterEncoding.swift */; }; C9CC5ED97D29C6C3DE22B78A9AA2AD91 /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72CE5B481B5899E9DE1BD6F4D76A1C47 /* Kingfisher.swift */; }; CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = B02D9A3ABC1D9941E4272685206A8EE2 /* Response.swift */; }; D3F381B45ADFDDE51CA31F1E141236CA /* GTMSessionFetcher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 715425DD6DEA0F8531B84E140F4F543C /* GTMSessionFetcher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; DBFECCB0BBE3F11CC41A3C1A8C4879D3 /* GTMNSData+zlib.h in Headers */ = {isa = PBXBuildFile; fileRef = 5E3645A39A15A2C35C0131C34E2519B8 /* GTMNSData+zlib.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC6080C64C269628C3F5107BE87055E2 /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9D2709B402534B8C53A5BBA0532B6EE /* ImageDownloader.swift */; }; DF9559C3822E3C6119BE43E4EDFD7EEE /* GTMSessionFetcherService.h in Headers */ = {isa = PBXBuildFile; fileRef = B8808E784C3AA63685FB3CC93ACDDCB4 /* GTMSessionFetcherService.h */; settings = {ATTRIBUTES = (Public, ); }; }; EA816A580C3858934ED6FE92040C26DD /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED3314C314C4A6ACD833634F66ABF2F5 /* RequestModifier.swift */; }; EE89512E8D36E67CDC525DB9D5BBF5A7 /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91B7C9D8DAE50787741FDF8912EA6F30 /* UIButton+Kingfisher.swift */; }; EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F3B17AA7D37F03B2668C40A7491DED /* Notifications.swift */; }; F09EDD53B94234F5F8DAC4DCD5CD969E /* GTMSessionUploadFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B6EFE6550E981A67A7AFE9161D0B664 /* GTMSessionUploadFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; F0DA3F38ECCA723EF832E2F746C7CFF0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */; }; F4E294C07EE32FFCDCF7FF4D71D850BD /* GTMSessionUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 8B0018A18DB880FDF60353AC2072CA4B /* GTMSessionUploadFetcher.m */; }; F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = F65B70E08278184C061D250034691B2C /* ResponseSerialization.swift */; }; F7D889906DECB078EAAECB9D4A320E9C /* GTMNSData+zlib.m in Sources */ = {isa = PBXBuildFile; fileRef = 3EA255E453144C5791B02AE2C5DFFF9A /* GTMNSData+zlib.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 204BAAC36755DE60765F373FB26CDE44 /* Alamofire.swift */; }; F8E957950566622A3E4B61AACE8F0B4A /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = C78C24B8CDAB38B903D11D6452206EFA /* ImageCache.swift */; }; FAC3F3CAABA60EF76069431C5BB5032A /* GoogleToolboxForMac-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3A5C738006AA2EB8FCDD88E24785979A /* GoogleToolboxForMac-dummy.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 62BCF1C4255DEC22F6CB1E79332FED47 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 00103D6C821BE85971C563025527BA5D; remoteInfo = GoogleToolboxForMac; }; 70340C6869658F6ED9D2D2C9E8837698 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; 7F4A40413ED5FA7D86A70E9D42CA03D4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C052BEBFBD0AB5218CC64BA3450F6547; remoteInfo = GTMSessionFetcher; }; 81EA9E33260BDCB52F6B0504E8B20ECD /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 61E5C1379DC63FAC57AF48F891CFB123; remoteInfo = AlamofireSwiftyJSON; }; 9BB2B391009907F2870003C114B2F54E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C68748E71A3DDB40B0AAF4BC0A8F9030; remoteInfo = SwiftyJSON; }; 9FDAF5C6C834BA59530A0169BB8EB750 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; A1F10796BCCFE760190DE33893C9FF98 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C4944FEC314D1A66588651D006273ADE; remoteInfo = Kingfisher; }; F6814470266156FFDECCFBF764C454DA /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C68748E71A3DDB40B0AAF4BC0A8F9030; remoteInfo = SwiftyJSON; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ 00D5A7387737E6AD24709714E04865D6 /* AlamofireSwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AlamofireSwiftyJSON.framework; path = AlamofireSwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 013BA0684E637571DD07340A640F13CA /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 0518DEFE28C2EC662F1399AC90DA9711 /* SwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.xcconfig; sourceTree = ""; }; 0C2D266D9518BDA4A32A7A7BFED3EEFA /* Pods-EZShopManager-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-EZShopManager-frameworks.sh"; sourceTree = ""; }; 0C8781363A3B93B1AA17A12E038BFCBB /* Kingfisher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-umbrella.h"; sourceTree = ""; }; 0E7C5B691EDA273ED6B83F0BEB9CED56 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 10D340CAFDB7AA71ED436416CE0D666F /* GoogleToolboxForMac-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleToolboxForMac-prefix.pch"; sourceTree = ""; }; 1684905648A8947821C01ED37279C8BC /* GoogleToolboxForMac.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GoogleToolboxForMac.xcconfig; sourceTree = ""; }; 18F3B17AA7D37F03B2668C40A7491DED /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 19B352AF708D558295BE7F4881EA1A84 /* AlamofireSwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireSwiftyJSON-prefix.pch"; sourceTree = ""; }; 1AE73D882FCDED1B3A8E1CC8CC802BCE /* ImageTransition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageTransition.swift; path = Sources/ImageTransition.swift; sourceTree = ""; }; 1C2454D7A050107A3C42852452ED7856 /* FirebaseAnalytics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseAnalytics.framework; path = Frameworks/FirebaseAnalytics.framework; sourceTree = ""; }; 1DB24866D657FB2E3504CC1174AE1704 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 1EE659DB710D9E62DD6109E00FC46206 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 1F97FF0FC0AB44FE0CB7317443FAEC46 /* FirebaseStorage.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseStorage.framework; path = Frameworks/FirebaseStorage.framework; sourceTree = ""; }; 204BAAC36755DE60765F373FB26CDE44 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 2346245F9A93834CD80C223F0017FF4F /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; 2951BC25B1835D75AECC8B20A6E3DF8E /* CacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CacheSerializer.swift; path = Sources/CacheSerializer.swift; sourceTree = ""; }; 2B7D60DC70101423FDCE99A920709E79 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; 2E32920629A9F1BC65523CF16C7F9F4C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 301F1B1D0570093C5E651B91DB8DCBC6 /* Pods-EZShopManager.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-EZShopManager.debug.xcconfig"; sourceTree = ""; }; 3027BDD9FF6088C9F5D585396DAE8416 /* Pods-EZShopManager-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-EZShopManager-dummy.m"; sourceTree = ""; }; 3454A48478AB5AB1DBCF0CA6F9FBAF27 /* Kingfisher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Kingfisher.h; path = Sources/Kingfisher.h; sourceTree = ""; }; 3A5C738006AA2EB8FCDD88E24785979A /* GoogleToolboxForMac-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GoogleToolboxForMac-dummy.m"; sourceTree = ""; }; 3D3ABBE9A15D4FD576281AF8C30CDB2D /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 3EA255E453144C5791B02AE2C5DFFF9A /* GTMNSData+zlib.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "GTMNSData+zlib.m"; path = "Foundation/GTMNSData+zlib.m"; sourceTree = ""; }; 40EC4D2DE7D2830C7A648DBB48DA3850 /* String+MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+MD5.swift"; path = "Sources/String+MD5.swift"; sourceTree = ""; }; 433044AEACC2C6281023025DE8694B42 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; 4601379BA848940F91BA97AB97DE9399 /* Pods-EZShopManager-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-EZShopManager-acknowledgements.markdown"; sourceTree = ""; }; 471644F2EBD89CC3F6BD52A42571A336 /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = SwiftyJSON.modulemap; sourceTree = ""; }; 4B6EFE6550E981A67A7AFE9161D0B664 /* GTMSessionUploadFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionUploadFetcher.h; path = Source/GTMSessionUploadFetcher.h; sourceTree = ""; }; 4DA8B8454898A573AEE021BBCCCCD143 /* ImagePrefetcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/ImagePrefetcher.swift; sourceTree = ""; }; 510ECC66DCD1AA79705F4ABAF7D9E075 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 52595D17C5C7F6FB2F98D61360FC91E1 /* Kingfisher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Kingfisher.modulemap; sourceTree = ""; }; 541A1FF12AF88165C46DA11AA0A6EF2B /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; 542FE9CA3B7A965BA9F504EBD781BFD4 /* GTMSessionFetcher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GTMSessionFetcher-dummy.m"; sourceTree = ""; }; 54B667E2B8DE34643E534A0D0915FF06 /* GTMSessionFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcher.m; path = Source/GTMSessionFetcher.m; sourceTree = ""; }; 5ABAE808D6B81FBFC6E34B88A4EE0895 /* Firebase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Firebase.h; path = Core/Sources/Firebase.h; sourceTree = ""; }; 5AF9063EF9CE2167E828E653DDD6D6AA /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5CF4AD475F0C4504BC6726C41015A388 /* Pods-EZShopManager-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-EZShopManager-acknowledgements.plist"; sourceTree = ""; }; 5E3645A39A15A2C35C0131C34E2519B8 /* GTMNSData+zlib.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "GTMNSData+zlib.h"; path = "Foundation/GTMNSData+zlib.h"; sourceTree = ""; }; 61360C3650FB1746237E013D6EB7A390 /* FirebaseInstanceID.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseInstanceID.framework; path = Frameworks/FirebaseInstanceID.framework; sourceTree = ""; }; 61CD56F3E99371C68F1F8737CCC9A538 /* GoogleToolboxForMac-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleToolboxForMac-umbrella.h"; sourceTree = ""; }; 66624E1C86E4CCD2A291EC8E8E7D3634 /* AlamofireSwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireSwiftyJSON.swift; path = Source/AlamofireSwiftyJSON.swift; sourceTree = ""; }; 670AD4A083DB504909A6A05101A6CB4D /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; 6D16541A098F54C50DD73A542B46865F /* Kingfisher.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.xcconfig; sourceTree = ""; }; 715425DD6DEA0F8531B84E140F4F543C /* GTMSessionFetcher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-umbrella.h"; sourceTree = ""; }; 72CE5B481B5899E9DE1BD6F4D76A1C47 /* Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kingfisher.swift; path = Sources/Kingfisher.swift; sourceTree = ""; }; 752644C15903325B219E9EB48AD16310 /* GTMSessionFetcherService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherService.m; path = Source/GTMSessionFetcherService.m; sourceTree = ""; }; 799F802B9F667245AC0CB5CB447BFEBA /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ImageView+Kingfisher.swift"; path = "Sources/ImageView+Kingfisher.swift"; sourceTree = ""; }; 7E20F3BDA6E05BBE04E83DD3C9AB2DB9 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 82C6F272A98A0CB844ABBCB48AF749F5 /* AlamofireSwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = AlamofireSwiftyJSON.modulemap; sourceTree = ""; }; 864714FA4CBEF3E0051C8CC002FBB4BB /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; 86A2747BB7F197C79A0FCE2C29D0B410 /* AlamofireSwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AlamofireSwiftyJSON-dummy.m"; sourceTree = ""; }; 89089346B32E549C5B99D39FA9ACA5BC /* AnimatedImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedImageView.swift; path = Sources/AnimatedImageView.swift; sourceTree = ""; }; 8B0018A18DB880FDF60353AC2072CA4B /* GTMSessionUploadFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionUploadFetcher.m; path = Source/GTMSessionUploadFetcher.m; sourceTree = ""; }; 8E3894F582965F5827889B1F4B1CB608 /* Kingfisher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kingfisher-dummy.m"; sourceTree = ""; }; 90D10815AC332484EA70AF47C5876F85 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; 911D22B4BEA68B1AE71AAAD314F1E570 /* Pods-EZShopManager.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-EZShopManager.modulemap"; sourceTree = ""; }; 91B7C9D8DAE50787741FDF8912EA6F30 /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Kingfisher.swift"; path = "Sources/UIButton+Kingfisher.swift"; sourceTree = ""; }; 930F2905CF29770C811B5CB6FCB45493 /* AlamofireSwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AlamofireSwiftyJSON.xcconfig; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 9990EDE1244738A11AF45C3F06062797 /* GoogleToolboxForMac.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GoogleToolboxForMac.framework; path = GoogleToolboxForMac.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9B59802982DD964621F5DD86AF4E78F4 /* KingfisherManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherManager.swift; path = Sources/KingfisherManager.swift; sourceTree = ""; }; 9BEADEDE363617FE082CB5F6973FA5B0 /* GTMDefines.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = GTMDefines.h; sourceTree = ""; }; 9CB0604F87731544C696F0B592649AA8 /* ImageProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProcessor.swift; path = Sources/ImageProcessor.swift; sourceTree = ""; }; 9E5B4DD8EAADF645387F3252B34BE8FC /* GTMSessionFetcherLogging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherLogging.h; path = Source/GTMSessionFetcherLogging.h; sourceTree = ""; }; A1A4B83783C220587D425BBBBD0444C2 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; A377FDA04AE20A00A6BDE1C3CFF954D1 /* Kingfisher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kingfisher.framework; path = Kingfisher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A38F6A6EA5A8880D4DC2937F4AE7C97F /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherOptionsInfo.swift; path = Sources/KingfisherOptionsInfo.swift; sourceTree = ""; }; A70D30216879C07B8EC7E7BE7F1319BF /* Kingfisher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-prefix.pch"; sourceTree = ""; }; A82B6FF091EBF87F734CD72D3028EF59 /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON.swift; sourceTree = ""; }; A9D2709B402534B8C53A5BBA0532B6EE /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Sources/ImageDownloader.swift; sourceTree = ""; }; AB2CB244EEC2B049C3CF730578C20B96 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; AC6291BAAE2E0FC64C117230EFCC1AB2 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; AED0D9C7D5FD128D10ED1745822239BF /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; B02D9A3ABC1D9941E4272685206A8EE2 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; B17BF2027EE9BFAB3C7CEEBEAAF58228 /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; B2D4CDE48F12B12D6A20022BB984F359 /* FirebaseCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseCore.framework; path = Frameworks/FirebaseCore.framework; sourceTree = ""; }; B3AB5B801C205E4F90FFACA25BBC3E86 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; B64078ACED8B96EC58AA8844BB776A35 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; B7368DF07CF48904376011446E0A2236 /* FirebaseDatabase.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseDatabase.framework; path = Frameworks/FirebaseDatabase.framework; sourceTree = ""; }; B8808E784C3AA63685FB3CC93ACDDCB4 /* GTMSessionFetcherService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherService.h; path = Source/GTMSessionFetcherService.h; sourceTree = ""; }; B8E6ECE2A0D0C4D9EAD3039AD267BDAD /* GTMSessionFetcher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GTMSessionFetcher.framework; path = GTMSessionFetcher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; BE5BB80E5E84F419579A7001030E3265 /* ThreadHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ThreadHelper.swift; path = Sources/ThreadHelper.swift; sourceTree = ""; }; C3E0CB87443BDB91ADEF4CE8C5C0C397 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; C67D197CB86FBE72AC9B65FE95C0CBA9 /* Pods-EZShopManager-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-EZShopManager-umbrella.h"; sourceTree = ""; }; C78C24B8CDAB38B903D11D6452206EFA /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Sources/ImageCache.swift; sourceTree = ""; }; C7CB49B79B764E44245789F1BC117B93 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; CA819FB7D60198C9D6AE90D5D053D425 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Filter.swift; sourceTree = ""; }; CD0020A47FBEB01AEDFAA556EE67D8E3 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; CFBF738505191686DEB5C2AEF35C27F5 /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; CFC8A7D8E125D4AEBC9096DB10DFA3C2 /* GTMSessionFetcher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-prefix.pch"; sourceTree = ""; }; D11DA8A1168B37BECAE0E745400611B6 /* GTMSessionFetcher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = GTMSessionFetcher.modulemap; sourceTree = ""; }; D1A028287B84581187D3CDCD7FD46B04 /* AlamofireSwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireSwiftyJSON-umbrella.h"; sourceTree = ""; }; D30AEF2A9C694D40741B41A7D86F389C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; D6A2442F555DBAE35E5F6E231833C844 /* Indicator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Indicator.swift; path = Sources/Indicator.swift; sourceTree = ""; }; D8092F6C6AB8BEA23A525ABCF6B6CBEF /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; E151C2C3314986F6898291A407869ADF /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; E2B0C304409DFC4809996F2A1FD3D11D /* GoogleToolboxForMac.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = GoogleToolboxForMac.modulemap; sourceTree = ""; }; E2DFB26D4B25C9812B1FD794EFFEEE80 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; E3A7EF587F364B67250ADC8FC971E415 /* Pods_EZShopManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_EZShopManager.framework; path = "Pods-EZShopManager.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; E4B954FBDBAD38CB415660E2973C4347 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; E9CFDE2136F0535D9CDE3BC3496AC9F8 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; EBF49C23970297B78CFAFC66AD58AB9D /* GTMSessionFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcher.h; path = Source/GTMSessionFetcher.h; sourceTree = ""; }; ECE9B6739B9B137C500ABB6547B4E8D4 /* GTMSessionFetcher.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GTMSessionFetcher.xcconfig; sourceTree = ""; }; ED3314C314C4A6ACD833634F66ABF2F5 /* RequestModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestModifier.swift; path = Sources/RequestModifier.swift; sourceTree = ""; }; EF510C5C44749955F9CA9F68C93E84AA /* GTMSessionFetcherLogging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherLogging.m; path = Source/GTMSessionFetcherLogging.m; sourceTree = ""; }; F089943DCDE784E6E45EC5EEFD5FE392 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; F1614E05B00DB6E549CDC107ACBCA5E7 /* Pods-EZShopManager.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-EZShopManager.release.xcconfig"; sourceTree = ""; }; F264450BCD24170A6D1F447D15D3329E /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; F65B70E08278184C061D250034691B2C /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; F8AB51ABDCA6B7ED9C3FA29D3AA4FEE5 /* Resource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resource.swift; path = Sources/Resource.swift; sourceTree = ""; }; FC042492701A8DFA11553FF585008EF3 /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Image.swift; sourceTree = ""; }; FD991F726A8E269ADAE7FAB183241D12 /* Pods-EZShopManager-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-EZShopManager-resources.sh"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 229003D8AA2FC24D450F02A58E1EA5D2 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 87C5C03722DEBE6F410B3C5B6460FE3C /* Alamofire.framework in Frameworks */, F0DA3F38ECCA723EF832E2F746C7CFF0 /* Foundation.framework in Frameworks */, 6DC7F9312F5A2D7036531D58527AC26F /* SwiftyJSON.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 6AE88E96161DE195EAAF0A3B6375EA50 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1F9B999DFAA1052294448B64C77434B1 /* Foundation.framework in Frameworks */, 65B56BD3DBC9B81BB008219D0BA735A9 /* Security.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 8DD06B625DFB302A853551293B0AB0B4 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 87D4CADFC296262AF19DBE6F6D0188B4 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; AEF8FFD8472A5F0322679DE200DF38DE /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 11AA8FD8D4B19499BFCB2D377A551C52 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; ED03E5917B811BACFE75189AE0C2A469 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 92136C6584624998D5005F46C70A628B /* CFNetwork.framework in Frameworks */, 9C99E45B90BD95712D9878994BFC8B88 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; F9BC43EEAF05BCB201B3D28C244AA7E1 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 3159D7CAFD56B809F40CA3330DA10889 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 027836C9E951F708F1B83AA9D13BA619 /* Targets Support Files */ = { isa = PBXGroup; children = ( 7F59B93592B0C78E525B8520D853B7C2 /* Pods-EZShopManager */, ); name = "Targets Support Files"; sourceTree = ""; }; 2BF17E0CC4DC53C4F3E390F5282C741C /* FirebaseInstanceID */ = { isa = PBXGroup; children = ( 78CD87E87C568688696E62B14FF0EFD1 /* Frameworks */, ); name = FirebaseInstanceID; path = FirebaseInstanceID; sourceTree = ""; }; 3696F4AE67C09691B728CA49923FD277 /* Frameworks */ = { isa = PBXGroup; children = ( B2D4CDE48F12B12D6A20022BB984F359 /* FirebaseCore.framework */, ); name = Frameworks; sourceTree = ""; }; 44BC261794EB78C43C44250172B5BCD3 /* Defines */ = { isa = PBXGroup; children = ( 9BEADEDE363617FE082CB5F6973FA5B0 /* GTMDefines.h */, ); name = Defines; sourceTree = ""; }; 45DC47518677BAF0EAB21D5538309ABB /* Core */ = { isa = PBXGroup; children = ( 5ABAE808D6B81FBFC6E34B88A4EE0895 /* Firebase.h */, ); name = Core; sourceTree = ""; }; 527452C6246B7E89BD90D04E1191EB2E /* FirebaseAnalytics */ = { isa = PBXGroup; children = ( 761EC5CB9DEE9E44A33EBEC78223A3F9 /* Frameworks */, ); name = FirebaseAnalytics; path = FirebaseAnalytics; sourceTree = ""; }; 578C591AF4A63007B04E92825F981019 /* Support Files */ = { isa = PBXGroup; children = ( AC6291BAAE2E0FC64C117230EFCC1AB2 /* Alamofire.modulemap */, AB2CB244EEC2B049C3CF730578C20B96 /* Alamofire.xcconfig */, 433044AEACC2C6281023025DE8694B42 /* Alamofire-dummy.m */, 541A1FF12AF88165C46DA11AA0A6EF2B /* Alamofire-prefix.pch */, 2346245F9A93834CD80C223F0017FF4F /* Alamofire-umbrella.h */, 2E32920629A9F1BC65523CF16C7F9F4C /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/Alamofire"; sourceTree = ""; }; 58EB6FCE3B2C73879E5C7EBB29980233 /* Kingfisher */ = { isa = PBXGroup; children = ( 89089346B32E549C5B99D39FA9ACA5BC /* AnimatedImageView.swift */, B17BF2027EE9BFAB3C7CEEBEAAF58228 /* Box.swift */, 2951BC25B1835D75AECC8B20A6E3DF8E /* CacheSerializer.swift */, CA819FB7D60198C9D6AE90D5D053D425 /* Filter.swift */, FC042492701A8DFA11553FF585008EF3 /* Image.swift */, C78C24B8CDAB38B903D11D6452206EFA /* ImageCache.swift */, A9D2709B402534B8C53A5BBA0532B6EE /* ImageDownloader.swift */, 4DA8B8454898A573AEE021BBCCCCD143 /* ImagePrefetcher.swift */, 9CB0604F87731544C696F0B592649AA8 /* ImageProcessor.swift */, 1AE73D882FCDED1B3A8E1CC8CC802BCE /* ImageTransition.swift */, 799F802B9F667245AC0CB5CB447BFEBA /* ImageView+Kingfisher.swift */, D6A2442F555DBAE35E5F6E231833C844 /* Indicator.swift */, 3454A48478AB5AB1DBCF0CA6F9FBAF27 /* Kingfisher.h */, 72CE5B481B5899E9DE1BD6F4D76A1C47 /* Kingfisher.swift */, 9B59802982DD964621F5DD86AF4E78F4 /* KingfisherManager.swift */, A38F6A6EA5A8880D4DC2937F4AE7C97F /* KingfisherOptionsInfo.swift */, ED3314C314C4A6ACD833634F66ABF2F5 /* RequestModifier.swift */, F8AB51ABDCA6B7ED9C3FA29D3AA4FEE5 /* Resource.swift */, 40EC4D2DE7D2830C7A648DBB48DA3850 /* String+MD5.swift */, BE5BB80E5E84F419579A7001030E3265 /* ThreadHelper.swift */, 91B7C9D8DAE50787741FDF8912EA6F30 /* UIButton+Kingfisher.swift */, F27EBA0EACA79D6B8BBB1616E48E6CD9 /* Support Files */, ); name = Kingfisher; path = Kingfisher; sourceTree = ""; }; 69D4B092CE2277D085652F08EF34DFDE /* Support Files */ = { isa = PBXGroup; children = ( D11DA8A1168B37BECAE0E745400611B6 /* GTMSessionFetcher.modulemap */, ECE9B6739B9B137C500ABB6547B4E8D4 /* GTMSessionFetcher.xcconfig */, 542FE9CA3B7A965BA9F504EBD781BFD4 /* GTMSessionFetcher-dummy.m */, CFC8A7D8E125D4AEBC9096DB10DFA3C2 /* GTMSessionFetcher-prefix.pch */, 715425DD6DEA0F8531B84E140F4F543C /* GTMSessionFetcher-umbrella.h */, 3D3ABBE9A15D4FD576281AF8C30CDB2D /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/GTMSessionFetcher"; sourceTree = ""; }; 6DBB7A7048260645677A612CACC8B1AA /* AlamofireSwiftyJSON */ = { isa = PBXGroup; children = ( 66624E1C86E4CCD2A291EC8E8E7D3634 /* AlamofireSwiftyJSON.swift */, D89D2AF3652F0441DCF930CECD0A6EA9 /* Support Files */, ); name = AlamofireSwiftyJSON; path = AlamofireSwiftyJSON; sourceTree = ""; }; 70A02CFB6624B6E5E29F6393273BAA1B /* Support Files */ = { isa = PBXGroup; children = ( E2B0C304409DFC4809996F2A1FD3D11D /* GoogleToolboxForMac.modulemap */, 1684905648A8947821C01ED37279C8BC /* GoogleToolboxForMac.xcconfig */, 3A5C738006AA2EB8FCDD88E24785979A /* GoogleToolboxForMac-dummy.m */, 10D340CAFDB7AA71ED436416CE0D666F /* GoogleToolboxForMac-prefix.pch */, 61CD56F3E99371C68F1F8737CCC9A538 /* GoogleToolboxForMac-umbrella.h */, CD0020A47FBEB01AEDFAA556EE67D8E3 /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/GoogleToolboxForMac"; sourceTree = ""; }; 761EC5CB9DEE9E44A33EBEC78223A3F9 /* Frameworks */ = { isa = PBXGroup; children = ( 1C2454D7A050107A3C42852452ED7856 /* FirebaseAnalytics.framework */, ); name = Frameworks; sourceTree = ""; }; 78CD87E87C568688696E62B14FF0EFD1 /* Frameworks */ = { isa = PBXGroup; children = ( 61360C3650FB1746237E013D6EB7A390 /* FirebaseInstanceID.framework */, ); name = Frameworks; sourceTree = ""; }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, CCB9F15D6A5617D99FA790F6C9D72582 /* Frameworks */, FEE279AD5F1DABF29252A7BD5D2C0D2E /* Pods */, C0F4433F1A7FB3CDF46BDFB7645C45C2 /* Products */, 027836C9E951F708F1B83AA9D13BA619 /* Targets Support Files */, ); sourceTree = ""; }; 7F59B93592B0C78E525B8520D853B7C2 /* Pods-EZShopManager */ = { isa = PBXGroup; children = ( 1DB24866D657FB2E3504CC1174AE1704 /* Info.plist */, 911D22B4BEA68B1AE71AAAD314F1E570 /* Pods-EZShopManager.modulemap */, 4601379BA848940F91BA97AB97DE9399 /* Pods-EZShopManager-acknowledgements.markdown */, 5CF4AD475F0C4504BC6726C41015A388 /* Pods-EZShopManager-acknowledgements.plist */, 3027BDD9FF6088C9F5D585396DAE8416 /* Pods-EZShopManager-dummy.m */, 0C2D266D9518BDA4A32A7A7BFED3EEFA /* Pods-EZShopManager-frameworks.sh */, FD991F726A8E269ADAE7FAB183241D12 /* Pods-EZShopManager-resources.sh */, C67D197CB86FBE72AC9B65FE95C0CBA9 /* Pods-EZShopManager-umbrella.h */, 301F1B1D0570093C5E651B91DB8DCBC6 /* Pods-EZShopManager.debug.xcconfig */, F1614E05B00DB6E549CDC107ACBCA5E7 /* Pods-EZShopManager.release.xcconfig */, ); name = "Pods-EZShopManager"; path = "Target Support Files/Pods-EZShopManager"; sourceTree = ""; }; 820F647CE40C707B3D03E0135E57E22A /* iOS */ = { isa = PBXGroup; children = ( F089943DCDE784E6E45EC5EEFD5FE392 /* CFNetwork.framework */, 026D3F072BCAD5455E6E0BA5FBA0F738 /* Foundation.framework */, 013BA0684E637571DD07340A640F13CA /* Security.framework */, ); name = iOS; sourceTree = ""; }; 8903A526304F97EF5CC9FA2F1D454C2C /* SwiftyJSON */ = { isa = PBXGroup; children = ( A82B6FF091EBF87F734CD72D3028EF59 /* SwiftyJSON.swift */, BC8D58F84C45CC1EF277355833A595C5 /* Support Files */, ); name = SwiftyJSON; path = SwiftyJSON; sourceTree = ""; }; 9190EFFA152186DFB39843E250B0470B /* Alamofire */ = { isa = PBXGroup; children = ( E151C2C3314986F6898291A407869ADF /* AFError.swift */, 204BAAC36755DE60765F373FB26CDE44 /* Alamofire.swift */, AED0D9C7D5FD128D10ED1745822239BF /* DispatchQueue+Alamofire.swift */, 90D10815AC332484EA70AF47C5876F85 /* MultipartFormData.swift */, 864714FA4CBEF3E0051C8CC002FBB4BB /* NetworkReachabilityManager.swift */, 18F3B17AA7D37F03B2668C40A7491DED /* Notifications.swift */, E4B954FBDBAD38CB415660E2973C4347 /* ParameterEncoding.swift */, 1EE659DB710D9E62DD6109E00FC46206 /* Request.swift */, B02D9A3ABC1D9941E4272685206A8EE2 /* Response.swift */, F65B70E08278184C061D250034691B2C /* ResponseSerialization.swift */, B3AB5B801C205E4F90FFACA25BBC3E86 /* Result.swift */, 670AD4A083DB504909A6A05101A6CB4D /* ServerTrustPolicy.swift */, E2DFB26D4B25C9812B1FD794EFFEEE80 /* SessionDelegate.swift */, C7CB49B79B764E44245789F1BC117B93 /* SessionManager.swift */, A1A4B83783C220587D425BBBBD0444C2 /* TaskDelegate.swift */, F264450BCD24170A6D1F447D15D3329E /* Timeline.swift */, B64078ACED8B96EC58AA8844BB776A35 /* Validation.swift */, 578C591AF4A63007B04E92825F981019 /* Support Files */, ); name = Alamofire; path = Alamofire; sourceTree = ""; }; 9AD35424036843577173F094001D4D1A /* Firebase */ = { isa = PBXGroup; children = ( 45DC47518677BAF0EAB21D5538309ABB /* Core */, ); name = Firebase; path = Firebase; sourceTree = ""; }; 9DBB5012CBDB4CE7F6AAF351900EF233 /* Core */ = { isa = PBXGroup; children = ( EBF49C23970297B78CFAFC66AD58AB9D /* GTMSessionFetcher.h */, 54B667E2B8DE34643E534A0D0915FF06 /* GTMSessionFetcher.m */, 9E5B4DD8EAADF645387F3252B34BE8FC /* GTMSessionFetcherLogging.h */, EF510C5C44749955F9CA9F68C93E84AA /* GTMSessionFetcherLogging.m */, B8808E784C3AA63685FB3CC93ACDDCB4 /* GTMSessionFetcherService.h */, 752644C15903325B219E9EB48AD16310 /* GTMSessionFetcherService.m */, 4B6EFE6550E981A67A7AFE9161D0B664 /* GTMSessionUploadFetcher.h */, 8B0018A18DB880FDF60353AC2072CA4B /* GTMSessionUploadFetcher.m */, ); name = Core; sourceTree = ""; }; A89CF264274041975E507371ACC63A36 /* GTMSessionFetcher */ = { isa = PBXGroup; children = ( 9DBB5012CBDB4CE7F6AAF351900EF233 /* Core */, 69D4B092CE2277D085652F08EF34DFDE /* Support Files */, ); name = GTMSessionFetcher; path = GTMSessionFetcher; sourceTree = ""; }; B255382970CC29F1C9EA3F3E759CF500 /* GoogleToolboxForMac */ = { isa = PBXGroup; children = ( 44BC261794EB78C43C44250172B5BCD3 /* Defines */, C8517F2F4154E974C01EF976BF5FDDF1 /* NSData+zlib */, 70A02CFB6624B6E5E29F6393273BAA1B /* Support Files */, ); name = GoogleToolboxForMac; path = GoogleToolboxForMac; sourceTree = ""; }; B74D9DA4B06980A8FD7628A905D3DE08 /* FirebaseCore */ = { isa = PBXGroup; children = ( 3696F4AE67C09691B728CA49923FD277 /* Frameworks */, ); name = FirebaseCore; path = FirebaseCore; sourceTree = ""; }; BC8D58F84C45CC1EF277355833A595C5 /* Support Files */ = { isa = PBXGroup; children = ( E9CFDE2136F0535D9CDE3BC3496AC9F8 /* Info.plist */, 471644F2EBD89CC3F6BD52A42571A336 /* SwiftyJSON.modulemap */, 0518DEFE28C2EC662F1399AC90DA9711 /* SwiftyJSON.xcconfig */, CFBF738505191686DEB5C2AEF35C27F5 /* SwiftyJSON-dummy.m */, 2B7D60DC70101423FDCE99A920709E79 /* SwiftyJSON-prefix.pch */, C3E0CB87443BDB91ADEF4CE8C5C0C397 /* SwiftyJSON-umbrella.h */, ); name = "Support Files"; path = "../Target Support Files/SwiftyJSON"; sourceTree = ""; }; C0F4433F1A7FB3CDF46BDFB7645C45C2 /* Products */ = { isa = PBXGroup; children = ( D8092F6C6AB8BEA23A525ABCF6B6CBEF /* Alamofire.framework */, 00D5A7387737E6AD24709714E04865D6 /* AlamofireSwiftyJSON.framework */, 9990EDE1244738A11AF45C3F06062797 /* GoogleToolboxForMac.framework */, B8E6ECE2A0D0C4D9EAD3039AD267BDAD /* GTMSessionFetcher.framework */, A377FDA04AE20A00A6BDE1C3CFF954D1 /* Kingfisher.framework */, E3A7EF587F364B67250ADC8FC971E415 /* Pods_EZShopManager.framework */, 7E20F3BDA6E05BBE04E83DD3C9AB2DB9 /* SwiftyJSON.framework */, ); name = Products; sourceTree = ""; }; C8517F2F4154E974C01EF976BF5FDDF1 /* NSData+zlib */ = { isa = PBXGroup; children = ( 5E3645A39A15A2C35C0131C34E2519B8 /* GTMNSData+zlib.h */, 3EA255E453144C5791B02AE2C5DFFF9A /* GTMNSData+zlib.m */, ); name = "NSData+zlib"; sourceTree = ""; }; CC2734255B9BA6EF08E4C7F154728682 /* Frameworks */ = { isa = PBXGroup; children = ( 1F97FF0FC0AB44FE0CB7317443FAEC46 /* FirebaseStorage.framework */, ); name = Frameworks; sourceTree = ""; }; CCB9F15D6A5617D99FA790F6C9D72582 /* Frameworks */ = { isa = PBXGroup; children = ( 0E7C5B691EDA273ED6B83F0BEB9CED56 /* Alamofire.framework */, 510ECC66DCD1AA79705F4ABAF7D9E075 /* SwiftyJSON.framework */, 820F647CE40C707B3D03E0135E57E22A /* iOS */, ); name = Frameworks; sourceTree = ""; }; D0E09A388F7C46D007EC151815FEB9AC /* FirebaseDatabase */ = { isa = PBXGroup; children = ( F34BBFE4EEB40F8454ED0157B232B46D /* Frameworks */, ); name = FirebaseDatabase; path = FirebaseDatabase; sourceTree = ""; }; D89D2AF3652F0441DCF930CECD0A6EA9 /* Support Files */ = { isa = PBXGroup; children = ( 82C6F272A98A0CB844ABBCB48AF749F5 /* AlamofireSwiftyJSON.modulemap */, 930F2905CF29770C811B5CB6FCB45493 /* AlamofireSwiftyJSON.xcconfig */, 86A2747BB7F197C79A0FCE2C29D0B410 /* AlamofireSwiftyJSON-dummy.m */, 19B352AF708D558295BE7F4881EA1A84 /* AlamofireSwiftyJSON-prefix.pch */, D1A028287B84581187D3CDCD7FD46B04 /* AlamofireSwiftyJSON-umbrella.h */, 5AF9063EF9CE2167E828E653DDD6D6AA /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/AlamofireSwiftyJSON"; sourceTree = ""; }; DDE1C1EADAB1AF964799C01911A2D391 /* FirebaseStorage */ = { isa = PBXGroup; children = ( CC2734255B9BA6EF08E4C7F154728682 /* Frameworks */, ); name = FirebaseStorage; path = FirebaseStorage; sourceTree = ""; }; F27EBA0EACA79D6B8BBB1616E48E6CD9 /* Support Files */ = { isa = PBXGroup; children = ( D30AEF2A9C694D40741B41A7D86F389C /* Info.plist */, 52595D17C5C7F6FB2F98D61360FC91E1 /* Kingfisher.modulemap */, 6D16541A098F54C50DD73A542B46865F /* Kingfisher.xcconfig */, 8E3894F582965F5827889B1F4B1CB608 /* Kingfisher-dummy.m */, A70D30216879C07B8EC7E7BE7F1319BF /* Kingfisher-prefix.pch */, 0C8781363A3B93B1AA17A12E038BFCBB /* Kingfisher-umbrella.h */, ); name = "Support Files"; path = "../Target Support Files/Kingfisher"; sourceTree = ""; }; F34BBFE4EEB40F8454ED0157B232B46D /* Frameworks */ = { isa = PBXGroup; children = ( B7368DF07CF48904376011446E0A2236 /* FirebaseDatabase.framework */, ); name = Frameworks; sourceTree = ""; }; FEE279AD5F1DABF29252A7BD5D2C0D2E /* Pods */ = { isa = PBXGroup; children = ( 9190EFFA152186DFB39843E250B0470B /* Alamofire */, 6DBB7A7048260645677A612CACC8B1AA /* AlamofireSwiftyJSON */, 9AD35424036843577173F094001D4D1A /* Firebase */, 527452C6246B7E89BD90D04E1191EB2E /* FirebaseAnalytics */, B74D9DA4B06980A8FD7628A905D3DE08 /* FirebaseCore */, D0E09A388F7C46D007EC151815FEB9AC /* FirebaseDatabase */, 2BF17E0CC4DC53C4F3E390F5282C741C /* FirebaseInstanceID */, DDE1C1EADAB1AF964799C01911A2D391 /* FirebaseStorage */, B255382970CC29F1C9EA3F3E759CF500 /* GoogleToolboxForMac */, A89CF264274041975E507371ACC63A36 /* GTMSessionFetcher */, 58EB6FCE3B2C73879E5C7EBB29980233 /* Kingfisher */, 8903A526304F97EF5CC9FA2F1D454C2C /* SwiftyJSON */, ); name = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 0F94B6BFE5A6242FBBB0BE3D27F7CEE9 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( A8F35D1EBAEF99D38F02A0B8CA5D8FBE /* Kingfisher-umbrella.h in Headers */, 179523942E7D1E3EB210EF05E2C7AE79 /* Kingfisher.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 3D3CACB7864BED7F83E4ADEDE0D6EE4D /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 5068EA401BAAC807CB5699005DEF8E03 /* SwiftyJSON-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 8046BB4149567CCD2182A4ABF1B0538B /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( BA64D4B770560972108CAE92C485D105 /* Pods-EZShopManager-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 82D993B88C10479096F17ADDEAB85D94 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( D3F381B45ADFDDE51CA31F1E141236CA /* GTMSessionFetcher-umbrella.h in Headers */, 8852FD9AFC242520924D98BE9C4E2477 /* GTMSessionFetcher.h in Headers */, 1ED67707C258751E7888DAC2AB3D8501 /* GTMSessionFetcherLogging.h in Headers */, DF9559C3822E3C6119BE43E4EDFD7EEE /* GTMSessionFetcherService.h in Headers */, F09EDD53B94234F5F8DAC4DCD5CD969E /* GTMSessionUploadFetcher.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; D5C9442E4D341BC38656D3EF6CE7F323 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 77C5A81B67F4C3A2890826E534AF53DD /* AlamofireSwiftyJSON-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; FDA600FDC48ED17BA03DA2D85D4EDA97 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 81E4B6988FF26F9249B79C6C8CC667B4 /* GoogleToolboxForMac-umbrella.h in Headers */, 541C5362289CC44D4F067D097F231250 /* GTMDefines.h in Headers */, DBFECCB0BBE3F11CC41A3C1A8C4879D3 /* GTMNSData+zlib.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 00103D6C821BE85971C563025527BA5D /* GoogleToolboxForMac */ = { isa = PBXNativeTarget; buildConfigurationList = C43D9CA5106C6CCEF973B7EDF833947B /* Build configuration list for PBXNativeTarget "GoogleToolboxForMac" */; buildPhases = ( 63D7DA997053F6B5D01DE8CB5817CB51 /* Sources */, F9BC43EEAF05BCB201B3D28C244AA7E1 /* Frameworks */, FDA600FDC48ED17BA03DA2D85D4EDA97 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = GoogleToolboxForMac; productName = GoogleToolboxForMac; productReference = 9990EDE1244738A11AF45C3F06062797 /* GoogleToolboxForMac.framework */; productType = "com.apple.product-type.framework"; }; 488E06E9F0251ABD57E7AA6A8F9F254C /* Pods-EZShopManager */ = { isa = PBXNativeTarget; buildConfigurationList = 55109BCFA5F87C7951E47D893E2980C0 /* Build configuration list for PBXNativeTarget "Pods-EZShopManager" */; buildPhases = ( C4BB6AC2523DA5CF65D0331AC3D873D6 /* Sources */, AEF8FFD8472A5F0322679DE200DF38DE /* Frameworks */, 8046BB4149567CCD2182A4ABF1B0538B /* Headers */, ); buildRules = ( ); dependencies = ( CEAC232D04E69798D57D57CE135061E7 /* PBXTargetDependency */, 1CC714863471D79952C5622111205275 /* PBXTargetDependency */, 950BA7BD27E10495AAA3A628EA521C47 /* PBXTargetDependency */, 5FCE831A2ED384DE4A61C4D51177618D /* PBXTargetDependency */, 7C927C0C2AF8F51829D2121B777487E0 /* PBXTargetDependency */, 1FCB5A84D8DB2AEB2422D2713CFA5780 /* PBXTargetDependency */, ); name = "Pods-EZShopManager"; productName = "Pods-EZShopManager"; productReference = E3A7EF587F364B67250ADC8FC971E415 /* Pods_EZShopManager.framework */; productType = "com.apple.product-type.framework"; }; 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */ = { isa = PBXNativeTarget; buildConfigurationList = DCCE50C77ACBD367E99B830BA1F92670 /* Build configuration list for PBXNativeTarget "AlamofireSwiftyJSON" */; buildPhases = ( FE667750AC3EE5E6C357274D08062245 /* Sources */, 229003D8AA2FC24D450F02A58E1EA5D2 /* Frameworks */, D5C9442E4D341BC38656D3EF6CE7F323 /* Headers */, ); buildRules = ( ); dependencies = ( F8E3977BAA922212CA0F1481E19D85F5 /* PBXTargetDependency */, FFC9EF8F219B1A13E2061AAE04196C7D /* PBXTargetDependency */, ); name = AlamofireSwiftyJSON; productName = AlamofireSwiftyJSON; productReference = 00D5A7387737E6AD24709714E04865D6 /* AlamofireSwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { isa = PBXNativeTarget; buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( 32B9974868188C4803318E36329C87FE /* Sources */, 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = Alamofire; productName = Alamofire; productReference = D8092F6C6AB8BEA23A525ABCF6B6CBEF /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; C052BEBFBD0AB5218CC64BA3450F6547 /* GTMSessionFetcher */ = { isa = PBXNativeTarget; buildConfigurationList = D7CC8559AB6F51830204F1A9CE54BF3E /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */; buildPhases = ( C5A309EC5A80A27DBD420C5176E2122A /* Sources */, 6AE88E96161DE195EAAF0A3B6375EA50 /* Frameworks */, 82D993B88C10479096F17ADDEAB85D94 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = GTMSessionFetcher; productName = GTMSessionFetcher; productReference = B8E6ECE2A0D0C4D9EAD3039AD267BDAD /* GTMSessionFetcher.framework */; productType = "com.apple.product-type.framework"; }; C4944FEC314D1A66588651D006273ADE /* Kingfisher */ = { isa = PBXNativeTarget; buildConfigurationList = 76E7EFBCEA1340954A03AA68051C2306 /* Build configuration list for PBXNativeTarget "Kingfisher" */; buildPhases = ( EAC7EA95310C5E1E724C632852F7D186 /* Sources */, ED03E5917B811BACFE75189AE0C2A469 /* Frameworks */, 0F94B6BFE5A6242FBBB0BE3D27F7CEE9 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = Kingfisher; productName = Kingfisher; productReference = A377FDA04AE20A00A6BDE1C3CFF954D1 /* Kingfisher.framework */; productType = "com.apple.product-type.framework"; }; C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */ = { isa = PBXNativeTarget; buildConfigurationList = EB8E706BCD309B61E67B4B6956F61DCA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; buildPhases = ( 6ADC89DA0DB8AAD7550B08A75014E0BB /* Sources */, 8DD06B625DFB302A853551293B0AB0B4 /* Frameworks */, 3D3CACB7864BED7F83E4ADEDE0D6EE4D /* Headers */, ); buildRules = ( ); dependencies = ( ); name = SwiftyJSON; productName = SwiftyJSON; productReference = 7E20F3BDA6E05BBE04E83DD3C9AB2DB9 /* SwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; LastUpgradeCheck = 0700; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; productRefGroup = C0F4433F1A7FB3CDF46BDFB7645C45C2 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */, 00103D6C821BE85971C563025527BA5D /* GoogleToolboxForMac */, C052BEBFBD0AB5218CC64BA3450F6547 /* GTMSessionFetcher */, C4944FEC314D1A66588651D006273ADE /* Kingfisher */, 488E06E9F0251ABD57E7AA6A8F9F254C /* Pods-EZShopManager */, C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 32B9974868188C4803318E36329C87FE /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 63D7DA997053F6B5D01DE8CB5817CB51 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( FAC3F3CAABA60EF76069431C5BB5032A /* GoogleToolboxForMac-dummy.m in Sources */, F7D889906DECB078EAAECB9D4A320E9C /* GTMNSData+zlib.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6ADC89DA0DB8AAD7550B08A75014E0BB /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 20FFCB796689940613A141013D758B10 /* SwiftyJSON-dummy.m in Sources */, A5CE453D368326CCFE2ECA3034306EAA /* SwiftyJSON.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; C4BB6AC2523DA5CF65D0331AC3D873D6 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( AB17FFF3EEFA547806EEA1923644C52E /* Pods-EZShopManager-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; C5A309EC5A80A27DBD420C5176E2122A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 6EA6DFC4473A9B2DB6B8A42EA986BA5B /* GTMSessionFetcher-dummy.m in Sources */, 64F31B70A6E5E6963518A01C285B435F /* GTMSessionFetcher.m in Sources */, 07340F15BACBA601736DBB2ABF1ABC35 /* GTMSessionFetcherLogging.m in Sources */, 95C69447F517DB81437EDE0003486963 /* GTMSessionFetcherService.m in Sources */, F4E294C07EE32FFCDCF7FF4D71D850BD /* GTMSessionUploadFetcher.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; EAC7EA95310C5E1E724C632852F7D186 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 342AE33215135AD56B73580012DC22AB /* AnimatedImageView.swift in Sources */, 6DA770087D354CDCD3889CDAE7C4C698 /* Box.swift in Sources */, 2E5E570FFC49EF98550401421A243C0F /* CacheSerializer.swift in Sources */, 4089E39F76F86466B8DDD39A1C1ABB6B /* Filter.swift in Sources */, 33A14E817C0FA585D5DA3A55E453299D /* Image.swift in Sources */, F8E957950566622A3E4B61AACE8F0B4A /* ImageCache.swift in Sources */, DC6080C64C269628C3F5107BE87055E2 /* ImageDownloader.swift in Sources */, 3414E1D9CB15149A296E16C45967B021 /* ImagePrefetcher.swift in Sources */, 0E9CC28AC8E34FE8E1C87E933E04BC7A /* ImageProcessor.swift in Sources */, 86B7DA678C8705523C300947117C0706 /* ImageTransition.swift in Sources */, 33395912F2FFA355C4C36B7EDEAA3DA7 /* ImageView+Kingfisher.swift in Sources */, 52A280AB4852FDE92DF09B5E79D5C2AA /* Indicator.swift in Sources */, 6A375593407BC7937234B2B6A0811760 /* Kingfisher-dummy.m in Sources */, C9CC5ED97D29C6C3DE22B78A9AA2AD91 /* Kingfisher.swift in Sources */, 7636F846675C9F4ED96E00C6C19A4890 /* KingfisherManager.swift in Sources */, 378B44CAA91C2106076668FDE72E1E02 /* KingfisherOptionsInfo.swift in Sources */, EA816A580C3858934ED6FE92040C26DD /* RequestModifier.swift in Sources */, 8DA7E6883118CB3C8132B64D3D43AE0B /* Resource.swift in Sources */, 9F826F893E86EB86591B637A1CE4B13A /* String+MD5.swift in Sources */, 6CD63E1564618B6213B98E0ABBC3127C /* ThreadHelper.swift in Sources */, EE89512E8D36E67CDC525DB9D5BBF5A7 /* UIButton+Kingfisher.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; FE667750AC3EE5E6C357274D08062245 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 4E59744DDACFECB37D3531E504228AA1 /* AlamofireSwiftyJSON-dummy.m in Sources */, 59BE44195191D46A245AAB3F8B5BA4A4 /* AlamofireSwiftyJSON.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 1CC714863471D79952C5622111205275 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = AlamofireSwiftyJSON; target = 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */; targetProxy = 81EA9E33260BDCB52F6B0504E8B20ECD /* PBXContainerItemProxy */; }; 1FCB5A84D8DB2AEB2422D2713CFA5780 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftyJSON; target = C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */; targetProxy = 9BB2B391009907F2870003C114B2F54E /* PBXContainerItemProxy */; }; 5FCE831A2ED384DE4A61C4D51177618D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GoogleToolboxForMac; target = 00103D6C821BE85971C563025527BA5D /* GoogleToolboxForMac */; targetProxy = 62BCF1C4255DEC22F6CB1E79332FED47 /* PBXContainerItemProxy */; }; 7C927C0C2AF8F51829D2121B777487E0 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Kingfisher; target = C4944FEC314D1A66588651D006273ADE /* Kingfisher */; targetProxy = A1F10796BCCFE760190DE33893C9FF98 /* PBXContainerItemProxy */; }; 950BA7BD27E10495AAA3A628EA521C47 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GTMSessionFetcher; target = C052BEBFBD0AB5218CC64BA3450F6547 /* GTMSessionFetcher */; targetProxy = 7F4A40413ED5FA7D86A70E9D42CA03D4 /* PBXContainerItemProxy */; }; CEAC232D04E69798D57D57CE135061E7 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; targetProxy = 70340C6869658F6ED9D2D2C9E8837698 /* PBXContainerItemProxy */; }; F8E3977BAA922212CA0F1481E19D85F5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; targetProxy = 9FDAF5C6C834BA59530A0169BB8EB750 /* PBXContainerItemProxy */; }; FFC9EF8F219B1A13E2061AAE04196C7D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftyJSON; target = C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */; targetProxy = F6814470266156FFDECCFBF764C454DA /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = AB2CB244EEC2B049C3CF730578C20B96 /* Alamofire.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 278C7981636F9B196A5DA1B51BCB7753 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = F1614E05B00DB6E549CDC107ACBCA5E7 /* Pods-EZShopManager.release.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-EZShopManager/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 10.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-EZShopManager/Pods-EZShopManager.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = Pods_EZShopManager; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 380C30050278E488BE23DB926933212E /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 6D16541A098F54C50DD73A542B46865F /* Kingfisher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Kingfisher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = Kingfisher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 406F8E030A25D2B7D358BF07A7AF34CA /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 301F1B1D0570093C5E651B91DB8DCBC6 /* Pods-EZShopManager.debug.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-EZShopManager/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 10.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-EZShopManager/Pods-EZShopManager.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = Pods_EZShopManager; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 673254EEAF0B5BF4596080C749645884 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_RELEASE=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; SYMROOT = "${SRCROOT}/../build"; VALIDATE_PRODUCT = YES; }; name = Release; }; 6E53245BBAAAB71AD4E0EE52CA99FD28 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 6D16541A098F54C50DD73A542B46865F /* Kingfisher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Kingfisher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = Kingfisher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 9EC0381780FB0030D1C388B0D8C5AF03 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 930F2905CF29770C811B5CB6FCB45493 /* AlamofireSwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/AlamofireSwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = AlamofireSwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; A0A2261397295783909F252F7AA52949 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 0518DEFE28C2EC662F1399AC90DA9711 /* SwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; B9C7324D0ADEABED7BC7B2D9C608C5E0 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = ECE9B6739B9B137C500ABB6547B4E8D4 /* GTMSessionFetcher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = GTMSessionFetcher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; BA3A1AE463BAE81544A37570B2425BE8 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 0518DEFE28C2EC662F1399AC90DA9711 /* SwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; BE557DED54B73B607DDA59D2EEFB306E /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 930F2905CF29770C811B5CB6FCB45493 /* AlamofireSwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/AlamofireSwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = AlamofireSwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; D60CD877A708870E2BE96B83BA32F883 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 1684905648A8947821C01ED37279C8BC /* GoogleToolboxForMac.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GoogleToolboxForMac/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = GoogleToolboxForMac; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; E4F26E6EB105713A6A7E7E2E283AC2DF /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = NO; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_DEBUG=1", "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; ONLY_ACTIVE_ARCH = YES; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; SYMROOT = "${SRCROOT}/../build"; }; name = Debug; }; ED969C86CBBA712335D5E741625E75B6 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = ECE9B6739B9B137C500ABB6547B4E8D4 /* GTMSessionFetcher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = GTMSessionFetcher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; F066921CBDBDB5F45795E50FBC5AC972 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 1684905648A8947821C01ED37279C8BC /* GoogleToolboxForMac.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GoogleToolboxForMac/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = GoogleToolboxForMac; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; F383079BFBF927813EA3613CFB679FDE /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = AB2CB244EEC2B049C3CF730578C20B96 /* Alamofire.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( E4F26E6EB105713A6A7E7E2E283AC2DF /* Debug */, 673254EEAF0B5BF4596080C749645884 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( F383079BFBF927813EA3613CFB679FDE /* Debug */, 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 55109BCFA5F87C7951E47D893E2980C0 /* Build configuration list for PBXNativeTarget "Pods-EZShopManager" */ = { isa = XCConfigurationList; buildConfigurations = ( 406F8E030A25D2B7D358BF07A7AF34CA /* Debug */, 278C7981636F9B196A5DA1B51BCB7753 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 76E7EFBCEA1340954A03AA68051C2306 /* Build configuration list for PBXNativeTarget "Kingfisher" */ = { isa = XCConfigurationList; buildConfigurations = ( 6E53245BBAAAB71AD4E0EE52CA99FD28 /* Debug */, 380C30050278E488BE23DB926933212E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C43D9CA5106C6CCEF973B7EDF833947B /* Build configuration list for PBXNativeTarget "GoogleToolboxForMac" */ = { isa = XCConfigurationList; buildConfigurations = ( D60CD877A708870E2BE96B83BA32F883 /* Debug */, F066921CBDBDB5F45795E50FBC5AC972 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; D7CC8559AB6F51830204F1A9CE54BF3E /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */ = { isa = XCConfigurationList; buildConfigurations = ( B9C7324D0ADEABED7BC7B2D9C608C5E0 /* Debug */, ED969C86CBBA712335D5E741625E75B6 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; DCCE50C77ACBD367E99B830BA1F92670 /* Build configuration list for PBXNativeTarget "AlamofireSwiftyJSON" */ = { isa = XCConfigurationList; buildConfigurations = ( BE557DED54B73B607DDA59D2EEFB306E /* Debug */, 9EC0381780FB0030D1C388B0D8C5AF03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; EB8E706BCD309B61E67B4B6956F61DCA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { isa = XCConfigurationList; buildConfigurations = ( A0A2261397295783909F252F7AA52949 /* Debug */, BA3A1AE463BAE81544A37570B2425BE8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Alamofire.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/AlamofireSwiftyJSON.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/GoogleToolboxForMac.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Kingfisher.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Pods-EZShopManager.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/SwiftyJSON.xcscheme ================================================ ================================================ FILE: iOS/Manager/EZShopManager/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/xcschememanagement.plist ================================================ SchemeUserState Alamofire.xcscheme isShown AlamofireSwiftyJSON.xcscheme isShown GTMSessionFetcher.xcscheme isShown GoogleToolboxForMac.xcscheme isShown Kingfisher.xcscheme isShown Pods-EZShopManager.xcscheme isShown SwiftyJSON.xcscheme isShown SuppressBuildableAutocreation 00103D6C821BE85971C563025527BA5D primary 488E06E9F0251ABD57E7AA6A8F9F254C primary 61E5C1379DC63FAC57AF48F891CFB123 primary 88E9EC28B8B46C3631E6B242B50F4442 primary C052BEBFBD0AB5218CC64BA3450F6547 primary C4944FEC314D1A66588651D006273ADE primary C68748E71A3DDB40B0AAF4BC0A8F9030 primary ================================================ FILE: iOS/Manager/EZShopManager/Pods/SwiftyJSON/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/Manager/EZShopManager/Pods/SwiftyJSON/README.md ================================================ # SwiftyJSON [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 2. [Requirements](#requirements) 3. [Integration](#integration) 4. [Usage](#usage) - [Initialization](#initialization) - [Subscript](#subscript) - [Loop](#loop) - [Error](#error) - [Optional getter](#optional-getter) - [Non-optional getter](#non-optional-getter) - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) > For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) > [中文介绍](http://tangplin.github.io/swiftyjson/) ## Why is the typical JSON handling in Swift NOT good? Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). The code would look like this: ```swift if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], let user = statusesArray[0]["user"] as? [String: Any], let username = user["name"] as? String { // Finally we got the username } ``` It's not good. Even if we use optional chaining, it would be messy: ```swift if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { // There's our username } ``` An unreadable mess--for something that should really be simple! With SwiftyJSON all you have to do is: ```swift let json = JSON(data: dataFromNetworking) if let userName = json[0]["user"]["name"].string { //Now you got your value } ``` And don't worry about the Optional Wrapping thing. It's done for you automatically. ```swift let json = JSON(data: dataFromNetworking) if let userName = json[999999]["wrong_key"]["wrong_name"].string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety } else { //Print the error print(json[999999]["wrong_key"]["wrong_name"]) } ``` ## Requirements - iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ - Xcode 8 ## Integration #### CocoaPods (iOS 8+, OS X 10.9+) You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: ```ruby platform :ios, '8.0' use_frameworks! target 'MyApp' do pod 'SwiftyJSON' end ``` Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: #### Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: ``` github "SwiftyJSON/SwiftyJSON" ``` #### Swift Package Manager You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: ```swift import PackageDescription let package = Package( name: "YOUR_PROJECT_NAME", targets: [], dependencies: [ .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0).. = json["list"].arrayValue ``` ```swift //If not a Dictionary or nil, return [:] let user: Dictionary = json["user"].dictionaryValue ``` #### Setter ```swift json["name"] = JSON("new-name") json[0] = JSON(1) ``` ```swift json["id"].int = 1234567890 json["coordinate"].double = 8766.766 json["name"].string = "Jack" json.arrayObject = [1,2,3,4] json.dictionaryObject = ["name":"Jack", "age":25] ``` #### Raw object ```swift let jsonObject: Any = json.object ``` ```swift if let jsonObject: Any = json.rawValue ``` ```swift //convert the JSON to raw NSData if let data = json.rawData() { //Do something you want } ``` ```swift //convert the JSON to a raw String if let string = json.rawString() { //Do something you want } ``` #### Existence ```swift //shows you whether value specified in JSON or not if json["name"].exists() ``` #### Literal convertibles For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) ```swift //StringLiteralConvertible let json: JSON = "I'm a json" ``` ```swift //IntegerLiteralConvertible let json: JSON = 12345 ``` ```swift //BooleanLiteralConvertible let json: JSON = true ``` ```swift //FloatLiteralConvertible let json: JSON = 2.8765 ``` ```swift //DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"] ``` ```swift //ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"] ``` ```swift //NilLiteralConvertible let json: JSON = nil ``` ```swift //With subscript in array var json: JSON = [1,2,3] json[0] = 100 json[1] = 200 json[2] = 300 json[999] = 300 //Don't worry, nothing will happen ``` ```swift //With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] json["name"] = "Mike" json["age"] = "25" //It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json ``` ```swift //Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" let path: [JSONSubscriptType] = ["list",3,"what"] json[path] = "that" ``` ```swift //With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ "user": user.object //use user.object instead of just user "apikey": "supersecretapitoken" ] ``` #### Merging It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: - In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. In case, where two fields in a JSON have a different types, the value will get always overwritten. There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. ```swift let original: JSON = [ "first_name": "John", "age": 20, "skills": ["Coding", "Reading"], "address": [ "street": "Front St", "zip": "12345", ] ] let update: JSON = [ "last_name": "Doe", "age": 21, "skills": ["Writing"], "address": [ "zip": "12342", "city": "New York City" ] ] let updated = original.merge(with: update) // [ // "first_name": "John", // "last_name": "Doe", // "age": 21, // "skills": ["Coding", "Reading", "Writing"], // "address": [ // "street": "Front St", // "zip": "12342", // "city": "New York City" // ] // ] ``` ## String representation There are two options available: - use the default Swift one - use a custom one that will handle optionals well and represent `nil` as `"null"`: ```swift let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} ``` ## Work with Alamofire SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: ```swift Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) print("JSON: \(json)") case .failure(let error): print(error) } } ``` ================================================ FILE: iOS/Manager/EZShopManager/Pods/SwiftyJSON/Source/SwiftyJSON.swift ================================================ // SwiftyJSON.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } catch let aError as NSError { if error != nil { error?.pointee = aError } self.init(jsonObject: NSNull()) } } /** Creates a JSON object - parameter object: the object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as [JSON] where object.count > 0: self.init(array: object) case let object as [String: JSON] where object.count > 0: self.init(dictionary: object) case let object as Data: self.init(data: object) default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ fileprivate init(jsonObject: Any) { self.object = jsonObject } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ fileprivate init(array: [JSON]) { self.init(array.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ fileprivate init(dictionary: [String: JSON]) { var newDictionary = [String: Any](minimumCapacity: dictionary.count) for (key, json) in dictionary { newDictionary[key] = json.object } self.init(newDictionary) } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case _ as [JSON]: _type = .array case nil: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } public enum Index: Comparable { case array(Int) case dictionary(DictionaryIndex) case null static public func ==(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func <(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index public typealias JSONRawIndex = Index extension JSON: Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): let (key, value) = self.rawDictionary[idx] return (key, JSON(value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let array = elements self.init(dictionaryLiteral: array) } public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in if let value = dictionary[key] { return (key, value) } return nil } return JSON(dictionaryLiteral: initializeElement) } var dict = [String : Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object } else if let jsonArray = element.1 as? [JSON] { elementToSet = JSON(jsonArray).object } else if let dictionary = element.1 as? [String : Any] { elementToSet = jsonFromDictionaryLiteral(dictionary).object } else if let dictArray = element.1 as? [[String : Any]] { let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } elementToSet = JSON(jsonArray).object } else { elementToSet = element.1 } dict[element.0] = elementToSet } self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } fileprivate func _rawString( _ encoding: String.Encoding = .utf8, options: [writtingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { if (maxObjectDepth < 0) { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = self.object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = self.object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String : JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return ["true", "y", "t"].contains() { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { return false } return true } } //MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writtingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Alamofire-dummy.m ================================================ #import @interface PodsDummy_Alamofire : NSObject @end @implementation PodsDummy_Alamofire @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double AlamofireVersionNumber; FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Alamofire.modulemap ================================================ framework module Alamofire { umbrella header "Alamofire-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Alamofire.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Alamofire/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 4.3.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-dummy.m ================================================ #import @interface PodsDummy_AlamofireSwiftyJSON : NSObject @end @implementation PodsDummy_AlamofireSwiftyJSON @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double AlamofireSwiftyJSONVersionNumber; FOUNDATION_EXPORT const unsigned char AlamofireSwiftyJSONVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap ================================================ framework module AlamofireSwiftyJSON { umbrella header "AlamofireSwiftyJSON-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/AlamofireSwiftyJSON/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 0.2.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m ================================================ #import @interface PodsDummy_GTMSessionFetcher : NSObject @end @implementation PodsDummy_GTMSessionFetcher @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "GTMSessionFetcher.h" #import "GTMSessionFetcherLogging.h" #import "GTMSessionFetcherService.h" #import "GTMSessionUploadFetcher.h" FOUNDATION_EXPORT double GTMSessionFetcherVersionNumber; FOUNDATION_EXPORT const unsigned char GTMSessionFetcherVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap ================================================ framework module GTMSessionFetcher { umbrella header "GTMSessionFetcher-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_LDFLAGS = -framework "Security" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GTMSessionFetcher/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 1.1.8 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-dummy.m ================================================ #import @interface PodsDummy_GoogleToolboxForMac : NSObject @end @implementation PodsDummy_GoogleToolboxForMac @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "GTMDefines.h" #import "GTMNSData+zlib.h" FOUNDATION_EXPORT double GoogleToolboxForMacVersionNumber; FOUNDATION_EXPORT const unsigned char GoogleToolboxForMacVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap ================================================ framework module GoogleToolboxForMac { umbrella header "GoogleToolboxForMac-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_LDFLAGS = -l"z" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/GoogleToolboxForMac/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 2.1.1 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 3.4.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Kingfisher-dummy.m ================================================ #import @interface PodsDummy_Kingfisher : NSObject @end @implementation PodsDummy_Kingfisher @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Kingfisher-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Kingfisher-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "Kingfisher.h" FOUNDATION_EXPORT double KingfisherVersionNumber; FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Kingfisher.modulemap ================================================ framework module Kingfisher { umbrella header "Kingfisher-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Kingfisher/Kingfisher.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Kingfisher GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_LDFLAGS = -framework "CFNetwork" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES SWIFT_VERSION = 3.0 ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 1.0.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-acknowledgements.markdown ================================================ # Acknowledgements This application makes use of the following third party libraries: ## Alamofire Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## AlamofireSwiftyJSON Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Firebase Copyright 2017 Google ## FirebaseAnalytics Copyright 2017 Google ## FirebaseCore Copyright 2017 Google ## FirebaseDatabase Copyright 2017 Google ## FirebaseInstanceID Copyright 2017 Google ## FirebaseStorage Copyright 2017 Google ## GTMSessionFetcher Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## GoogleToolboxForMac Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## Kingfisher The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SwiftyJSON The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - https://cocoapods.org ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-acknowledgements.plist ================================================ PreferenceSpecifiers FooterText This application makes use of the following third party libraries: Title Acknowledgements Type PSGroupSpecifier FooterText Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title Alamofire Type PSGroupSpecifier FooterText Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title AlamofireSwiftyJSON Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title Firebase Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseAnalytics Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseCore Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseDatabase Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseInstanceID Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseStorage Type PSGroupSpecifier FooterText Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. License Apache Title GTMSessionFetcher Type PSGroupSpecifier FooterText Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. License Apache Title GoogleToolboxForMac Type PSGroupSpecifier FooterText The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title Kingfisher Type PSGroupSpecifier FooterText The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title SwiftyJSON Type PSGroupSpecifier FooterText Generated by CocoaPods - https://cocoapods.org Title Type PSGroupSpecifier StringsTable Acknowledgements Title Acknowledgements ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-dummy.m ================================================ #import @interface PodsDummy_Pods_EZShopManager : NSObject @end @implementation PodsDummy_Pods_EZShopManager @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-frameworks.sh ================================================ #!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" install_framework "$BUILT_PRODUCTS_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework" install_framework "$BUILT_PRODUCTS_DIR/GTMSessionFetcher/GTMSessionFetcher.framework" install_framework "$BUILT_PRODUCTS_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework" install_framework "$BUILT_PRODUCTS_DIR/Kingfisher/Kingfisher.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftyJSON/SwiftyJSON.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" install_framework "$BUILT_PRODUCTS_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework" install_framework "$BUILT_PRODUCTS_DIR/GTMSessionFetcher/GTMSessionFetcher.framework" install_framework "$BUILT_PRODUCTS_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework" install_framework "$BUILT_PRODUCTS_DIR/Kingfisher/Kingfisher.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftyJSON/SwiftyJSON.framework" fi ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-resources.sh ================================================ #!/bin/sh set -e mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" XCASSET_FILES=() case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac install_resource() { if [[ "$1" = /* ]] ; then RESOURCE_PATH="$1" else RESOURCE_PATH="${PODS_ROOT}/$1" fi if [[ ! -e "$RESOURCE_PATH" ]] ; then cat << EOM error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. EOM exit 1 fi case $RESOURCE_PATH in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" ;; *.xcassets) ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") ;; *) echo "$RESOURCE_PATH" echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" ;; esac } mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] then # Find all other xcassets (this unfortunately includes those of path pods and other targets). OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) while read line; do if [[ $line != "${PODS_ROOT}*" ]]; then XCASSET_FILES+=("$line") fi done <<<"$OTHER_XCASSETS" printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double Pods_EZShopManagerVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_EZShopManagerVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager.debug.xcconfig ================================================ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES EMBEDDED_CONTENT_CONTAINS_SWIFT = YES FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON" "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher" "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac" "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseCore/Frameworks" "${PODS_ROOT}/FirebaseDatabase/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/FirebaseStorage/Frameworks" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/Core/Sources $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher/Kingfisher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" -isystem "${PODS_ROOT}/Headers/Public/FirebaseCore" -isystem "${PODS_ROOT}/Headers/Public/FirebaseDatabase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" -isystem "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "Alamofire" -framework "AlamofireSwiftyJSON" -framework "CFNetwork" -framework "FirebaseAnalytics" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseStorage" -framework "GTMSessionFetcher" -framework "GoogleToolboxForMac" -framework "Kingfisher" -framework "MobileCoreServices" -framework "Security" -framework "StoreKit" -framework "SwiftyJSON" -framework "SystemConfiguration" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT}/Pods ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager.modulemap ================================================ framework module Pods_EZShopManager { umbrella header "Pods-EZShopManager-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/Pods-EZShopManager/Pods-EZShopManager.release.xcconfig ================================================ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES EMBEDDED_CONTENT_CONTAINS_SWIFT = YES FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON" "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher" "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac" "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseCore/Frameworks" "${PODS_ROOT}/FirebaseDatabase/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/FirebaseStorage/Frameworks" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/Core/Sources $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher/Kingfisher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" -isystem "${PODS_ROOT}/Headers/Public/FirebaseCore" -isystem "${PODS_ROOT}/Headers/Public/FirebaseDatabase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" -isystem "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "Alamofire" -framework "AlamofireSwiftyJSON" -framework "CFNetwork" -framework "FirebaseAnalytics" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseStorage" -framework "GTMSessionFetcher" -framework "GoogleToolboxForMac" -framework "Kingfisher" -framework "MobileCoreServices" -framework "Security" -framework "StoreKit" -framework "SwiftyJSON" -framework "SystemConfiguration" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT}/Pods ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 3.1.4 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m ================================================ #import @interface PodsDummy_SwiftyJSON : NSObject @end @implementation PodsDummy_SwiftyJSON @end ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double SwiftyJSONVersionNumber; FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap ================================================ framework module SwiftyJSON { umbrella header "SwiftyJSON-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/Manager/EZShopManager/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseStorage" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES SWIFT_VERSION = 3.0 ================================================ FILE: iOS/README.md ================================================ Hello! ================================================ FILE: iOS/User/ezshopUser/Podfile ================================================ # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'ezshopUser' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for ezshopUser pod 'Firebase/Core' pod 'AlamofireSwiftyJSON' pod 'Firebase/Database' pod 'Firebase/Messaging' pod 'Kingfisher', '~> 3.0' end ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/LICENSE ================================================ Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/README.md ================================================ ![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) Alamofire is an HTTP networking library written in Swift. - [Features](#features) - [Component Libraries](#component-libraries) - [Requirements](#requirements) - [Migration Guides](#migration-guides) - [Communication](#communication) - [Installation](#installation) - [Usage](#usage) - **Intro -** [Making a Request](#making-a-request), [Response Handling](#response-handling), [Response Validation](#response-validation), [Response Caching](#response-caching) - **HTTP -** [HTTP Methods](#http-methods), [Parameter Encoding](#parameter-encoding), [HTTP Headers](#http-headers), [Authentication](#authentication) - **Large Data -** [Downloading Data to a File](#downloading-data-to-a-file), [Uploading Data to a Server](#uploading-data-to-a-server) - **Tools -** [Statistical Metrics](#statistical-metrics), [cURL Command Output](#curl-command-output) - [Advanced Usage](#advanced-usage) - **URL Session -** [Session Manager](#session-manager), [Session Delegate](#session-delegate), [Request](#request) - **Routing -** [Routing Requests](#routing-requests), [Adapting and Retrying Requests](#adapting-and-retrying-requests) - **Model Objects -** [Custom Response Serialization](#custom-response-serialization) - **Connection -** [Security](#security), [Network Reachability](#network-reachability) - [Open Radars](#open-radars) - [FAQ](#faq) - [Credits](#credits) - [Donations](#donations) - [License](#license) ## Features - [x] Chainable Request / Response Methods - [x] URL / JSON / plist Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData - [x] Download File using Request or Resume Data - [x] Authentication with URLCredential - [x] HTTP Response Validation - [x] Upload and Download Progress Closures with Progress - [x] cURL Command Output - [x] Dynamically Adapt and Retry Requests - [x] TLS Certificate and Public Key Pinning - [x] Network Reachability - [x] Comprehensive Unit and Integration Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) ## Component Libraries In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. - [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. ## Requirements - iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ - Xcode 8.1+ - Swift 3.0+ ## Migration Guides - [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) - [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) - [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) ## Communication - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). - If you **found a bug**, open an issue. - If you **have a feature request**, open an issue. - If you **want to contribute**, submit a pull request. ## Installation ### CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: ```bash $ gem install cocoapods ``` > CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' use_frameworks! target '' do pod 'Alamofire', '~> 4.3' end ``` Then, run the following command: ```bash $ pod install ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with [Homebrew](http://brew.sh/) using the following command: ```bash $ brew update $ brew install carthage ``` To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "Alamofire/Alamofire" ~> 4.3 ``` Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. ### Swift Pacakge Manager The [Swift Pacakage Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. ```swift dependencies: [ .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) ] ``` ### Manually If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. #### Embedded Framework - Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: ```bash $ git init ``` - Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git ``` - Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - Select the top `Alamofire.framework` for iOS and the bottom one for OS X. > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. - And that's it! > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. --- ## Usage ### Making a Request ```swift import Alamofire Alamofire.request("https://httpbin.org/get") ``` ### Response Handling Handling the `Response` of a `Request` made in Alamofire involves chaining a response handler onto the `Request`. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } ``` In the above example, the `responseJSON` handler is appended to the `Request` to be executed once the `Request` is complete. Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure. > Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. Alamofire contains five different response handlers by default including: ```swift // Response Handler - Unserialized Response func response( queue: DispatchQueue?, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self // Response Data Handler - Serialized into Data func responseData( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response String Handler - Serialized into String func responseString( queue: DispatchQueue?, encoding: String.Encoding?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response JSON Handler - Serialized into Any func responseJSON( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self // Response PropertyList (plist) Handler - Serialized into Any func responsePropertyList( queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void)) -> Self ``` None of the response handlers perform any validation of the `HTTPURLResponse` it gets back from the server. > For example, response status codes in the `400..<499` and `500..<599` ranges do NOT automatically trigger an `Error`. Alamofire uses [Response Validation](#response-validation) method chaining to achieve this. #### Response Handler The `response` handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using `cURL` to execute a `Request`. ```swift Alamofire.request("https://httpbin.org/get").response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } ``` > We strongly encourage you to leverage the other response serializers taking advantage of `Response` and `Result` types. #### Response Data Handler The `responseData` handler uses the `responseDataSerializer` (the object that serializes the server data into some other type) to extract the `Data` returned by the server. If no errors occur and `Data` is returned, the response `Result` will be a `.success` and the `value` will be of type `Data`. ```swift Alamofire.request("https://httpbin.org/get").responseData { response in debugPrint("All Response Info: \(response)") if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } ``` #### Response String Handler The `responseString` handler uses the `responseStringSerializer` to convert the `Data` returned by the server into a `String` with the specified encoding. If no errors occur and the server data is successfully serialized into a `String`, the response `Result` will be a `.success` and the `value` will be of type `String`. ```swift Alamofire.request("https://httpbin.org/get").responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") } ``` > If no encoding is specified, Alamofire will use the text encoding specified in the `HTTPURLResponse` from the server. If the text encoding cannot be determined by the server response, it defaults to `.isoLatin1`. #### Response JSON Handler The `responseJSON` handler uses the `responseJSONSerializer` to convert the `Data` returned by the server into an `Any` type using the specified `JSONSerialization.ReadingOptions`. If no errors occur and the server data is successfully serialized into a JSON object, the response `Result` will be a `.success` and the `value` will be of type `Any`. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in debugPrint(response) if let json = response.result.value { print("JSON: \(json)") } } ``` > All JSON serialization is handled by the `JSONSerialization` API in the `Foundation` framework. #### Chained Response Handlers Response handlers can even be chained: ```swift Alamofire.request("https://httpbin.org/get") .responseString { response in print("Response String: \(response.result.value)") } .responseJSON { response in print("Response JSON: \(response.result.value)") } ``` > It is important to note that using multiple response handlers on the same `Request` requires the server data to be serialized multiple times. Once for each response handler. #### Response Handler Queue Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead. ```swift let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in print("Executing response handler on utility queue") } ``` ### Response Validation By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling `validate` before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. #### Manual Validation ```swift Alamofire.request("https://httpbin.org/get") .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseData { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } } ``` #### Automatic Validation Automatically validates status code within `200...299` range, and that the `Content-Type` header of the response matches the `Accept` header of the request, if one is provided. ```swift Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } } ``` ### Response Caching Response Caching is handled on the system framework level by [`URLCache`](https://developer.apple.com/reference/foundation/urlcache). It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions. > By default, Alamofire leverages the shared `URLCache`. In order to customize it, see the [Session Manager Configurations](#session-manager) section. ### HTTP Methods The `HTTPMethod` enumeration lists the HTTP methods defined in [RFC 7231 §4.3](http://tools.ietf.org/html/rfc7231#section-4.3): ```swift public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } ``` These values can be passed as the `method` argument to the `Alamofire.request` API: ```swift Alamofire.request("https://httpbin.org/get") // method defaults to `.get` Alamofire.request("https://httpbin.org/post", method: .post) Alamofire.request("https://httpbin.org/put", method: .put) Alamofire.request("https://httpbin.org/delete", method: .delete) ``` > The `Alamofire.request` method parameter defaults to `.get`. ### Parameter Encoding Alamofire supports three types of parameter encoding including: `URL`, `JSON` and `PropertyList`. It can also support any custom encoding that conforms to the `ParameterEncoding` protocol. #### URL Encoding The `URLEncoding` type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the `Destination` of the encoding. The `Destination` enumeration has three cases: - `.methodDependent` - Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and sets as the HTTP body for requests with any other HTTP method. - `.queryString` - Sets or appends encoded query string result to existing query string. - `.httpBody` - Sets encoded query string result as the HTTP body of the URL request. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). ##### GET Request With URL-Encoded Parameters ```swift let parameters: Parameters = ["foo": "bar"] // All three of these calls are equivalent Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default` Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent)) // https://httpbin.org/get?foo=bar ``` ##### POST Request With URL-Encoded Parameters ```swift let parameters: Parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ] ] // All three of these calls are equivalent Alamofire.request("https://httpbin.org/post", parameters: parameters) Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default) Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody) // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 ``` #### JSON Encoding The `JSONEncoding` type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. ##### POST Request with JSON-Encoded Parameters ```swift let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ] ] // Both calls are equivalent Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default) Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: [])) // HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} ``` #### Property List Encoding The `PropertyListEncoding` uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. #### Custom Encoding In the event that the provided `ParameterEncoding` types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom `JSONStringArrayEncoding` type to encode a JSON string array onto a `Request`. ```swift struct JSONStringArrayEncoding: ParameterEncoding { private let array: [String] init(array: [String]) { self.array = array } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = urlRequest.urlRequest let data = try JSONSerialization.data(withJSONObject: array, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return urlRequest } } ``` #### Manual Parameter Encoding of a URLRequest The `ParameterEncoding` APIs can be used outside of making network requests. ```swift let url = URL(string: "https://httpbin.org/get")! var urlRequest = URLRequest(url: url) let parameters: Parameters = ["foo": "bar"] let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) ``` ### HTTP Headers Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. ```swift let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Accept": "application/json" ] Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in debugPrint(response) } ``` > For HTTP headers that do not change, it is recommended to set them on the `URLSessionConfiguration` so they are automatically applied to any `URLSessionTask` created by the underlying `URLSession`. For more information, see the [Session Manager Configurations](#session-manager) section. The default Alamofire `SessionManager` provides a default set of headers for every `Request`. These include: - `Accept-Encoding`, which defaults to `gzip;q=1.0, compress;q=0.5`, per [RFC 7230 §4.2.3](https://tools.ietf.org/html/rfc7230#section-4.2.3). - `Accept-Language`, which defaults to up to the top 6 preferred languages on the system, formatted like `en;q=1.0`, per [RFC 7231 §5.3.5](https://tools.ietf.org/html/rfc7231#section-5.3.5). - `User-Agent`, which contains versioning information about the current app. For example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0`, per [RFC 7231 §5.5.3](https://tools.ietf.org/html/rfc7231#section-5.5.3). If you need to customize these headers, a custom `URLSessionConfiguration` should be created, the `defaultHTTPHeaders` property updated and the configuration applied to a new `SessionManager` instance. ### Authentication Authentication is handled on the system framework level by [`URLCredential`](https://developer.apple.com/reference/foundation/nsurlcredential) and [`URLAuthenticationChallenge`](https://developer.apple.com/reference/foundation/urlauthenticationchallenge). **Supported Authentication Schemes** - [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) - [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) - [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) - [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) #### HTTP Basic Authentication The `authenticate` method on a `Request` will automatically provide a `URLCredential` to a `URLAuthenticationChallenge` when appropriate: ```swift let user = "user" let password = "password" Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .responseJSON { response in debugPrint(response) } ``` Depending upon your server implementation, an `Authorization` header may also be appropriate: ```swift let user = "user" let password = "password" var headers: HTTPHeaders = [:] if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { headers[authorizationHeader.key] = authorizationHeader.value } Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) .responseJSON { response in debugPrint(response) } ``` #### Authentication with URLCredential ```swift let user = "user" let password = "password" let credential = URLCredential(user: user, password: password, persistence: .forSession) Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(usingCredential: credential) .responseJSON { response in debugPrint(response) } ``` > It is important to note that when using a `URLCredential` for authentication, the underlying `URLSession` will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying `URLSession`. ### Downloading Data to a File Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The `Alamofire.request` APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the `Alamofire.download` APIs to download the server data to a temporary file on-disk. > This will only work on `macOS` as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the [Download File Destination](#download-file-destination) section. ```swift Alamofire.download("https://httpbin.org/image/png").responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` > The `Alamofire.download` APIs should also be used if you need to download data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. #### Download File Destination You can also provide a `DownloadFileDestination` closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the `destinationURL`, the `DownloadOptions` specified in the closure will be executed. The two currently supported `DownloadOptions` are: - `.createIntermediateDirectories` - Creates intermediate directories for the destination URL if specified. - `.removePreviousFile` - Removes a previous file from the destination URL if specified. ```swift let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendPathComponent("pig.png") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(urlString, to: destination).response { response in print(response) if response.error == nil, let imagePath = response.destinationURL?.path { let image = UIImage(contentsOfFile: imagePath) } } ``` You can also use the suggested download destination API. ```swift let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory) Alamofire.download("https://httpbin.org/image/png", to: destination) ``` #### Download Progress Many times it can be helpful to report download progress to the user. Any `DownloadRequest` can report download progress using the `downloadProgress` API. ```swift Alamofire.download("https://httpbin.org/image/png") .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` The `downloadProgress` API also takes a `queue` parameter which defines which `DispatchQueue` the download progress closure should be called on. ```swift let utilityQueue = DispatchQueue.global(qos: .utility) Alamofire.download("https://httpbin.org/image/png") .downloadProgress(queue: utilityQueue) { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } } ``` #### Resuming a Download If a `DownloadRequest` is cancelled or interrupted, the underlying URL session may generate resume data for the active `DownloadRequest`. If this happens, the resume data can be re-used to restart the `DownloadRequest` where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request. > **IMPORTANT:** On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow [post](http://stackoverflow.com/a/39347461/1342462). ```swift class ImageRequestor { private var resumeData: Data? private var image: UIImage? func fetchImage(completion: (UIImage?) -> Void) { guard image == nil else { completion(image) ; return } let destination: DownloadRequest.DownloadFileDestination = { _, _ in let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendPathComponent("pig.png") return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) } let request: DownloadRequest if let resumeData = resumeData { request = Alamofire.download(resumingWith: resumeData) } else { request = Alamofire.download("https://httpbin.org/image/png") } request.responseData { response in switch response.result { case .success(let data): self.image = UIImage(data: data) case .failure: self.resumeData = response.resumeData } } } } ``` ### Uploading Data to a Server When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the `Alamofire.request` APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an `InputStream`, then the `Alamofire.upload` APIs are what you want to use. > The `Alamofire.upload` APIs should also be used if you need to upload data while your app is in the background. For more information, please see the [Session Manager Configurations](#session-manager) section. #### Uploading Data ```swift let imageData = UIPNGRepresentation(image)! Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response) } ``` #### Uploading a File ```swift let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response) } ``` #### Uploading Multipart Form Data ```swift Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") }, to: "https://httpbin.org/post", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .failure(let encodingError): print(encodingError) } } ) ``` #### Upload Progress While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any `UploadRequest` can report both upload progress and download progress of the response data using the `uploadProgress` and `downloadProgress` APIs. ```swift let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") Alamofire.upload(fileURL, to: "https://httpbin.org/post") .uploadProgress { progress in // main queue by default print("Upload Progress: \(progress.fractionCompleted)") } .downloadProgress { progress in // main queue by default print("Download Progress: \(progress.fractionCompleted)") } .responseJSON { response in debugPrint(response) } ``` ### Statistical Metrics #### Timeline Alamofire collects timings throughout the lifecycle of a `Request` and creates a `Timeline` object exposed as a property on all response types. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.timeline) } ``` The above reports the following `Timeline` info: - `Latency`: 0.428 seconds - `Request Duration`: 0.428 seconds - `Serialization Duration`: 0.001 seconds - `Total Duration`: 0.429 seconds #### URL Session Task Metrics In iOS and tvOS 10 and macOS 10.12, Apple introduced the new [URLSessionTaskMetrics](https://developer.apple.com/reference/foundation/urlsessiontaskmetrics) APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the `Timeline`, but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type. ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in print(response.metrics) } ``` It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks: ```swift Alamofire.request("https://httpbin.org/get").responseJSON { response in if #available(iOS 10.0. *) { print(response.metrics) } } ``` ### cURL Command Output Debugging platform issues can be frustrating. Thankfully, Alamofire `Request` objects conform to both the `CustomStringConvertible` and `CustomDebugStringConvertible` protocols to provide some VERY helpful debugging tools. #### CustomStringConvertible ```swift let request = Alamofire.request("https://httpbin.org/ip") print(request) // GET https://httpbin.org/ip (200) ``` #### CustomDebugStringConvertible ```swift let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]) debugPrint(request) ``` Outputs: ```bash $ curl -i \ -H "User-Agent: Alamofire/4.0.0" \ -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \ -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \ "https://httpbin.org/get?foo=bar" ``` --- ## Advanced Usage Alamofire is built on `URLSession` and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack. **Recommended Reading** - [URL Loading System Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html) - [URLSession Class Reference](https://developer.apple.com/reference/foundation/nsurlsession) - [URLCache Class Reference](https://developer.apple.com/reference/foundation/urlcache) - [URLAuthenticationChallenge Class Reference](https://developer.apple.com/reference/foundation/urlauthenticationchallenge) ### Session Manager Top-level convenience methods like `Alamofire.request` use a default instance of `Alamofire.SessionManager`, which is configured with the default `URLSessionConfiguration`. As such, the following two statements are equivalent: ```swift Alamofire.request("https://httpbin.org/get") ``` ```swift let sessionManager = Alamofire.SessionManager.default sessionManager.request("https://httpbin.org/get") ``` Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (`httpAdditionalHeaders`) or timeout interval (`timeoutIntervalForRequest`). #### Creating a Session Manager with Default Configuration ```swift let configuration = URLSessionConfiguration.default let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Creating a Session Manager with Background Configuration ```swift let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background") let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Creating a Session Manager with Ephemeral Configuration ```swift let configuration = URLSessionConfiguration.ephemeral let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` #### Modifying the Session Configuration ```swift var defaultHeaders = Alamofire.SessionManager.default.defaultHTTPHeaders defaultHeaders["DNT"] = "1 (Do Not Track Enabled)" let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = defaultHeaders let sessionManager = Alamofire.SessionManager(configuration: configuration) ``` > This is **not** recommended for `Authorization` or `Content-Type` headers. Instead, use the `headers` parameter in the top-level `Alamofire.request` APIs, `URLRequestConvertible` and `ParameterEncoding`, respectively. ### Session Delegate By default, an Alamofire `SessionManager` instance creates a `SessionDelegate` object to handle all the various types of delegate callbacks that are generated by the underlying `URLSession`. The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons. #### Override Closures The first way to customize the `SessionDelegate` behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching `SessionDelegate` API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available: ```swift /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? ``` The following is a short example of how to use the `taskWillPerformHTTPRedirection` to avoid following redirects to any `apple.com` domains. ```swift let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default) let delegate: Alamofire.SessionDelegate = sessionManager.delegate delegate.taskWillPerformHTTPRedirection = { session, task, response, request in var finalRequest = request if let originalRequest = task.originalRequest, let urlString = originalRequest.url?.urlString, urlString.contains("apple.com") { finalRequest = originalRequest } return finalRequest } ``` #### Subclassing Another way to override the default implementation of the `SessionDelegate` is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the `SessionDelegate` and logging a message when a redirect occurs. ```swift class LoggingSessionDelegate: SessionDelegate { override func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { print("URLSession will perform HTTP redirection to request: \(request)") super.urlSession( session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler ) } } ``` Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort. > It is important to keep in mind that the `subdelegates` are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks. ### Request The result of a `request`, `download`, `upload` or `stream` methods are a `DataRequest`, `DownloadRequest`, `UploadRequest` and `StreamRequest` which all inherit from `Request`. All `Request` instances are always created by an owning session manager, and never initialized directly. Each subclass has specialized methods such as `authenticate`, `validate`, `responseJSON` and `uploadProgress` that each return the caller instance in order to facilitate method chaining. Requests can be suspended, resumed and cancelled: - `suspend()`: Suspends the underlying task and dispatch queue. - `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have `startRequestsImmediately` set to `true`, the request must call `resume()` in order to start. - `cancel()`: Cancels the underlying task, producing an error that is passed to any registered response handlers. ### Routing Requests As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire `URLConvertible` and `URLRequestConvertible` protocols along with the `Router` design pattern are here to help. #### URLConvertible Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct URL requests internally. `String`, `URL`, and `URLComponents` conform to `URLConvertible` by default, allowing any of them to be passed as `url` parameters to the `request`, `upload`, and `download` methods: ```swift let urlString = "https://httpbin.org/post" Alamofire.request(urlString, method: .post) let url = URL(string: urlString)! Alamofire.request(url, method: .post) let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)! Alamofire.request(urlComponents, method: .post) ``` Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLConvertible` as a convenient way to map domain-specific models to server resources. ##### Type-Safe Routing ```swift extension User: URLConvertible { static let baseURLString = "https://example.com" func asURL() throws -> URL { let urlString = User.baseURLString + "/users/\(username)/" return try urlString.asURL() } } ``` ```swift let user = User(username: "mattt") Alamofire.request(user) // https://example.com/users/mattt ``` #### URLRequestConvertible Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. `URLRequest` conforms to `URLRequestConvertible` by default, allowing it to be passed into `request`, `upload`, and `download` methods directly (this is the recommended way to specify custom HTTP body for individual requests): ```swift let url = URL(string: "https://httpbin.org/post")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" let parameters = ["foo": "bar"] do { urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) } catch { // No-op } urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") Alamofire.request(urlRequest) ``` Applications interacting with web applications in a significant manner are encouraged to have custom types conform to `URLRequestConvertible` as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state. ##### API Parameter Abstraction ```swift enum Router: URLRequestConvertible { case search(query: String, page: Int) static let baseURLString = "https://example.com" static let perPage = 50 // MARK: URLRequestConvertible func asURLRequest() throws -> URLRequest { let result: (path: String, parameters: Parameters) = { switch self { case let .search(query, page) where page > 0: return ("/search", ["q": query, "offset": Router.perPage * page]) case let .search(query, _): return ("/search", ["q": query]) } }() let url = try Router.baseURLString.asURL() let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) return try URLEncoding.default.encode(urlRequest, with: result.parameters) } } ``` ```swift Alamofire.request(Router.search(query: "foo bar", page: 1)) // https://example.com/search?q=foo%20bar&offset=50 ``` ##### CRUD & Authorization ```swift import Alamofire enum Router: URLRequestConvertible { case createUser(parameters: Parameters) case readUser(username: String) case updateUser(username: String, parameters: Parameters) case destroyUser(username: String) static let baseURLString = "https://example.com" var method: HTTPMethod { switch self { case .createUser: return .post case .readUser: return .get case .updateUser: return .put case .destroyUser: return .delete } } var path: String { switch self { case .createUser: return "/users" case .readUser(let username): return "/users/\(username)" case .updateUser(let username, _): return "/users/\(username)" case .destroyUser(let username): return "/users/\(username)" } } // MARK: URLRequestConvertible func asURLRequest() throws -> URLRequest { let url = try Router.baseURLString.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(path)) urlRequest.httpMethod = method.rawValue switch self { case .createUser(let parameters): urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) case .updateUser(_, let parameters): urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters) default: break } return urlRequest } } ``` ```swift Alamofire.request(Router.readUser("mattt")) // GET https://example.com/users/mattt ``` ### Adapting and Retrying Requests Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered. The `RequestAdapter` and `RequestRetrier` protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services. #### RequestAdapter The `RequestAdapter` protocol allows each `Request` made on a `SessionManager` to be inspected and adapted before being created. One very specific way to use an adapter is to append an `Authorization` header to requests behind a certain type of authentication. ```swift class AccessTokenAdapter: RequestAdapter { private let accessToken: String init(accessToken: String) { self.accessToken = accessToken } func adapt(_ urlRequest: URLRequest) throws -> URLRequest { var urlRequest = urlRequest if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") { urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") } return urlRequest } } ``` ```swift let sessionManager = SessionManager() sessionManager.adapter = AccessTokenAdapter(accessToken: "1234") sessionManager.request("https://httpbin.org/get") ``` #### RequestRetrier The `RequestRetrier` protocol allows a `Request` that encountered an `Error` while being executed to be retried. When using both the `RequestAdapter` and `RequestRetrier` protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens. > **DISCLAIMER:** This is **NOT** a global `OAuth2` solution. It is merely an example demonstrating how one could use the `RequestAdapter` in conjunction with the `RequestRetrier` to create a thread-safe refresh system. > To reiterate, **do NOT copy** this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type. ```swift class OAuth2Handler: RequestAdapter, RequestRetrier { private typealias RefreshCompletion = (_ succeeded: Bool, _ accessToken: String?, _ refreshToken: String?) -> Void private let sessionManager: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() private let lock = NSLock() private var clientID: String private var baseURLString: String private var accessToken: String private var refreshToken: String private var isRefreshing = false private var requestsToRetry: [RequestRetryCompletion] = [] // MARK: - Initialization public init(clientID: String, baseURLString: String, accessToken: String, refreshToken: String) { self.clientID = clientID self.baseURLString = baseURLString self.accessToken = accessToken self.refreshToken = refreshToken } // MARK: - RequestAdapter func adapt(_ urlRequest: URLRequest) throws -> URLRequest { if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) { var urlRequest = urlRequest urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization") return urlRequest } return urlRequest } // MARK: - RequestRetrier func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { requestsToRetry.append(completion) if !isRefreshing { refreshTokens { [weak self] succeeded, accessToken, refreshToken in guard let strongSelf = self else { return } strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } if let accessToken = accessToken, let refreshToken = refreshToken { strongSelf.accessToken = accessToken strongSelf.refreshToken = refreshToken } strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } strongSelf.requestsToRetry.removeAll() } } } else { completion(false, 0.0) } } // MARK: - Private - Refresh Tokens private func refreshTokens(completion: @escaping RefreshCompletion) { guard !isRefreshing else { return } isRefreshing = true let urlString = "\(baseURLString)/oauth2/token" let parameters: [String: Any] = [ "access_token": accessToken, "refresh_token": refreshToken, "client_id": clientID, "grant_type": "refresh_token" ] sessionManager.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { [weak self] response in guard let strongSelf = self else { return } if let json = response.result.value as? [String: Any], let accessToken = json["access_token"] as? String, let refreshToken = json["refresh_token"] as? String { completion(true, accessToken, refreshToken) } else { completion(false, nil, nil) } strongSelf.isRefreshing = false } } } ``` ```swift let baseURLString = "https://some.domain-behind-oauth2.com" let oauthHandler = OAuth2Handler( clientID: "12345678", baseURLString: baseURLString, accessToken: "abcd1234", refreshToken: "ef56789a" ) let sessionManager = SessionManager() sessionManager.adapter = oauthHandler sessionManager.retrier = oauthHandler let urlString = "\(baseURLString)/some/endpoint" sessionManager.request(urlString).validate().responseJSON { response in debugPrint(response) } ``` Once the `OAuth2Handler` is applied as both the `adapter` and `retrier` for the `SessionManager`, it will handle an invalid access token error by automatically refreshing the access token and retrying all failed requests in the same order they failed. > If you needed them to execute in the same order they were created, you could sort them by their task identifiers. The example above only checks for a `401` response code which is not nearly robust enough, but does demonstrate how one could check for an invalid access token error. In a production application, one would want to check the `realm` and most likely the `www-authenticate` header response although it depends on the OAuth2 implementation. Another important note is that this authentication system could be shared between multiple session managers. For example, you may need to use both a `default` and `ephemeral` session configuration for the same set of web services. The example above allows the same `oauthHandler` instance to be shared across multiple session managers to manage the single refresh flow. ### Custom Response Serialization #### Handling Errors Before implementing custom response serializers or object serialization methods, it's important to consider how to handle any errors that may occur. There are two basic options: passing existing errors along unmodified, to be dealt with at response time; or, wrapping all errors in an `Error` type specific to your app. For example, here's a simple `BackendError` enum which will be used in later examples: ```swift enum BackendError: Error { case network(error: Error) // Capture any underlying Error from the URLSession API case dataSerialization(error: Error) case jsonSerialization(error: Error) case xmlSerialization(error: Error) case objectSerialization(reason: String) } ``` #### Creating a Custom Response Serializer Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on `Alamofire.DataRequest` and / or `Alamofire.DownloadRequest`. For example, here's how a response handler using [Ono](https://github.com/mattt/Ono) might be implemented: ```swift extension DataRequest { static func xmlResponseSerializer() -> DataResponseSerializer { return DataResponseSerializer { request, response, data, error in // Pass through any underlying URLSession error to the .network case. guard error == nil else { return .failure(BackendError.network(error: error!)) } // Use Alamofire's existing data serializer to extract the data, passing the error as nil, as it has // already been handled. let result = Request.serializeResponseData(response: response, data: data, error: nil) guard case let .success(validData) = result else { return .failure(BackendError.dataSerialization(error: result.error! as! AFError)) } do { let xml = try ONOXMLDocument(data: validData) return .success(xml) } catch { return .failure(BackendError.xmlSerialization(error: error)) } } } @discardableResult func responseXMLDocument( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.xmlResponseSerializer(), completionHandler: completionHandler ) } } ``` #### Generic Response Object Serialization Generics can be used to provide automatic, type-safe response object serialization. ```swift protocol ResponseObjectSerializable { init?(response: HTTPURLResponse, representation: Any) } extension DataRequest { func responseObject( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { let responseSerializer = DataResponseSerializer { request, response, data, error in guard error == nil else { return .failure(BackendError.network(error: error!)) } let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = jsonResponseSerializer.serializeResponse(request, response, data, nil) guard case let .success(jsonObject) = result else { return .failure(BackendError.jsonSerialization(error: result.error!)) } guard let response = response, let responseObject = T(response: response, representation: jsonObject) else { return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)")) } return .success(responseObject) } return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler) } } ``` ```swift struct User: ResponseObjectSerializable, CustomStringConvertible { let username: String let name: String var description: String { return "User: { username: \(username), name: \(name) }" } init?(response: HTTPURLResponse, representation: Any) { guard let username = response.url?.lastPathComponent, let representation = representation as? [String: Any], let name = representation["name"] as? String else { return nil } self.username = username self.name = name } } ``` ```swift Alamofire.request("https://example.com/users/mattt").responseObject { (response: DataResponse) in debugPrint(response) if let user = response.result.value { print("User: { username: \(user.username), name: \(user.name) }") } } ``` The same approach can also be used to handle endpoints that return a representation of a collection of objects: ```swift protocol ResponseCollectionSerializable { static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] } extension ResponseCollectionSerializable where Self: ResponseObjectSerializable { static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] { var collection: [Self] = [] if let representation = representation as? [[String: Any]] { for itemRepresentation in representation { if let item = Self(response: response, representation: itemRepresentation) { collection.append(item) } } } return collection } } ``` ```swift extension DataRequest { @discardableResult func responseCollection( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self { let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in guard error == nil else { return .failure(BackendError.network(error: error!)) } let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments) let result = jsonSerializer.serializeResponse(request, response, data, nil) guard case let .success(jsonObject) = result else { return .failure(BackendError.jsonSerialization(error: result.error!)) } guard let response = response else { let reason = "Response collection could not be serialized due to nil response." return .failure(BackendError.objectSerialization(reason: reason)) } return .success(T.collection(from: response, withRepresentation: jsonObject)) } return response(responseSerializer: responseSerializer, completionHandler: completionHandler) } } ``` ```swift struct User: ResponseObjectSerializable, ResponseCollectionSerializable, CustomStringConvertible { let username: String let name: String var description: String { return "User: { username: \(username), name: \(name) }" } init?(response: HTTPURLResponse, representation: Any) { guard let username = response.url?.lastPathComponent, let representation = representation as? [String: Any], let name = representation["name"] as? String else { return nil } self.username = username self.name = name } } ``` ```swift Alamofire.request("https://example.com/users").responseCollection { (response: DataResponse<[User]>) in debugPrint(response) if let users = response.result.value { users.forEach { print("- \($0)") } } } ``` ### Security Using a secure HTTPS connection when communicating with servers and web services is an important step in securing sensitive data. By default, Alamofire will evaluate the certificate chain provided by the server using Apple's built in validation provided by the Security framework. While this guarantees the certificate chain is valid, it does not prevent man-in-the-middle (MITM) attacks or other potential vulnerabilities. In order to mitigate MITM attacks, applications dealing with sensitive customer data or financial information should use certificate or public key pinning provided by the `ServerTrustPolicy`. #### ServerTrustPolicy The `ServerTrustPolicy` enumeration evaluates the server trust generally provided by an `URLAuthenticationChallenge` when connecting to a server over a secure HTTPS connection. ```swift let serverTrustPolicy = ServerTrustPolicy.pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true ) ``` There are many different cases of server trust evaluation giving you complete control over the validation process: * `performDefaultEvaluation`: Uses the default server trust evaluation while allowing you to control whether to validate the host provided by the challenge. * `pinCertificates`: Uses the pinned certificates to validate the server trust. The server trust is considered valid if one of the pinned certificates match one of the server certificates. * `pinPublicKeys`: Uses the pinned public keys to validate the server trust. The server trust is considered valid if one of the pinned public keys match one of the server certificate public keys. * `disableEvaluation`: Disables all evaluation which in turn will always consider any server trust as valid. * `customEvaluation`: Uses the associated closure to evaluate the validity of the server trust thus giving you complete control over the validation process. Use with caution. #### Server Trust Policy Manager The `ServerTrustPolicyManager` is responsible for storing an internal mapping of server trust policies to a particular host. This allows Alamofire to evaluate each host against a different server trust policy. ```swift let serverTrustPolicies: [String: ServerTrustPolicy] = [ "test.example.com": .pinCertificates( certificates: ServerTrustPolicy.certificatesInBundle(), validateCertificateChain: true, validateHost: true ), "insecure.expired-apis.com": .disableEvaluation ] let sessionManager = SessionManager( serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) ) ``` > Make sure to keep a reference to the new `SessionManager` instance, otherwise your requests will all get cancelled when your `sessionManager` is deallocated. These server trust policies will result in the following behavior: - `test.example.com` will always use certificate pinning with certificate chain and host validation enabled thus requiring the following criteria to be met to allow the TLS handshake to succeed: - Certificate chain MUST be valid. - Certificate chain MUST include one of the pinned certificates. - Challenge host MUST match the host in the certificate chain's leaf certificate. - `insecure.expired-apis.com` will never evaluate the certificate chain and will always allow the TLS handshake to succeed. - All other hosts will use the default evaluation provided by Apple. ##### Subclassing Server Trust Policy Manager If you find yourself needing more flexible server trust policy matching behavior (i.e. wildcarded domains), then subclass the `ServerTrustPolicyManager` and override the `serverTrustPolicyForHost` method with your own custom implementation. ```swift class CustomServerTrustPolicyManager: ServerTrustPolicyManager { override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { var policy: ServerTrustPolicy? // Implement your custom domain matching behavior... return policy } } ``` #### Validating the Host The `.performDefaultEvaluation`, `.pinCertificates` and `.pinPublicKeys` server trust policies all take a `validateHost` parameter. Setting the value to `true` will cause the server trust evaluation to verify that hostname in the certificate matches the hostname of the challenge. If they do not match, evaluation will fail. A `validateHost` value of `false` will still evaluate the full certificate chain, but will not validate the hostname of the leaf certificate. > It is recommended that `validateHost` always be set to `true` in production environments. #### Validating the Certificate Chain Pinning certificates and public keys both have the option of validating the certificate chain using the `validateCertificateChain` parameter. By setting this value to `true`, the full certificate chain will be evaluated in addition to performing a byte equality check against the pinned certificates or public keys. A value of `false` will skip the certificate chain validation, but will still perform the byte equality check. There are several cases where it may make sense to disable certificate chain validation. The most common use cases for disabling validation are self-signed and expired certificates. The evaluation would always fail in both of these cases, but the byte equality check will still ensure you are receiving the certificate you expect from the server. > It is recommended that `validateCertificateChain` always be set to `true` in production environments. #### App Transport Security With the addition of App Transport Security (ATS) in iOS 9, it is possible that using a custom `ServerTrustPolicyManager` with several `ServerTrustPolicy` objects will have no effect. If you continuously see `CFNetwork SSLHandshake failed (-9806)` errors, you have probably run into this problem. Apple's ATS system overrides the entire challenge system unless you configure the ATS settings in your app's plist to disable enough of it to allow your app to evaluate the server trust. If you run into this problem (high probability with self-signed certificates), you can work around this issue by adding the following to your `Info.plist`. ```xml NSAppTransportSecurity NSExceptionDomains example.com NSExceptionAllowsInsecureHTTPLoads NSExceptionRequiresForwardSecrecy NSIncludesSubdomains NSTemporaryExceptionMinimumTLSVersion TLSv1.2 ``` Whether you need to set the `NSExceptionRequiresForwardSecrecy` to `NO` depends on whether your TLS connection is using an allowed cipher suite. In certain cases, it will need to be set to `NO`. The `NSExceptionAllowsInsecureHTTPLoads` MUST be set to `YES` in order to allow the `SessionDelegate` to receive challenge callbacks. Once the challenge callbacks are being called, the `ServerTrustPolicyManager` will take over the server trust evaluation. You may also need to specify the `NSTemporaryExceptionMinimumTLSVersion` if you're trying to connect to a host that only supports TLS versions less than `1.2`. > It is recommended to always use valid certificates in production environments. ### Network Reachability The `NetworkReachabilityManager` listens for reachability changes of hosts and addresses for both WWAN and WiFi network interfaces. ```swift let manager = NetworkReachabilityManager(host: "www.apple.com") manager?.listener = { status in print("Network Status Changed: \(status)") } manager?.startListening() ``` > Make sure to remember to retain the `manager` in the above example, or no status changes will be reported. There are some important things to remember when using network reachability to determine what to do next. - **Do NOT** use Reachability to determine if a network request should be sent. - You should **ALWAYS** send it. - When Reachability is restored, use the event to retry failed network requests. - Even though the network requests may still fail, this is a good moment to retry them. - The network reachability status can be useful for determining why a network request may have failed. - If a network request fails, it is more useful to tell the user that the network request failed due to being offline rather than a more technical error, such as "request timed out." > It is recommended to check out [WWDC 2012 Session 706, "Networking Best Practices"](https://developer.apple.com/videos/play/wwdc2012-706/) for more info. --- ## Open Radars The following radars have some effect on the current implementation of Alamofire. - [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case - [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage - `rdar://26870455` - Background URL Session Configurations do not work in the simulator - `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` ## FAQ ### What's the origin of the name Alamofire? Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. ### What logic belongs in a Router vs. a Request Adapter? Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. --- ## Credits Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. ### Security Disclosure If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. ## Donations The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially register as a federal non-profit organization. Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. Donating to the ASF will enable us to: - Pay our legal fees to register as a federal non-profit organization - Pay our yearly legal fees to keep the non-profit in good status - Pay for our mail servers to help us stay on top of all questions and security issues - Potentially fund test servers to make it easier for us to test the edge cases - Potentially fund developers to work on one of our projects full-time The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Our initial goal is to raise $1000 to get all our legal ducks in a row and kickstart this campaign. Any amount you can donate today to help us reach our goal would be greatly appreciated. Click here to lend your support to: Alamofire Software Foundation and make a donation at pledgie.com ! ## License Alamofire is released under the MIT license. See LICENSE for details. ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/AFError.swift ================================================ // // AFError.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with /// their own associated reasons. /// /// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. /// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. /// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. /// - responseValidationFailed: Returned when a `validate()` call fails. /// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. public enum AFError: Error { /// The underlying reason the parameter encoding error occurred. /// /// - missingURL: The URL request did not have a URL to encode. /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the /// encoding process. /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during /// encoding process. public enum ParameterEncodingFailureReason { case missingURL case jsonEncodingFailed(error: Error) case propertyListEncodingFailed(error: Error) } /// The underlying reason the multipart encoding error occurred. /// /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a /// file URL. /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty /// `lastPathComponent` or `pathExtension. /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw /// an error. /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by /// the system. /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided /// threw an error. /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the /// encoded data to disk. /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file /// already exists at the provided `fileURL`. /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is /// not a file URL. /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an /// underlying error. /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with /// underlying system error. public enum MultipartEncodingFailureReason { case bodyPartURLInvalid(url: URL) case bodyPartFilenameInvalid(in: URL) case bodyPartFileNotReachable(at: URL) case bodyPartFileNotReachableWithError(atURL: URL, error: Error) case bodyPartFileIsDirectory(at: URL) case bodyPartFileSizeNotAvailable(at: URL) case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) case bodyPartInputStreamCreationFailed(for: URL) case outputStreamCreationFailed(for: URL) case outputStreamFileAlreadyExists(at: URL) case outputStreamURLInvalid(url: URL) case outputStreamWriteFailed(error: Error) case inputStreamReadFailed(error: Error) } /// The underlying reason the response validation error occurred. /// /// - dataFileNil: The data file containing the server response did not exist. /// - dataFileReadFailed: The data file containing the server response could not be read. /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` /// provided did not contain wildcard type. /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided /// `acceptableContentTypes`. /// - unacceptableStatusCode: The response status code was not acceptable. public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(code: Int) } /// The underlying reason the response serialization error occurred. /// /// - inputDataNil: The server response contained no data. /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. /// - inputFileNil: The file containing the server response did not exist. /// - inputFileReadFailed: The file containing the server response could not be read. /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. public enum ResponseSerializationFailureReason { case inputDataNil case inputDataNilOrZeroLength case inputFileNil case inputFileReadFailed(at: URL) case stringSerializationFailed(encoding: String.Encoding) case jsonSerializationFailed(error: Error) case propertyListSerializationFailed(error: Error) } case invalidURL(url: URLConvertible) case parameterEncodingFailed(reason: ParameterEncodingFailureReason) case multipartEncodingFailed(reason: MultipartEncodingFailureReason) case responseValidationFailed(reason: ResponseValidationFailureReason) case responseSerializationFailed(reason: ResponseSerializationFailureReason) } // MARK: - Adapt Error struct AdaptError: Error { let error: Error } extension Error { var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } } // MARK: - Error Booleans extension AFError { /// Returns whether the AFError is an invalid URL error. public var isInvalidURLError: Bool { if case .invalidURL = self { return true } return false } /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will /// contain the associated value. public var isParameterEncodingError: Bool { if case .parameterEncodingFailed = self { return true } return false } /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties /// will contain the associated values. public var isMultipartEncodingError: Bool { if case .multipartEncodingFailed = self { return true } return false } /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, /// `responseContentType`, and `responseCode` properties will contain the associated values. public var isResponseValidationError: Bool { if case .responseValidationFailed = self { return true } return false } /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and /// `underlyingError` properties will contain the associated values. public var isResponseSerializationError: Bool { if case .responseSerializationFailed = self { return true } return false } } // MARK: - Convenience Properties extension AFError { /// The `URLConvertible` associated with the error. public var urlConvertible: URLConvertible? { switch self { case .invalidURL(let url): return url default: return nil } } /// The `URL` associated with the error. public var url: URL? { switch self { case .multipartEncodingFailed(let reason): return reason.url default: return nil } } /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. public var underlyingError: Error? { switch self { case .parameterEncodingFailed(let reason): return reason.underlyingError case .multipartEncodingFailed(let reason): return reason.underlyingError case .responseSerializationFailed(let reason): return reason.underlyingError default: return nil } } /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. public var acceptableContentTypes: [String]? { switch self { case .responseValidationFailed(let reason): return reason.acceptableContentTypes default: return nil } } /// The response `Content-Type` of a `.responseValidationFailed` error. public var responseContentType: String? { switch self { case .responseValidationFailed(let reason): return reason.responseContentType default: return nil } } /// The response code of a `.responseValidationFailed` error. public var responseCode: Int? { switch self { case .responseValidationFailed(let reason): return reason.responseCode default: return nil } } /// The `String.Encoding` associated with a failed `.stringResponse()` call. public var failedStringEncoding: String.Encoding? { switch self { case .responseSerializationFailed(let reason): return reason.failedStringEncoding default: return nil } } } extension AFError.ParameterEncodingFailureReason { var underlyingError: Error? { switch self { case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): return error default: return nil } } } extension AFError.MultipartEncodingFailureReason { var url: URL? { switch self { case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): return url default: return nil } } var underlyingError: Error? { switch self { case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): return error default: return nil } } } extension AFError.ResponseValidationFailureReason { var acceptableContentTypes: [String]? { switch self { case .missingContentType(let types), .unacceptableContentType(let types, _): return types default: return nil } } var responseContentType: String? { switch self { case .unacceptableContentType(_, let responseType): return responseType default: return nil } } var responseCode: Int? { switch self { case .unacceptableStatusCode(let code): return code default: return nil } } } extension AFError.ResponseSerializationFailureReason { var failedStringEncoding: String.Encoding? { switch self { case .stringSerializationFailed(let encoding): return encoding default: return nil } } var underlyingError: Error? { switch self { case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): return error default: return nil } } } // MARK: - Error Descriptions extension AFError: LocalizedError { public var errorDescription: String? { switch self { case .invalidURL(let url): return "URL is not valid: \(url)" case .parameterEncodingFailed(let reason): return reason.localizedDescription case .multipartEncodingFailed(let reason): return reason.localizedDescription case .responseValidationFailed(let reason): return reason.localizedDescription case .responseSerializationFailed(let reason): return reason.localizedDescription } } } extension AFError.ParameterEncodingFailureReason { var localizedDescription: String { switch self { case .missingURL: return "URL request to encode was missing a URL" case .jsonEncodingFailed(let error): return "JSON could not be encoded because of error:\n\(error.localizedDescription)" case .propertyListEncodingFailed(let error): return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" } } } extension AFError.MultipartEncodingFailureReason { var localizedDescription: String { switch self { case .bodyPartURLInvalid(let url): return "The URL provided is not a file URL: \(url)" case .bodyPartFilenameInvalid(let url): return "The URL provided does not have a valid filename: \(url)" case .bodyPartFileNotReachable(let url): return "The URL provided is not reachable: \(url)" case .bodyPartFileNotReachableWithError(let url, let error): return ( "The system returned an error while checking the provided URL for " + "reachability.\nURL: \(url)\nError: \(error)" ) case .bodyPartFileIsDirectory(let url): return "The URL provided is a directory: \(url)" case .bodyPartFileSizeNotAvailable(let url): return "Could not fetch the file size from the provided URL: \(url)" case .bodyPartFileSizeQueryFailedWithError(let url, let error): return ( "The system returned an error while attempting to fetch the file size from the " + "provided URL.\nURL: \(url)\nError: \(error)" ) case .bodyPartInputStreamCreationFailed(let url): return "Failed to create an InputStream for the provided URL: \(url)" case .outputStreamCreationFailed(let url): return "Failed to create an OutputStream for URL: \(url)" case .outputStreamFileAlreadyExists(let url): return "A file already exists at the provided URL: \(url)" case .outputStreamURLInvalid(let url): return "The provided OutputStream URL is invalid: \(url)" case .outputStreamWriteFailed(let error): return "OutputStream write failed with error: \(error)" case .inputStreamReadFailed(let error): return "InputStream read failed with error: \(error)" } } } extension AFError.ResponseSerializationFailureReason { var localizedDescription: String { switch self { case .inputDataNil: return "Response could not be serialized, input data was nil." case .inputDataNilOrZeroLength: return "Response could not be serialized, input data was nil or zero length." case .inputFileNil: return "Response could not be serialized, input file was nil." case .inputFileReadFailed(let url): return "Response could not be serialized, input file could not be read: \(url)." case .stringSerializationFailed(let encoding): return "String could not be serialized with encoding: \(encoding)." case .jsonSerializationFailed(let error): return "JSON could not be serialized because of error:\n\(error.localizedDescription)" case .propertyListSerializationFailed(let error): return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" } } } extension AFError.ResponseValidationFailureReason { var localizedDescription: String { switch self { case .dataFileNil: return "Response could not be validated, data file was nil." case .dataFileReadFailed(let url): return "Response could not be validated, data file could not be read: \(url)." case .missingContentType(let types): return ( "Response Content-Type was missing and acceptable content types " + "(\(types.joined(separator: ","))) do not match \"*/*\"." ) case .unacceptableContentType(let acceptableTypes, let responseType): return ( "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + "\(acceptableTypes.joined(separator: ","))." ) case .unacceptableStatusCode(let code): return "Response status code was unacceptable: \(code)." } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Alamofire.swift ================================================ // // Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct /// URL requests. public protocol URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. func asURL() throws -> URL } extension String: URLConvertible { /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. /// /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } return url } } extension URL: URLConvertible { /// Returns self. public func asURL() throws -> URL { return self } } extension URLComponents: URLConvertible { /// Returns a URL if `url` is not nil, otherise throws an `Error`. /// /// - throws: An `AFError.invalidURL` if `url` is `nil`. /// /// - returns: A URL or throws an `AFError`. public func asURL() throws -> URL { guard let url = url else { throw AFError.invalidURL(url: self) } return url } } // MARK: - /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. public protocol URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. /// /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// /// - returns: A URL request. func asURLRequest() throws -> URLRequest } extension URLRequestConvertible { /// The URL request. public var urlRequest: URLRequest? { return try? asURLRequest() } } extension URLRequest: URLRequestConvertible { /// Returns a URL request or throws if an `Error` was encountered. public func asURLRequest() throws -> URLRequest { return self } } // MARK: - extension URLRequest { /// Creates an instance with the specified `method`, `urlString` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The new `URLRequest` instance. public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { let url = try url.asURL() self.init(url: url) httpMethod = method.rawValue if let headers = headers { for (headerField, headerValue) in headers { setValue(headerValue, forHTTPHeaderField: headerField) } } } func adapt(using adapter: RequestAdapter?) throws -> URLRequest { guard let adapter = adapter else { return self } return try adapter.adapt(self) } } // MARK: - Data Request /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult public func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { return SessionManager.default.request( url, method: method, parameters: parameters, encoding: encoding, headers: headers ) } /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest`. /// /// - parameter urlRequest: The URL request /// /// - returns: The created `DataRequest`. @discardableResult public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { return SessionManager.default.request(urlRequest) } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download( url, method: method, parameters: parameters, encoding: encoding, headers: headers, to: destination ) } /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the /// specified `urlRequest` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// - parameter urlRequest: The URL request. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(urlRequest, to: destination) } // MARK: Resume Data /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional /// information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult public func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return SessionManager.default.download(resumingWith: resumeData, to: destination) } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) } /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `file`. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(fileURL, with: urlRequest) } // MARK: Data /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(data, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `data`. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(data, with: urlRequest) } // MARK: InputStream /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` /// for uploading the `stream`. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { return SessionManager.default.upload(stream, to: url, method: method, headers: headers) } /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for /// uploading the `stream`. /// /// - parameter urlRequest: The URL request. /// - parameter stream: The stream to upload. /// /// - returns: The created `UploadRequest`. @discardableResult public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { return SessionManager.default.upload(stream, with: urlRequest) } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, to: url, method: method, headers: headers, encodingCompletion: encodingCompletion ) } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. public func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { return SessionManager.default.upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` /// and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(withHostName hostName: String, port: Int) -> StreamRequest { return SessionManager.default.stream(withHostName: hostName, port: port) } // MARK: NetService /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) public func stream(with netService: NetService) -> StreamRequest { return SessionManager.default.stream(with: netService) } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift ================================================ // // DispatchQueue+Alamofire.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Dispatch import Foundation extension DispatchQueue { static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { asyncAfter(deadline: .now() + delay, execute: closure) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/MultipartFormData.swift ================================================ // // MultipartFormData.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(macOS) import CoreServices #endif /// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode /// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead /// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the /// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for /// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. /// /// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well /// and the w3 form documentation. /// /// - https://www.ietf.org/rfc/rfc2388.txt /// - https://www.ietf.org/rfc/rfc2045.txt /// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 open class MultipartFormData { // MARK: - Helper Types struct EncodingCharacters { static let crlf = "\r\n" } struct BoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func randomBoundary() -> String { return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { case .initial: boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" case .encapsulated: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" case .final: boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" } return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } class BodyPart { let headers: HTTPHeaders let bodyStream: InputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BodyPart] private var bodyPartError: AFError? private let streamBufferSize: Int // MARK: - Lifecycle /// Creates a multipart form data object. /// /// - returns: The multipart form data object. public init() { self.boundary = BoundaryGenerator.randomBoundary() self.bodyParts = [] /// /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more /// information, please refer to the following article: /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html /// self.streamBufferSize = 1024 } // MARK: - Body Parts /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. public func append(_ data: Data, withName name: String) { let headers = contentHeaders(withName: name) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, mimeType: String) { let headers = contentHeaders(withName: name, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the data and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter data: The data to encode into the multipart form data. /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) /// - `Content-Type: #{generated mimeType}` (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the /// system associated MIME type. /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. public func append(_ fileURL: URL, withName name: String) { let fileName = fileURL.lastPathComponent let pathExtension = fileURL.pathExtension if !fileName.isEmpty && !pathExtension.isEmpty { let mime = mimeType(forPathExtension: pathExtension) append(fileURL, withName: name, fileName: fileName, mimeType: mime) } else { setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) } } /// Creates a body part from the file and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) /// - Content-Type: #{mimeType} (HTTP Header) /// - Encoded file data /// - Multipart form boundary /// /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) //============================================================ // Check 1 - is file URL? //============================================================ guard fileURL.isFileURL else { setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) return } //============================================================ // Check 2 - is file URL reachable? //============================================================ do { let isReachable = try fileURL.checkPromisedItemIsReachable() guard isReachable else { setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) return } } catch { setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) return } //============================================================ // Check 3 - is file URL a directory? //============================================================ var isDirectory: ObjCBool = false let path = fileURL.path guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) return } //============================================================ // Check 4 - can the file size be extracted? //============================================================ let bodyContentLength: UInt64 do { guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) return } bodyContentLength = fileSize.uint64Value } catch { setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) return } //============================================================ // Check 5 - can a stream be created from file URL? //============================================================ guard let stream = InputStream(url: fileURL) else { setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) return } append(stream, withLength: bodyContentLength, headers: headers) } /// Creates a body part from the stream and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) /// - `Content-Type: #{mimeType}` (HTTP Header) /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. public func append( _ stream: InputStream, withLength length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) append(stream, withLength: length, headers: headers) } /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. /// /// The body part data will be encoded using the following format: /// /// - HTTP headers /// - Encoded stream data /// - Multipart form boundary /// /// - parameter stream: The input stream to encode in the multipart form data. /// - parameter length: The content length of the stream. /// - parameter headers: The HTTP headers for the body part. public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } // MARK: - Data Encoding /// Encodes all the appended body parts into a single `Data` value. /// /// It is important to note that this method will load all the appended body parts into memory all at the same /// time. This method should only be used when the encoded data will have a small memory footprint. For large data /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. /// /// - throws: An `AFError` if encoding encounters an error. /// /// - returns: The encoded `Data` if encoding is successful. public func encode() throws -> Data { if let bodyPartError = bodyPartError { throw bodyPartError } var encoded = Data() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encode(bodyPart) encoded.append(encodedData) } return encoded } /// Writes the appended body parts into the given file URL. /// /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, /// this approach is very memory efficient and should be used for large body part data. /// /// - parameter fileURL: The file URL to write the multipart form data into. /// /// - throws: An `AFError` if encoding encounters an error. public func writeEncodedData(to fileURL: URL) throws { if let bodyPartError = bodyPartError { throw bodyPartError } if FileManager.default.fileExists(atPath: fileURL.path) { throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) } else if !fileURL.isFileURL { throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) } guard let outputStream = OutputStream(url: fileURL, append: false) else { throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) } outputStream.open() defer { outputStream.close() } self.bodyParts.first?.hasInitialBoundary = true self.bodyParts.last?.hasFinalBoundary = true for bodyPart in self.bodyParts { try write(bodyPart, to: outputStream) } } // MARK: - Private - Body Part Encoding private func encode(_ bodyPart: BodyPart) throws -> Data { var encoded = Data() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.append(initialData) let headerData = encodeHeaders(for: bodyPart) encoded.append(headerData) let bodyStreamData = try encodeBodyStream(for: bodyPart) encoded.append(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.append(finalBoundaryData()) } return encoded } private func encodeHeaders(for bodyPart: BodyPart) -> Data { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(EncodingCharacters.crlf)" } headerText += EncodingCharacters.crlf return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let error = inputStream.streamError { throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) } if bytesRead > 0 { encoded.append(buffer, count: bytesRead) } else { break } } return encoded } // MARK: - Private - Writing Body Part to Output Stream private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { try writeInitialBoundaryData(for: bodyPart, to: outputStream) try writeHeaderData(for: bodyPart, to: outputStream) try writeBodyStream(for: bodyPart, to: outputStream) try writeFinalBoundaryData(for: bodyPart, to: outputStream) } private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() return try write(initialData, to: outputStream) } private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let headerData = encodeHeaders(for: bodyPart) return try write(headerData, to: outputStream) } private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let streamError = inputStream.streamError { throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) } if bytesRead > 0 { if buffer.count != bytesRead { buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) if let error = outputStream.streamError { throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) } bytesToWrite -= bytesWritten if bytesToWrite > 0 { buffer = Array(buffer[bytesWritten.. String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { var disposition = "form-data; name=\"\(name)\"" if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } var headers = ["Content-Disposition": disposition] if let mimeType = mimeType { headers["Content-Type"] = mimeType } return headers } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) } private func encapsulatedBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) } private func finalBoundaryData() -> Data { return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) } // MARK: - Private - Errors private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { guard bodyPartError == nil else { return } bodyPartError = AFError.multipartEncodingFailed(reason: reason) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/NetworkReachabilityManager.swift ================================================ // // NetworkReachabilityManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) import Foundation import SystemConfiguration /// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and /// WiFi network interfaces. /// /// Reachability can be used to determine background information about why a network operation failed, or to retry /// network requests when a connection is established. It should not be used to prevent a user from initiating a network /// request, as it's possible that an initial request may be required to establish reachability. public class NetworkReachabilityManager { /// Defines the various states of network reachability. /// /// - unknown: It is unknown whether the network is reachable. /// - notReachable: The network is not reachable. /// - reachable: The network is reachable. public enum NetworkReachabilityStatus { case unknown case notReachable case reachable(ConnectionType) } /// Defines the various connection types detected by reachability flags. /// /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. /// - wwan: The connection type is a WWAN connection. public enum ConnectionType { case ethernetOrWiFi case wwan } /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void // MARK: - Properties /// Whether the network is currently reachable. public var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } /// Whether the network is currently reachable over the WWAN interface. public var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } /// Whether the network is currently reachable over Ethernet or WiFi interface. public var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } /// The current network reachability status. public var networkReachabilityStatus: NetworkReachabilityStatus { guard let flags = self.flags else { return .unknown } return networkReachabilityStatusForFlags(flags) } /// The dispatch queue to execute the `listener` closure on. public var listenerQueue: DispatchQueue = DispatchQueue.main /// A closure executed when the network reachability status changes. public var listener: Listener? private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachability, &flags) { return flags } return nil } private let reachability: SCNetworkReachability private var previousFlags: SCNetworkReachabilityFlags // MARK: - Initialization /// Creates a `NetworkReachabilityManager` instance with the specified host. /// /// - parameter host: The host used to evaluate network reachability. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?(host: String) { guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } self.init(reachability: reachability) } /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. /// /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing /// status of the device, both IPv4 and IPv6. /// /// - returns: The new `NetworkReachabilityManager` instance. public convenience init?() { var address = sockaddr_in() address.sin_len = UInt8(MemoryLayout.size) address.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(to: &address, { pointer in return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { return SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return nil } self.init(reachability: reachability) } private init(reachability: SCNetworkReachability) { self.reachability = reachability self.previousFlags = SCNetworkReachabilityFlags() } deinit { stopListening() } // MARK: - Listening /// Starts listening for changes in network reachability status. /// /// - returns: `true` if listening was started successfully, `false` otherwise. @discardableResult public func startListening() -> Bool { var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = Unmanaged.passUnretained(self).toOpaque() let callbackEnabled = SCNetworkReachabilitySetCallback( reachability, { (_, flags, info) in let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() reachability.notifyListener(flags) }, &context ) let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) listenerQueue.async { self.previousFlags = SCNetworkReachabilityFlags() self.notifyListener(self.flags ?? SCNetworkReachabilityFlags()) } return callbackEnabled && queueEnabled } /// Stops listening for changes in network reachability status. public func stopListening() { SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) } // MARK: - Internal - Listener Notification func notifyListener(_ flags: SCNetworkReachabilityFlags) { guard previousFlags != flags else { return } previousFlags = flags listener?(networkReachabilityStatusForFlags(flags)) } // MARK: - Internal - Network Reachability Status func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { guard flags.contains(.reachable) else { return .notReachable } var networkStatus: NetworkReachabilityStatus = .notReachable if !flags.contains(.connectionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) { if !flags.contains(.interventionRequired) { networkStatus = .reachable(.ethernetOrWiFi) } } #if os(iOS) if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } #endif return networkStatus } } // MARK: - extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} /// Returns whether the two network reachability status values are equal. /// /// - parameter lhs: The left-hand side value to compare. /// - parameter rhs: The right-hand side value to compare. /// /// - returns: `true` if the two values are equal, `false` otherwise. public func ==( lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown): return true case (.notReachable, .notReachable): return true case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): return lhsConnectionType == rhsConnectionType default: return false } } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Notifications.swift ================================================ // // Notifications.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Notification.Name { /// Used as a namespace for all `URLSessionTask` related notifications. public struct Task { /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") } } // MARK: - extension Notification { /// Used as a namespace for all `Notification` user info dictionary keys. public struct Key { /// User info dictionary key representing the `URLSessionTask` associated with the notification. public static let Task = "org.alamofire.notification.key.task" } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/ParameterEncoding.swift ================================================ // // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode /// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending /// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent) { self.destination = destination } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: "\(key)[]", value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape((value.boolValue ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape((bool ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex.. String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. /// /// - parameter urlRequest: The request to apply the JSON object to. /// - parameter jsonObject: The JSON object to apply to the request. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header /// field of an encoded request is set to `application/x-plist`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Request.swift ================================================ // // Request.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asychronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } /// The number of times the request has been retried. open internal(set) var retryCount: UInt = 0 let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.sync { session.dataTask(with: urlRequest) } } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let requestable = originalTask as? Requestable { return requestable.urlRequest } return nil } /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.sync { session.downloadTask(withResumeData: resumeData) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { return urlRequest } return nil } /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } guard let uploadable = originalTask as? Uploadable else { return nil } switch uploadable { case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): return urlRequest } } /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.sync { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.sync { session.streamTask(with: netService) } } return task } } } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Response.swift ================================================ // // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/ResponseSerialization.swift ================================================ // // ResponseSerialization.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The type in which all data response serializers must conform to in order to serialize a response. public protocol DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, data and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } } // MARK: - /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DataResponseSerializer: DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, data and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { self.serializeResponse = serializeResponse } } // MARK: - /// The type in which all download response serializers must conform to in order to serialize a response. public protocol DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, url and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } } // MARK: - /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, url and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { self.serializeResponse = serializeResponse } } // MARK: - Timeline extension Request { var timeline: Timeline { let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime return Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) } } // MARK: - Default extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var dataResponse = DefaultDataResponse( request: self.request, response: self.response, data: self.delegate.data, error: self.delegate.error, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) completionHandler(dataResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DataResponse) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) var dataResponse = DataResponse( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } } return self } } extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDownloadResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var downloadResponse = DefaultDownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, error: self.downloadDelegate.error, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) completionHandler(downloadResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data contained in the destination url. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.downloadDelegate.fileURL, self.downloadDelegate.error ) var downloadResponse = DownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, result: result, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self } } // MARK: - Data extension Request { /// Returns a result data type that contains the response data as-is. /// /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return .success(validData) } } extension DataRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseData(response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseData(response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } // MARK: - String extension Request { /// Returns a result string type initialized from the response data with the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } } extension DataRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(json) } catch { return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /// Returns a plist object contained in a result type constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponsePropertyList( options: PropertyListSerialization.ReadOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) return .success(plist) } catch { return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DownloadResponseSerializer { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DownloadResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set = [204, 205] ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Result.swift ================================================ // // Result.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to represent whether a request was successful or encountered an error. /// /// - success: The request and all post processing operations were successful resulting in the serialization of the /// provided associated value. /// /// - failure: The request encountered an error resulting in a failure. The associated values are the original data /// provided by the server as well as the error that caused the failure. public enum Result { case success(Value) case failure(Error) /// Returns `true` if the result is a success, `false` otherwise. public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } /// Returns `true` if the result is a failure, `false` otherwise. public var isFailure: Bool { return !isSuccess } /// Returns the associated value if the result is a success, `nil` otherwise. public var value: Value? { switch self { case .success(let value): return value case .failure: return nil } } /// Returns the associated error value if the result is a failure, `nil` otherwise. public var error: Error? { switch self { case .success: return nil case .failure(let error): return error } } } // MARK: - CustomStringConvertible extension Result: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { switch self { case .success: return "SUCCESS" case .failure: return "FAILURE" } } } // MARK: - CustomDebugStringConvertible extension Result: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes whether the result was a /// success or failure in addition to the value or error. public var debugDescription: String { switch self { case .success(let value): return "SUCCESS: \(value)" case .failure(let error): return "FAILURE: \(error)" } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/ServerTrustPolicy.swift ================================================ // // ServerTrustPolicy.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. open class ServerTrustPolicyManager { /// The dictionary of policies mapped to a particular host. open let policies: [String: ServerTrustPolicy] /// Initializes the `ServerTrustPolicyManager` instance with the given policies. /// /// Since different servers and web services can have different leaf certificates, intermediate and even root /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key /// pinning for host3 and disabling evaluation for host4. /// /// - parameter policies: A dictionary of all policies mapped to a particular host. /// /// - returns: The new `ServerTrustPolicyManager` instance. public init(policies: [String: ServerTrustPolicy]) { self.policies = policies } /// Returns the `ServerTrustPolicy` for the given host if applicable. /// /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override /// this method and implement more complex mapping implementations such as wildcards. /// /// - parameter host: The host to use when searching for a matching policy. /// /// - returns: The server trust policy for the given host if found. open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { return policies[host] } } // MARK: - extension URLSession { private struct AssociatedKeys { static var managerKey = "URLSession.ServerTrustPolicyManager" } var serverTrustPolicyManager: ServerTrustPolicyManager? { get { return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager } set (manager) { objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - ServerTrustPolicy /// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when /// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust /// with a given set of criteria to determine whether the server trust is valid and the connection should be made. /// /// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other /// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged /// to route all communication over an HTTPS connection with pinning enabled. /// /// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to /// validate the host provided by the challenge. Applications are encouraged to always /// validate the host in production environments to guarantee the validity of the server's /// certificate chain. /// /// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to /// validate the host provided by the challenge as well as specify the revocation flags for /// testing for revoked certificates. Apple platforms did not start testing for revoked /// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is /// demonstrated in our TLS tests. Applications are encouraged to always validate the host /// in production environments to guarantee the validity of the server's certificate chain. /// /// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is /// considered valid if one of the pinned certificates match one of the server certificates. /// By validating both the certificate chain and host, certificate pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered /// valid if one of the pinned public keys match one of the server certificate public keys. /// By validating both the certificate chain and host, public key pinning provides a very /// secure form of server trust validation mitigating most, if not all, MITM attacks. /// Applications are encouraged to always validate the host and require a valid certificate /// chain in production environments. /// /// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. /// /// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. public enum ServerTrustPolicy { case performDefaultEvaluation(validateHost: Bool) case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) case disableEvaluation case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) // MARK: - Bundle Location /// Returns all certificates within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `.cer` files. /// /// - returns: All certificates within the given bundle. public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { var certificates: [SecCertificate] = [] let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) }.joined()) for path in paths { if let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, let certificate = SecCertificateCreateWithData(nil, certificateData) { certificates.append(certificate) } } return certificates } /// Returns all public keys within the given bundle with a `.cer` file extension. /// /// - parameter bundle: The bundle to search for all `*.cer` files. /// /// - returns: All public keys within the given bundle. public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { var publicKeys: [SecKey] = [] for certificate in certificates(in: bundle) { if let publicKey = publicKey(for: certificate) { publicKeys.append(publicKey) } } return publicKeys } // MARK: - Evaluation /// Evaluates whether the server trust is valid for the given host. /// /// - parameter serverTrust: The server trust to evaluate. /// - parameter host: The host of the challenge protection space. /// /// - returns: Whether the server trust is valid. public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { var serverTrustIsValid = false switch self { case let .performDefaultEvaluation(validateHost): let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) serverTrustIsValid = trustIsValid(serverTrust) case let .performRevokedEvaluation(validateHost, revocationFlags): let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) serverTrustIsValid = trustIsValid(serverTrust) case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) SecTrustSetAnchorCertificatesOnly(serverTrust, true) serverTrustIsValid = trustIsValid(serverTrust) } else { let serverCertificatesDataArray = certificateData(for: serverTrust) let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) outerLoop: for serverCertificateData in serverCertificatesDataArray { for pinnedCertificateData in pinnedCertificatesDataArray { if serverCertificateData == pinnedCertificateData { serverTrustIsValid = true break outerLoop } } } } case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): var certificateChainEvaluationPassed = true if validateCertificateChain { let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) SecTrustSetPolicies(serverTrust, policy) certificateChainEvaluationPassed = trustIsValid(serverTrust) } if certificateChainEvaluationPassed { outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { if serverPublicKey.isEqual(pinnedPublicKey) { serverTrustIsValid = true break outerLoop } } } } case .disableEvaluation: serverTrustIsValid = true case let .customEvaluation(closure): serverTrustIsValid = closure(serverTrust, host) } return serverTrustIsValid } // MARK: - Private - Trust Validation private func trustIsValid(_ trust: SecTrust) -> Bool { var isValid = false var result = SecTrustResultType.invalid let status = SecTrustEvaluate(trust, &result) if status == errSecSuccess { let unspecified = SecTrustResultType.unspecified let proceed = SecTrustResultType.proceed isValid = result == unspecified || result == proceed } return isValid } // MARK: - Private - Certificate Data private func certificateData(for trust: SecTrust) -> [Data] { var certificates: [SecCertificate] = [] for index in 0.. [Data] { return certificates.map { SecCertificateCopyData($0) as Data } } // MARK: - Private - Public Key Extraction private static func publicKeys(for trust: SecTrust) -> [SecKey] { var publicKeys: [SecKey] = [] for index in 0.. SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/SessionDelegate.swift ================================================ // // SessionDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for handling all delegate callbacks for the underlying session. open class SessionDelegate: NSObject { // MARK: URLSessionDelegate Overrides /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? // MARK: URLSessionTaskDelegate Overrides /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and /// requires the caller to call the `completionHandler`. open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? // MARK: URLSessionDataDelegate Overrides /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)? // MARK: URLSessionDownloadDelegate Overrides /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: URLSessionStreamDelegate Overrides #if !os(watchOS) /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? #endif // MARK: Properties var retrier: RequestRetrier? weak var sessionManager: SessionManager? private var requests: [Int: Request] = [:] private let lock = NSLock() /// Access the task delegate for the specified task in a thread-safe manner. open subscript(task: URLSessionTask) -> Request? { get { lock.lock() ; defer { lock.unlock() } return requests[task.taskIdentifier] } set { lock.lock() ; defer { lock.unlock() } requests[task.taskIdentifier] = newValue } } // MARK: Lifecycle /// Initializes the `SessionDelegate` instance. /// /// - returns: The new `SessionDelegate` instance. public override init() { super.init() } // MARK: NSObject Overrides /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond /// to a specified message. /// /// - parameter selector: A selector that identifies a message. /// /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. open override func responds(to selector: Selector) -> Bool { #if !os(macOS) if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif #if !os(watchOS) if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { switch selector { case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): return streamTaskReadClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): return streamTaskWriteClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): return streamTaskBetterRouteDiscovered != nil case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): return streamTaskDidBecomeInputAndOutputStreams != nil default: break } } #endif switch selector { case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return type(of: self).instancesRespond(to: selector) } } } // MARK: - URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the delegate that the session has been invalidated. /// /// - parameter session: The session object that was invalidated. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { sessionDidBecomeInvalidWithError?(session, error) } /// Requests credentials from the delegate in response to a session-level authentication request from the /// remote server. /// /// - parameter session: The session containing the task that requested authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } completionHandler(disposition, credential) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// /// - parameter session: The session that no longer has any outstanding requests. open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } #endif } // MARK: - URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// /// - parameter session: The session containing the task whose request resulted in a redirect. /// - parameter task: The task whose request resulted in a redirect. /// - parameter response: An object containing the server’s response to the original request. /// - parameter request: A URL request object filled out with the new location. /// - parameter completionHandler: A closure that your handler should call with either the value of the request /// parameter, a modified URL request object, or NULL to refuse the redirect and /// return the body of the redirect response. open func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// /// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task]?.delegate { delegate.urlSession( session, task: task, didReceive: challenge, completionHandler: completionHandler ) } else { urlSession(session, didReceive: challenge, completionHandler: completionHandler) } } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// /// - parameter session: The session containing the task that needs a new body stream. /// - parameter task: The task that needs a new body stream. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. open func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task]?.delegate { delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) } } /// Periodically informs the delegate of the progress of sending body content to the server. /// /// - parameter session: The session containing the data task. /// - parameter task: The data task. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. /// - parameter totalBytesSent: The total number of bytes sent so far. /// - parameter totalBytesExpectedToSend: The expected length of the body data. open func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } #if !os(watchOS) /// Tells the delegate that the session finished collecting metrics for the task. /// /// - parameter session: The session collecting the metrics. /// - parameter task: The task whose metrics have been collected. /// - parameter metrics: The collected metrics. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) @objc(URLSession:task:didFinishCollectingMetrics:) open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { self[task]?.delegate.metrics = metrics } #endif /// Tells the delegate that the task finished transferring data. /// /// - parameter session: The session containing the task whose request finished transferring data. /// - parameter task: The task whose request finished transferring data. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { /// Executed after it is determined that the request is not going to be retried let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in guard let strongSelf = self else { return } if let taskDidComplete = strongSelf.taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = strongSelf[task]?.delegate { delegate.urlSession(session, task: task, didCompleteWithError: error) } NotificationCenter.default.post( name: Notification.Name.Task.DidComplete, object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } // Run all validations on the request before checking if an error occurred request.validations.forEach { $0() } // Determine whether an error has occurred var error: Error? = error if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { error = taskDelegate.error } /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request /// should be retried. Otherwise, complete the task by notifying the task delegate. if let retrier = retrier, let error = error { retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in guard shouldRetry else { completeTask(session, task, error) ; return } DispatchQueue.utility.after(timeDelay) { [weak self] in guard let strongSelf = self else { return } let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false if retrySucceeded, let task = request.task { strongSelf[task] = request return } else { completeTask(session, task, error) } } } } else { completeTask(session, task, error) } } } // MARK: - URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// /// - parameter session: The session containing the data task that received an initial reply. /// - parameter dataTask: The data task that received an initial reply. /// - parameter response: A URL response object populated with headers. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a /// constant to indicate whether the transfer should continue as a data task or /// should become a download task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: URLSession.ResponseDisposition = .allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /// Tells the delegate that the data task was changed to a download task. /// /// - parameter session: The session containing the task that was replaced by a download task. /// - parameter dataTask: The data task that was replaced by a download task. /// - parameter downloadTask: The new download task that replaced the data task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) } } /// Tells the delegate that the data task has received some of the expected data. /// /// - parameter session: The session containing the data task that provided data. /// - parameter dataTask: The data task that provided data. /// - parameter data: A data object containing the transferred data. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession(session, dataTask: dataTask, didReceive: data) } } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// /// - parameter session: The session containing the data (or upload) task. /// - parameter dataTask: The data (or upload) task. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma /// and Cache-Control headers. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed /// response, a modified version of that response, or NULL to prevent caching the /// response. If your delegate implements this method, it must call this completion /// handler; otherwise, your app leaks memory. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } } // MARK: - URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that finished. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either /// open the file for reading or move it to a permanent location in your app’s sandbox /// container directory before returning from this delegate method. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } } /// Periodically informs the delegate about the download’s progress. /// /// - parameter session: The session containing the download task. /// - parameter downloadTask: The download task. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate /// method was called. /// - parameter totalBytesWritten: The total number of bytes transferred so far. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length /// header. If this header was not provided, the value is /// `NSURLSessionTransferSizeUnknown`. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /// Tells the delegate that the download task has resumed downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the /// existing content, then this value is zero. Otherwise, this value is an /// integer representing the number of bytes on disk that do not need to be /// retrieved again. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } } // MARK: - URLSessionStreamDelegate #if !os(watchOS) @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /// Tells the delegate that the write side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /// Tells the delegate that the system has determined that a better route to the host is available. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. /// - parameter inputStream: The new input stream. /// - parameter outputStream: The new output stream. open func urlSession( _ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) } } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/SessionManager.swift ================================================ // // SessionManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. open class SessionManager { // MARK: - Helper Types /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as /// associated values. /// /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with /// streaming information. /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding /// error. public enum MultipartFormDataEncodingResult { case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) case failure(Error) } // MARK: - Properties /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use /// directly for any ad hoc requests. open static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. open static let defaultHTTPHeaders: HTTPHeaders = { // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` let userAgent: String = { if let info = Bundle.main.infoDictionary { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" let osNameVersion: String = { let version = ProcessInfo.processInfo.operatingSystemVersion let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" let osName: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "OS X" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() return "\(osName) \(versionString)" }() let alamofireVersion: String = { guard let afInfo = Bundle(for: SessionManager.self).infoDictionary, let build = afInfo["CFBundleShortVersionString"] else { return "Unknown" } return "Alamofire/\(build)" }() return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() /// Default memory threshold used when encoding `MultipartFormData` in bytes. open static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 /// The underlying session. open let session: URLSession /// The session delegate handling all the task and session delegate callbacks. open let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. open var startRequestsImmediately: Bool = true /// The request adapter called each time a new request is created. open var adapter: RequestAdapter? /// The request retrier called each time a request encounters an error to determine whether to retry the request. open var retrier: RequestRetrier? { get { return delegate.retrier } set { delegate.retrier = newValue } } /// The background completion handler closure provided by the UIApplicationDelegate /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation /// will automatically call the handler. /// /// If you need to handle your own events before the handler is called, then you need to override the /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. /// /// `nil` by default. open var backgroundCompletionHandler: (() -> Void)? let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) // MARK: - Lifecycle /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter configuration: The configuration used to construct the managed session. /// `URLSessionConfiguration.default` by default. /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by /// default. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance. public init( configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SessionDelegate = SessionDelegate(), serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = delegate self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. /// /// - parameter session: The URL session. /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust /// challenges. `nil` by default. /// /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. public init?( session: URLSession, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { guard delegate === session.delegate else { return nil } self.delegate = delegate self.session = session commonInit(serverTrustPolicyManager: serverTrustPolicyManager) } private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { session.serverTrustPolicyManager = serverTrustPolicyManager delegate.sessionManager = self delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in guard let strongSelf = self else { return } DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } } } deinit { session.invalidateAndCancel() } // MARK: - Data Request /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` /// and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult open func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) return request(encodedURLRequest) } catch { return request(originalRequest, failedWith: error) } } /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request. /// /// - returns: The created `DataRequest`. open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { var originalRequest: URLRequest? do { originalRequest = try urlRequest.asURLRequest() let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) let task = try originalTask.task(session: session, adapter: adapter, queue: queue) let request = DataRequest(session: session, requestTask: .data(originalTask, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return request(originalRequest, failedWith: error) } } // MARK: Private - Request Implementation private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { var requestTask: Request.RequestTask = .data(nil, nil) if let urlRequest = urlRequest { let originalTask = DataRequest.Requestable(urlRequest: urlRequest) requestTask = .data(originalTask, nil) } let underlyingError = error.underlyingAdaptError ?? error let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: request, with: underlyingError) } else { if startRequestsImmediately { request.resume() } } return request } // MARK: - Download Request // MARK: URL Request /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, /// `headers` and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) return download(encodedURLRequest, to: destination) } catch { return download(nil, to: destination, failedWith: error) } } /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save /// them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter urlRequest: The URL request /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( _ urlRequest: URLRequestConvertible, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { do { let urlRequest = try urlRequest.asURLRequest() return download(.request(urlRequest), to: destination) } catch { return download(nil, to: destination, failedWith: error) } } // MARK: Resume Data /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve /// the contents of the original request and save them to the `destination`. /// /// If `destination` is not specified, the contents will remain in the temporary location determined by the /// underlying URL session. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the /// data is written incorrectly and will always fail to resume the download. For more information about the bug and /// possible workarounds, please refer to the following Stack Overflow post: /// /// - http://stackoverflow.com/a/39347461/1342462 /// /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for /// additional information. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. /// /// - returns: The created `DownloadRequest`. @discardableResult open func download( resumingWith resumeData: Data, to destination: DownloadRequest.DownloadFileDestination? = nil) -> DownloadRequest { return download(.resumeData(resumeData), to: destination) } // MARK: Private - Download Implementation private func download( _ downloadable: DownloadRequest.Downloadable, to destination: DownloadRequest.DownloadFileDestination?) -> DownloadRequest { do { let task = try downloadable.task(session: session, adapter: adapter, queue: queue) let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) download.downloadDelegate.destination = destination delegate[task] = download if startRequestsImmediately { download.resume() } return download } catch { return download(downloadable, to: destination, failedWith: error) } } private func download( _ downloadable: DownloadRequest.Downloadable?, to destination: DownloadRequest.DownloadFileDestination?, failedWith error: Error) -> DownloadRequest { var downloadTask: Request.RequestTask = .download(nil, nil) if let downloadable = downloadable { downloadTask = .download(downloadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) download.downloadDelegate.destination = destination if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: download, with: underlyingError) } else { if startRequestsImmediately { download.resume() } } return download } // MARK: - Upload Request // MARK: File /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ fileURL: URL, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(fileURL, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter file: The file to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.file(fileURL, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: Data /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ data: Data, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(data, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter data: The data to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.data(data, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: InputStream /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload( _ stream: InputStream, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil) -> UploadRequest { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload(stream, with: urlRequest) } catch { return upload(nil, failedWith: error) } } /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter stream: The stream to upload. /// - parameter urlRequest: The URL request. /// /// - returns: The created `UploadRequest`. @discardableResult open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { do { let urlRequest = try urlRequest.asURLRequest() return upload(.stream(stream, urlRequest)) } catch { return upload(nil, failedWith: error) } } // MARK: MultipartFormData /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `url`, `method` and `headers`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter url: The URL. /// - parameter method: The HTTP method. `.post` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to url: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) return upload( multipartFormData: multipartFormData, usingThreshold: encodingMemoryThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } catch { DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new /// `UploadRequest` using the `urlRequest`. /// /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be /// used for larger payloads such as video content. /// /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding /// technique was used. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. /// `multipartFormDataEncodingMemoryThreshold` by default. /// - parameter urlRequest: The URL request. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. open func upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { DispatchQueue.global(qos: .utility).async { let formData = MultipartFormData() multipartFormData(formData) var tempFileURL: URL? do { var urlRequestWithContentType = try urlRequest.asURLRequest() urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") let isBackgroundSession = self.session.configuration.identifier != nil if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.success( request: self.upload(data, with: urlRequestWithContentType), streamingFromDisk: false, streamFileURL: nil ) DispatchQueue.main.async { encodingCompletion?(encodingResult) } } else { let fileManager = FileManager.default let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") let fileName = UUID().uuidString let fileURL = directoryURL.appendingPathComponent(fileName) tempFileURL = fileURL var directoryError: Error? // Create directory inside serial queue to ensure two threads don't do this in parallel self.queue.sync { do { try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) } catch { directoryError = error } } if let directoryError = directoryError { throw directoryError } try formData.writeEncodedData(to: fileURL) let upload = self.upload(fileURL, with: urlRequestWithContentType) // Cleanup the temp file once the upload is complete upload.delegate.queue.addOperation { do { try FileManager.default.removeItem(at: fileURL) } catch { // No-op } } DispatchQueue.main.async { let encodingResult = MultipartFormDataEncodingResult.success( request: upload, streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } } catch { // Cleanup the temp file in the event that the multipart form data encoding failed if let tempFileURL = tempFileURL { do { try FileManager.default.removeItem(at: tempFileURL) } catch { // No-op } } DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } } } // MARK: Private - Upload Implementation private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { do { let task = try uploadable.task(session: session, adapter: adapter, queue: queue) let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) if case let .stream(inputStream, _) = uploadable { upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } } delegate[task] = upload if startRequestsImmediately { upload.resume() } return upload } catch { return upload(uploadable, failedWith: error) } } private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { var uploadTask: Request.RequestTask = .upload(nil, nil) if let uploadable = uploadable { uploadTask = .upload(uploadable, nil) } let underlyingError = error.underlyingAdaptError ?? error let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) if let retrier = retrier, error is AdaptError { allowRetrier(retrier, toRetry: upload, with: underlyingError) } else { if startRequestsImmediately { upload.resume() } } return upload } #if !os(watchOS) // MARK: - Stream Request // MARK: Hostname and Port /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter hostName: The hostname of the server to connect to. /// - parameter port: The port of the server to connect to. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(withHostName hostName: String, port: Int) -> StreamRequest { return stream(.stream(hostName: hostName, port: port)) } // MARK: NetService /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. /// /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. /// /// - parameter netService: The net service used to identify the endpoint. /// /// - returns: The created `StreamRequest`. @discardableResult @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open func stream(with netService: NetService) -> StreamRequest { return stream(.netService(netService)) } // MARK: Private - Stream Implementation @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { do { let task = try streamable.task(session: session, adapter: adapter, queue: queue) let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) delegate[task] = request if startRequestsImmediately { request.resume() } return request } catch { return stream(failedWith: error) } } @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) private func stream(failedWith error: Error) -> StreamRequest { let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) if startRequestsImmediately { stream.resume() } return stream } #endif // MARK: - Internal - Retry Request func retry(_ request: Request) -> Bool { guard let originalTask = request.originalTask else { return false } do { let task = try originalTask.task(session: session, adapter: adapter, queue: queue) request.delegate.task = task // resets all task delegate data request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { DispatchQueue.utility.async { [weak self] in guard let strongSelf = self else { return } retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in guard let strongSelf = self else { return } guard shouldRetry else { if strongSelf.startRequestsImmediately { request.resume() } return } DispatchQueue.utility.after(timeDelay) { guard let strongSelf = self else { return } let retrySucceeded = strongSelf.retry(request) if retrySucceeded, let task = request.task { strongSelf.delegate[task] = request } else { if strongSelf.startRequestsImmediately { request.resume() } } } } } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/TaskDelegate.swift ================================================ // // TaskDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as /// executing all operations attached to the serial operation queue upon task completion. open class TaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. open let queue: OperationQueue /// The data returned by the server. public var data: Data? { return nil } /// The error generated throughout the lifecyle of the task. public var error: Error? var task: URLSessionTask? { didSet { reset() } } var initialResponseTime: CFAbsoluteTime? var credential: URLCredential? var metrics: AnyObject? // URLSessionTaskMetrics // MARK: Lifecycle init(task: URLSessionTask?) { self.task = task self.queue = { let operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true operationQueue.qualityOfService = .utility return operationQueue }() } func reset() { error = nil initialResponseTime = nil } // MARK: URLSessionTaskDelegate var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } @objc(URLSession:task:didReceiveChallenge:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } else { if challenge.previousFailureCount > 0 { disposition = .rejectProtectionSpace } else { credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) if credential != nil { disposition = .useCredential } } } completionHandler(disposition, credential) } @objc(URLSession:task:needNewBodyStream:) func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { var bodyStream: InputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } @objc(URLSession:task:didCompleteWithError:) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { if self.error == nil { self.error = error } if let downloadDelegate = self as? DownloadTaskDelegate, let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data { downloadDelegate.resumeData = resumeData } } queue.isSuspended = false } } } // MARK: - class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { // MARK: Properties var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } override var data: Data? { if dataStream != nil { return nil } else { return mutableData } } var progress: Progress var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? var dataStream: ((_ data: Data) -> Void)? private var totalBytesReceived: Int64 = 0 private var mutableData: Data private var expectedContentLength: Int64? // MARK: Lifecycle override init(task: URLSessionTask?) { mutableData = Data() progress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() progress = Progress(totalUnitCount: 0) totalBytesReceived = 0 mutableData = Data() expectedContentLength = nil } // MARK: URLSessionDataDelegate var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { var disposition: URLSession.ResponseDisposition = .allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data) } else { mutableData.append(data) } let bytesReceived = Int64(data.count) totalBytesReceived += bytesReceived let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived if let progressHandler = progressHandler { progressHandler.queue.async { progressHandler.closure(self.progress) } } } } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { var cachedResponse: CachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } // MARK: - class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { // MARK: Properties var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } var progress: Progress var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? var resumeData: Data? override var data: Data? { return resumeData } var destination: DownloadRequest.DownloadFileDestination? var temporaryURL: URL? var destinationURL: URL? var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } // MARK: Lifecycle override init(task: URLSessionTask?) { progress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() progress = Progress(totalUnitCount: 0) resumeData = nil } // MARK: URLSessionDownloadDelegate var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { temporaryURL = location guard let destination = destination, let response = downloadTask.response as? HTTPURLResponse else { return } let result = destination(location, response) let destinationURL = result.destinationURL let options = result.options self.destinationURL = destinationURL do { if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.removeItem(at: destinationURL) } if options.contains(.createIntermediateDirectories) { let directory = destinationURL.deletingLastPathComponent() try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } try FileManager.default.moveItem(at: location, to: destinationURL) } catch { self.error = error } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite ) } else { progress.totalUnitCount = totalBytesExpectedToWrite progress.completedUnitCount = totalBytesWritten if let progressHandler = progressHandler { progressHandler.queue.async { progressHandler.closure(self.progress) } } } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else { progress.totalUnitCount = expectedTotalBytes progress.completedUnitCount = fileOffset } } } // MARK: - class UploadTaskDelegate: DataTaskDelegate { // MARK: Properties var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } var uploadProgress: Progress var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? // MARK: Lifecycle override init(task: URLSessionTask?) { uploadProgress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() uploadProgress = Progress(totalUnitCount: 0) } // MARK: URLSessionTaskDelegate var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? func URLSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { uploadProgress.totalUnitCount = totalBytesExpectedToSend uploadProgress.completedUnitCount = totalBytesSent if let uploadProgressHandler = uploadProgressHandler { uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } } } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Timeline.swift ================================================ // // Timeline.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTime: CFAbsoluteTime /// The time when the request was completed. public let requestCompletedTime: CFAbsoluteTime /// The time when the response serialization was completed. public let serializationCompletedTime: CFAbsoluteTime /// The time interval in seconds from the time the request started to the initial response from the server. public let latency: TimeInterval /// The time interval in seconds from the time the request started to the time the request completed. public let requestDuration: TimeInterval /// The time interval in seconds from the time the request completed to the time response serialization completed. public let serializationDuration: TimeInterval /// The time interval in seconds from the time the request started to the time response serialization completed. public let totalDuration: TimeInterval /// Creates a new `Timeline` instance with the specified request times. /// /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. /// Defaults to `0.0`. /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults /// to `0.0`. /// /// - returns: The new `Timeline` instance. public init( requestStartTime: CFAbsoluteTime = 0.0, initialResponseTime: CFAbsoluteTime = 0.0, requestCompletedTime: CFAbsoluteTime = 0.0, serializationCompletedTime: CFAbsoluteTime = 0.0) { self.requestStartTime = requestStartTime self.initialResponseTime = initialResponseTime self.requestCompletedTime = requestCompletedTime self.serializationCompletedTime = serializationCompletedTime self.latency = initialResponseTime - requestStartTime self.requestDuration = requestCompletedTime - requestStartTime self.serializationDuration = serializationCompletedTime - requestCompletedTime self.totalDuration = serializationCompletedTime - requestStartTime } } // MARK: - CustomStringConvertible extension Timeline: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the latency, the request /// duration and the total duration. public var description: String { let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } // MARK: - CustomDebugStringConvertible extension Timeline: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes the request start time, the /// initial response time, the request completed time, the serialization completed time, the latency, the request /// duration and the total duration. public var debugDescription: String { let requestStartTime = String(format: "%.3f", self.requestStartTime) let initialResponseTime = String(format: "%.3f", self.initialResponseTime) let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) let latency = String(format: "%.3f", self.latency) let requestDuration = String(format: "%.3f", self.requestDuration) let serializationDuration = String(format: "%.3f", self.serializationDuration) let totalDuration = String(format: "%.3f", self.totalDuration) // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. let timings = [ "\"Request Start Time\": " + requestStartTime, "\"Initial Response Time\": " + initialResponseTime, "\"Request Completed Time\": " + requestCompletedTime, "\"Serialization Completed Time\": " + serializationCompletedTime, "\"Latency\": " + latency + " secs", "\"Request Duration\": " + requestDuration + " secs", "\"Serialization Duration\": " + serializationDuration + " secs", "\"Total Duration\": " + totalDuration + " secs" ] return "Timeline: { " + timings.joined(separator: ", ") + " }" } } ================================================ FILE: iOS/User/ezshopUser/Pods/Alamofire/Source/Validation.swift ================================================ // // Validation.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Request { // MARK: Helper Types fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason /// Used to represent whether validation was successful or encountered an error resulting in a failure. /// /// - success: The validation was successful. /// - failure: The validation failed encountering the provided error. public enum ValidationResult { case success case failure(Error) } fileprivate struct MIMEType { let type: String let subtype: String var isWildcard: Bool { return type == "*" && subtype == "*" } init?(_ string: String) { let components: [String] = { let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) return split.components(separatedBy: "/") }() if let type = components.first, let subtype = components.last { self.type = type self.subtype = subtype } else { return nil } } func matches(_ mime: MIMEType) -> Bool { switch (type, subtype) { case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): return true default: return false } } } // MARK: Properties fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } fileprivate var acceptableContentTypes: [String] { if let accept = request?.value(forHTTPHeaderField: "Accept") { return accept.components(separatedBy: ",") } return ["*/*"] } // MARK: Status Code fileprivate func validate( statusCode acceptableStatusCodes: S, response: HTTPURLResponse) -> ValidationResult where S.Iterator.Element == Int { if acceptableStatusCodes.contains(response.statusCode) { return .success } else { let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) return .failure(AFError.responseValidationFailed(reason: reason)) } } // MARK: Content Type fileprivate func validate( contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, data.count > 0 else { return .success } guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .success } } let error: AFError = { let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } for contentType in acceptableContentTypes { if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { return .success } } let error: AFError = { let reason: ErrorReason = .unacceptableContentType( acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType ) return AFError.responseValidationFailed(reason: reason) }() return .failure(error) } } // MARK: - extension DataRequest { /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the /// request was valid. public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(self.request, response, self.delegate.data) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, data in return self.validate(contentType: acceptableContentTypes, response: response, data: data) } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } // MARK: - extension DownloadRequest { /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a /// destination URL, and returns whether the request was valid. public typealias Validation = ( _ request: URLRequest?, _ response: HTTPURLResponse, _ temporaryURL: URL?, _ destinationURL: URL?) -> ValidationResult /// Validates the request, using the specified closure. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter validation: A closure to validate the request. /// /// - returns: The request. @discardableResult public func validate(_ validation: @escaping Validation) -> Self { let validationExecution: () -> Void = { [unowned self] in let request = self.request let temporaryURL = self.downloadDelegate.temporaryURL let destinationURL = self.downloadDelegate.destinationURL if let response = self.response, self.delegate.error == nil, case let .failure(error) = validation(request, response, temporaryURL, destinationURL) { self.delegate.error = error } } validations.append(validationExecution) return self } /// Validates that the response has a status code in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter range: The range of acceptable status codes. /// /// - returns: The request. @discardableResult public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { return validate { [unowned self] _, response, _, _ in return self.validate(statusCode: acceptableStatusCodes, response: response) } } /// Validates that the response has a content type in the specified sequence. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. /// /// - returns: The request. @discardableResult public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { return validate { [unowned self] _, response, _, _ in let fileURL = self.downloadDelegate.fileURL guard let validFileURL = fileURL else { return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) } do { let data = try Data(contentsOf: validFileURL) return self.validate(contentType: acceptableContentTypes, response: response, data: data) } catch { return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) } } } /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns: The request. @discardableResult public func validate() -> Self { return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) } } ================================================ FILE: iOS/User/ezshopUser/Pods/AlamofireSwiftyJSON/LICENSE ================================================ Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/User/ezshopUser/Pods/AlamofireSwiftyJSON/README.md ================================================ #AlamofireSwiftyJSON [![Build Status](https://travis-ci.org/starboychina/AlamofireSwiftyJSON.svg)](https://travis-ci.org/starboychina/AlamofireSwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![SwiftLint](https://img.shields.io/badge/SwiftLint-passing-brightgreen.svg)](https://github.com/realm/SwiftLint) [![codecov.io](https://codecov.io/github/starboychina/AlamofireSwiftyJSON/coverage.svg?branch=master)](https://codecov.io/gh/starboychina/AlamofireSwiftyJSON?branch=master) [![GitHub release](https://img.shields.io/github/release/starboychina/AlamofireSwiftyJSON.svg)](https://github.com/starboychina/AlamofireSwiftyJSON/releases) --- Easy way to use both [Alamofire](https://github.com/Alamofire/Alamofire) and [SwiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON) ## Requirements - iOS 8.0+ / Mac OS X 10.9+ - Xcode 7.0 ## Install - CocoaPods ```swift source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! target "target name" do pod 'AlamofireSwiftyJSON' end ``` - [Carthage](https://github.com/Carthage/Carthage) ```swift github "starboychina/AlamofireSwiftyJSON" ``` ## Usage ```swift let URL = "http://httpbin.org/get" Alamofire.request(.GET, URL, parameters: ["foo": "bar"]).responseSwiftyJSON { response in print("###Success: \(response.result.isSuccess)") //now response.result.value is SwiftyJSON.JSON type print("###Value: \(response.result.value?["args"].array)") } ``` ================================================ FILE: iOS/User/ezshopUser/Pods/AlamofireSwiftyJSON/Source/AlamofireSwiftyJSON.swift ================================================ // // AlamofireSwiftyJSON.swift // AlamofireSwiftyJSON // // Created by Hikaru on 2016/01/29. // Copyright © 2016年 Hikaru. All rights reserved. // import Alamofire import SwiftyJSON /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set = [204, 205] // MARK: - Request for SwiftyJSON extension DataRequest { /// Creates a response serializer that /// returns a SwiftyJSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func serializeResponseSwiftyJSON( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseSwiftyJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: /// The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseSwiftyJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.serializeResponseSwiftyJSON(options: options), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed /// from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseSwiftyJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(JSON.null) } guard let validData = data, !validData.isEmpty else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(JSON(json)) } catch { return .failure(AFError.responseSerializationFailed( reason: .jsonSerializationFailed(error: error))) } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Firebase/Core/Sources/Firebase.h ================================================ #import #import #if !defined(__has_include) #error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \ import the headers individually." #else #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #if __has_include() #import #endif #endif // defined(__has_include) ================================================ FILE: iOS/User/ezshopUser/Pods/Firebase/Core/Sources/module.modulemap ================================================ module Firebase { export * header "Firebase.h" } ================================================ FILE: iOS/User/ezshopUser/Pods/Firebase/README.md ================================================ # Firebase APIs for iOS Simplify your iOS development, grow your user base, and monetize more effectively with Firebase services. Much more information can be found at [https://firebase.google.com](https://firebase.google.com). ## Install a Firebase SDK using CocoaPods Firebase distributes several iOS specific APIs and SDKs via CocoaPods. You can install the CocoaPods tool on OS X by running the following command from the terminal. Detailed information is available in the [Getting Started guide](https://guides.cocoapods.org/using/getting-started.html#getting-started). ``` $ sudo gem install cocoapods ``` ## Try out an SDK You can try any of the SDKs with `pod try`. Run the following command and select the SDK you are interested in when prompted: ``` $ pod try Firebase ``` Note that some SDKs may require credentials. More information is available in the SDK-specific documentation at [https://firebase.google.com/docs/](https://firebase.google.com/docs/). ## Add a Firebase SDK to your iOS app CocoaPods is used to install and manage dependencies in existing Xcode projects. 1. Create an Xcode project, and save it to your local machine. 2. Create a file named `Podfile` in your project directory. This file defines your project's dependencies, and is commonly referred to as a Podspec. 3. Open `Podfile`, and add your dependencies. A simple Podspec is shown here: ``` platform :ios, '7.0' pod 'Firebase' ``` 4. Save the file. 5. Open a terminal and `cd` to the directory containing the Podfile. ``` $ cd /project/ ``` 6. Run the `pod install` command. This will install the SDKs specified in the Podspec, along with any dependencies they may have. ``` $ pod install ``` 7. Open your app's `.xcworkspace` file to launch Xcode. Use this file for all development on your app. 8. You can also install other Firebase SDKs by adding the subspecs in the Podfile. ``` pod 'Firebase/AdMob' pod 'Firebase/Analytics' pod 'Firebase/AppIndexing' pod 'Firebase/Auth' pod 'Firebase/Crash' pod 'Firebase/Database' pod 'Firebase/DynamicLinks' pod 'Firebase/Invites' pod 'Firebase/Messaging' pod 'Firebase/RemoteConfig' pod 'Firebase/Storage' ``` ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/FirebaseAnalytics ================================================ [File too large to display: 14.3 MB] ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics+AppDelegate.h ================================================ #import #import "FIRAnalytics.h" /** * Provides App Delegate handlers to be used in your App Delegate. * * To save time integrating Firebase Analytics in an application, Firebase Analytics does not * require delegation implementation from the AppDelegate. Instead this is automatically done by * Firebase Analytics. Should you choose instead to delegate manually, you can turn off the App * Delegate Proxy by adding FirebaseAppDelegateProxyEnabled into your app's Info.plist and setting * it to NO, and adding the methods in this category to corresponding delegation handlers. * * To handle Universal Links, you must return YES in * [UIApplicationDelegate application:didFinishLaunchingWithOptions:]. */ @interface FIRAnalytics (AppDelegate) /** * Handles events related to a URL session that are waiting to be processed. * * For optimal use of Firebase Analytics, call this method from the * [UIApplicationDelegate application:handleEventsForBackgroundURLSession:completionHandler] * method of the app delegate in your app. * * @param identifier The identifier of the URL session requiring attention. * @param completionHandler The completion handler to call when you finish processing the events. * Calling this completion handler lets the system know that your app's user interface is * updated and a new snapshot can be taken. */ + (void)handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler; /** * Handles the event when the app is launched by a URL. * * Call this method from [UIApplicationDelegate application:openURL:options:] (on iOS 9.0 and * above), or [UIApplicationDelegate application:openURL:sourceApplication:annotation:] (on iOS 8.x * and below) in your app. * * @param url The URL resource to open. This resource can be a network resource or a file. */ + (void)handleOpenURL:(NSURL *)url; /** * Handles the event when the app receives data associated with user activity that includes a * Universal Link (on iOS 9.0 and above). * * Call this method from [UIApplication continueUserActivity:restorationHandler:] in your app * delegate (on iOS 9.0 and above). * * @param userActivity The activity object containing the data associated with the task the user * was performing. */ + (void)handleUserActivity:(id)userActivity; @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalytics.h ================================================ #import #import "FIREventNames.h" #import "FIRParameterNames.h" #import "FIRUserPropertyNames.h" NS_ASSUME_NONNULL_BEGIN /// The top level Firebase Analytics singleton that provides methods for logging events and setting /// user properties. See the developer guides for general /// information on using Firebase Analytics in your apps. @interface FIRAnalytics : NSObject /// Logs an app event. The event can have up to 25 parameters. Events with the same name must have /// the same parameters. Up to 500 event names are supported. Using predefined events and/or /// parameters is recommended for optimal reporting. /// /// The following event names are reserved and cannot be used: ///
    ///
  • app_clear_data
  • ///
  • app_remove
  • ///
  • app_update
  • ///
  • error
  • ///
  • first_open
  • ///
  • in_app_purchase
  • ///
  • notification_dismiss
  • ///
  • notification_foreground
  • ///
  • notification_open
  • ///
  • notification_receive
  • ///
  • os_update
  • ///
  • session_start
  • ///
  • user_engagement
  • ///
/// /// @param name The name of the event. Should contain 1 to 40 alphanumeric characters or /// underscores. The name must start with an alphabetic character. Some event names are /// reserved. See FIREventNames.h for the list of reserved event names. The "firebase_" prefix /// is reserved and should not be used. Note that event names are case-sensitive and that /// logging two events whose names differ only in case will result in two distinct events. /// @param parameters The dictionary of event parameters. Passing nil indicates that the event has /// no parameters. Parameter names can be up to 40 characters long and must start with an /// alphabetic character and contain only alphanumeric characters and underscores. Only NSString /// and NSNumber (signed 64-bit integer and 64-bit floating-point number) parameter types are /// supported. NSString parameter values can be up to 100 characters long. The "firebase_" /// prefix is reserved and should not be used for parameter names. + (void)logEventWithName:(NSString *)name parameters:(nullable NSDictionary *)parameters; /// Sets a user property to a given value. Up to 25 user property names are supported. Once set, /// user property values persist throughout the app lifecycle and across sessions. /// /// The following user property names are reserved and cannot be used: ///
    ///
  • first_open_time
  • ///
  • last_deep_link_referrer
  • ///
  • user_id
  • ///
/// /// @param value The value of the user property. Values can be up to 36 characters long. Setting the /// value to nil removes the user property. /// @param name The name of the user property to set. Should contain 1 to 24 alphanumeric characters /// or underscores and must start with an alphabetic character. The "firebase_" prefix is /// reserved and should not be used for user property names. + (void)setUserPropertyString:(nullable NSString *)value forName:(NSString *)name; /// Sets the user ID property. This feature must be used in accordance with /// Google's Privacy Policy /// /// @param userID The user ID to ascribe to the user of this app on this device, which must be /// non-empty and no more than 36 characters long. Setting userID to nil removes the user ID. + (void)setUserID:(nullable NSString *)userID; /// Sets the current screen name, which specifies the current visual context in your app. This helps /// identify the areas in your app where users spend their time and how they interact with your app. /// /// Note that screen reporting is enabled automatically and records the class name of the current /// UIViewController for you without requiring you to call this method. If you implement /// viewDidAppear in your UIViewController but do not call [super viewDidAppear:], that screen class /// will not be automatically tracked. The class name can optionally be overridden by calling this /// method in the viewDidAppear callback of your UIViewController and specifying the /// screenClassOverride parameter. /// /// If your app does not use a distinct UIViewController for each screen, you should call this /// method and specify a distinct screenName each time a new screen is presented to the user. /// /// The screen name and screen class remain in effect until the current UIViewController changes or /// a new call to setScreenName:screenClass: is made. /// /// @param screenName The name of the current screen. Should contain 1 to 100 characters. Set to nil /// to clear the current screen name. /// @param screenClassOverride The name of the screen class. Should contain 1 to 100 characters. By /// default this is the class name of the current UIViewController. Set to nil to revert to the /// default class name. + (void)setScreenName:(nullable NSString *)screenName screenClass:(nullable NSString *)screenClassOverride; /// The unique ID for this instance of the application. + (NSString *)appInstanceID; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRAnalyticsConfiguration.h ================================================ #import ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRApp.h ================================================ #import ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRConfiguration.h ================================================ #import ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIREventNames.h ================================================ /// @file FIREventNames.h /// /// Predefined event names. /// /// An Event is an important occurrence in your app that you want to measure. You can report up to /// 500 different types of Events per app and you can associate up to 25 unique parameters with each /// Event type. Some common events are suggested below, but you may also choose to specify custom /// Event types that are associated with your specific app. Each event type is identified by a /// unique name. Event names can be up to 40 characters long, may only contain alphanumeric /// characters and underscores ("_"), and must start with an alphabetic character. The "firebase_" /// prefix is reserved and should not be used. /// Add Payment Info event. This event signifies that a user has submitted their payment information /// to your app. static NSString *const kFIREventAddPaymentInfo = @"add_payment_info"; /// E-Commerce Add To Cart event. This event signifies that an item was added to a cart for /// purchase. Add this event to a funnel with kFIREventEcommercePurchase to gauge the effectiveness /// of your checkout process. Note: If you supply the @c kFIRParameterValue parameter, you must /// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
static NSString *const kFIREventAddToCart = @"add_to_cart"; /// E-Commerce Add To Wishlist event. This event signifies that an item was added to a wishlist. /// Use this event to identify popular gift items in your app. Note: If you supply the /// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency /// parameter so that revenue metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventAddToWishlist = @"add_to_wishlist"; /// App Open event. By logging this event when an App is moved to the foreground, developers can /// understand how often users leave and return during the course of a Session. Although Sessions /// are automatically reported, this event can provide further clarification around the continuous /// engagement of app-users. static NSString *const kFIREventAppOpen = @"app_open"; /// E-Commerce Begin Checkout event. This event signifies that a user has begun the process of /// checking out. Add this event to a funnel with your kFIREventEcommercePurchase event to gauge the /// effectiveness of your checkout process. Note: If you supply the @c kFIRParameterValue /// parameter, you must also supply the @c kFIRParameterCurrency parameter so that revenue /// metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventBeginCheckout = @"begin_checkout"; /// Campaign Detail event. Log this event to supply the referral details of a re-engagement /// campaign. Note: you must supply at least one of the required parameters kFIRParameterSource, /// kFIRParameterMedium or kFIRParameterCampaign. Params: /// ///
    ///
  • @c kFIRParameterSource (NSString)
  • ///
  • @c kFIRParameterMedium (NSString)
  • ///
  • @c kFIRParameterCampaign (NSString)
  • ///
  • @c kFIRParameterTerm (NSString) (optional)
  • ///
  • @c kFIRParameterContent (NSString) (optional)
  • ///
  • @c kFIRParameterAdNetworkClickID (NSString) (optional)
  • ///
  • @c kFIRParameterCP1 (NSString) (optional)
  • ///
static NSString *const kFIREventCampaignDetails = @"campaign_details"; /// Earn Virtual Currency event. This event tracks the awarding of virtual currency in your app. Log /// this along with @c kFIREventSpendVirtualCurrency to better understand your virtual economy. /// Params: /// ///
    ///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • ///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • ///
static NSString *const kFIREventEarnVirtualCurrency = @"earn_virtual_currency"; /// E-Commerce Purchase event. This event signifies that an item was purchased by a user. Note: /// This is different from the in-app purchase event, which is reported automatically for App /// Store-based apps. Note: If you supply the @c kFIRParameterValue parameter, you must also /// supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
  • @c kFIRParameterTax (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterShipping (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCoupon (NSString) (optional)
  • ///
  • @c kFIRParameterLocation (NSString) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventEcommercePurchase = @"ecommerce_purchase"; /// Generate Lead event. Log this event when a lead has been generated in the app to understand the /// efficacy of your install and re-engagement campaigns. Note: If you supply the /// @c kFIRParameterValue parameter, you must also supply the @c kFIRParameterCurrency /// parameter so that revenue metrics can be computed accurately. Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventGenerateLead = @"generate_lead"; /// Join Group event. Log this event when a user joins a group such as a guild, team or family. Use /// this event to analyze how popular certain groups or social features are in your app. Params: /// ///
    ///
  • @c kFIRParameterGroupID (NSString)
  • ///
static NSString *const kFIREventJoinGroup = @"join_group"; /// Level Up event. This event signifies that a player has leveled up in your gaming app. It can /// help you gauge the level distribution of your userbase and help you identify certain levels that /// are difficult to pass. Params: /// ///
    ///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterCharacter (NSString) (optional)
  • ///
static NSString *const kFIREventLevelUp = @"level_up"; /// Login event. Apps with a login feature can report this event to signify that a user has logged /// in. static NSString *const kFIREventLogin = @"login"; /// Post Score event. Log this event when the user posts a score in your gaming app. This event can /// help you understand how users are actually performing in your game and it can help you correlate /// high scores with certain audiences or behaviors. Params: /// ///
    ///
  • @c kFIRParameterScore (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterLevel (signed 64-bit integer as NSNumber) (optional)
  • ///
  • @c kFIRParameterCharacter (NSString) (optional)
  • ///
static NSString *const kFIREventPostScore = @"post_score"; /// Present Offer event. This event signifies that the app has presented a purchase offer to a user. /// Add this event to a funnel with the kFIREventAddToCart and kFIREventEcommercePurchase to gauge /// your conversion process. Note: If you supply the @c kFIRParameterValue parameter, you must /// also supply the @c kFIRParameterCurrency parameter so that revenue metrics can be computed /// accurately. Params: /// ///
    ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
static NSString *const kFIREventPresentOffer = @"present_offer"; /// E-Commerce Purchase Refund event. This event signifies that an item purchase was refunded. /// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the /// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. /// Params: /// ///
    ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterTransactionID (NSString) (optional)
  • ///
static NSString *const kFIREventPurchaseRefund = @"purchase_refund"; /// Search event. Apps that support search features can use this event to contextualize search /// operations by supplying the appropriate, corresponding parameters. This event can help you /// identify the most popular content in your app. Params: /// ///
    ///
  • @c kFIRParameterSearchTerm (NSString)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// hotel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventSearch = @"search"; /// Select Content event. This general purpose event signifies that a user has selected some content /// of a certain type in an app. The content can be any object in your app. This event can help you /// identify popular content and categories of content in your app. Params: /// ///
    ///
  • @c kFIRParameterContentType (NSString)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
static NSString *const kFIREventSelectContent = @"select_content"; /// Share event. Apps with social features can log the Share event to identify the most viral /// content. Params: /// ///
    ///
  • @c kFIRParameterContentType (NSString)
  • ///
  • @c kFIRParameterItemID (NSString)
  • ///
static NSString *const kFIREventShare = @"share"; /// Sign Up event. This event indicates that a user has signed up for an account in your app. The /// parameter signifies the method by which the user signed up. Use this event to understand the /// different behaviors between logged in and logged out users. Params: /// ///
    ///
  • @c kFIRParameterSignUpMethod (NSString)
  • ///
static NSString *const kFIREventSignUp = @"sign_up"; /// Spend Virtual Currency event. This event tracks the sale of virtual goods in your app and can /// help you identify which virtual goods are the most popular objects of purchase. Params: /// ///
    ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterVirtualCurrencyName (NSString)
  • ///
  • @c kFIRParameterValue (signed 64-bit integer or double as NSNumber)
  • ///
static NSString *const kFIREventSpendVirtualCurrency = @"spend_virtual_currency"; /// Tutorial Begin event. This event signifies the start of the on-boarding process in your app. Use /// this in a funnel with kFIREventTutorialComplete to understand how many users complete this /// process and move on to the full app experience. static NSString *const kFIREventTutorialBegin = @"tutorial_begin"; /// Tutorial End event. Use this event to signify the user's completion of your app's on-boarding /// process. Add this to a funnel with kFIREventTutorialBegin to gauge the completion rate of your /// on-boarding process. static NSString *const kFIREventTutorialComplete = @"tutorial_complete"; /// Unlock Achievement event. Log this event when the user has unlocked an achievement in your /// game. Since achievements generally represent the breadth of a gaming experience, this event can /// help you understand how many users are experiencing all that your game has to offer. Params: /// ///
    ///
  • @c kFIRParameterAchievementID (NSString)
  • ///
static NSString *const kFIREventUnlockAchievement = @"unlock_achievement"; /// View Item event. This event signifies that some content was shown to the user. This content may /// be a product, a webpage or just a simple image or text. Use the appropriate parameters to /// contextualize the event. Use this event to discover the most popular items viewed in your app. /// Note: If you supply the @c kFIRParameterValue parameter, you must also supply the /// @c kFIRParameterCurrency parameter so that revenue metrics can be computed accurately. /// Params: /// ///
    ///
  • @c kFIRParameterItemID (NSString)
  • ///
  • @c kFIRParameterItemName (NSString)
  • ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
  • @c kFIRParameterItemLocationID (NSString) (optional)
  • ///
  • @c kFIRParameterPrice (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterQuantity (signed 64-bit integer as NSNumber) (optional)
  • ///
  • @c kFIRParameterCurrency (NSString) (optional)
  • ///
  • @c kFIRParameterValue (double as NSNumber) (optional)
  • ///
  • @c kFIRParameterStartDate (NSString) (optional)
  • ///
  • @c kFIRParameterEndDate (NSString) (optional)
  • ///
  • @c kFIRParameterFlightNumber (NSString) (optional) for travel bookings
  • ///
  • @c kFIRParameterNumberOfPassengers (signed 64-bit integer as NSNumber) (optional) /// for travel bookings
  • ///
  • @c kFIRParameterNumberOfNights (signed 64-bit integer as NSNumber) (optional) for /// travel bookings
  • ///
  • @c kFIRParameterNumberOfRooms (signed 64-bit integer as NSNumber) (optional) for /// travel bookings
  • ///
  • @c kFIRParameterOrigin (NSString) (optional)
  • ///
  • @c kFIRParameterDestination (NSString) (optional)
  • ///
  • @c kFIRParameterSearchTerm (NSString) (optional) for travel bookings
  • ///
  • @c kFIRParameterTravelClass (NSString) (optional) for travel bookings
  • ///
static NSString *const kFIREventViewItem = @"view_item"; /// View Item List event. Log this event when the user has been presented with a list of items of a /// certain category. Params: /// ///
    ///
  • @c kFIRParameterItemCategory (NSString)
  • ///
static NSString *const kFIREventViewItemList = @"view_item_list"; /// View Search Results event. Log this event when the user has been presented with the results of a /// search. Params: /// ///
    ///
  • @c kFIRParameterSearchTerm (NSString)
  • ///
static NSString *const kFIREventViewSearchResults = @"view_search_results"; ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIROptions.h ================================================ #import ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRParameterNames.h ================================================ /// @file FIRParameterNames.h /// /// Predefined event parameter names. /// /// Params supply information that contextualize Events. You can associate up to 25 unique Params /// with each Event type. Some Params are suggested below for certain common Events, but you are /// not limited to these. You may supply extra Params for suggested Events or custom Params for /// Custom events. Param names can be up to 40 characters long, may only contain alphanumeric /// characters and underscores ("_"), and must start with an alphabetic character. Param values can /// be up to 100 characters long. The "firebase_" prefix is reserved and should not be used. /// Game achievement ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterAchievementID : @"10_matches_won",
///       // ...
///     };
/// 
static NSString *const kFIRParameterAchievementID = @"achievement_id"; /// Ad Network Click ID (NSString). Used for network-specific click IDs which vary in format. ///
///     NSDictionary *params = @{
///       kFIRParameterAdNetworkClickID : @"1234567",
///       // ...
///     };
/// 
static NSString *const kFIRParameterAdNetworkClickID = @"aclid"; /// The individual campaign name, slogan, promo code, etc. Some networks have pre-defined macro to /// capture campaign information, otherwise can be populated by developer. Highly Recommended /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCampaign : @"winter_promotion",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCampaign = @"campaign"; /// Character used in game (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCharacter : @"beat_boss",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCharacter = @"character"; /// Campaign content (NSString). static NSString *const kFIRParameterContent = @"content"; /// Type of content selected (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterContentType : @"news article",
///       // ...
///     };
/// 
static NSString *const kFIRParameterContentType = @"content_type"; /// Coupon code for a purchasable item (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCoupon : @"zz123",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCoupon = @"coupon"; /// Campaign custom parameter (NSString). Used as a method of capturing custom data in a campaign. /// Use varies by network. ///
///     NSDictionary *params = @{
///       kFIRParameterCP1 : @"custom_data",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCP1 = @"cp1"; /// Purchase currency in 3-letter /// ISO_4217 format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterCurrency : @"USD",
///       // ...
///     };
/// 
static NSString *const kFIRParameterCurrency = @"currency"; /// Flight or Travel destination (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterDestination : @"Mountain View, CA",
///       // ...
///     };
/// 
static NSString *const kFIRParameterDestination = @"destination"; /// The arrival date, check-out date or rental end date for the item. This should be in /// YYYY-MM-DD format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterEndDate : @"2015-09-14",
///       // ...
///     };
/// 
static NSString *const kFIRParameterEndDate = @"end_date"; /// Flight number for travel events (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterFlightNumber : @"ZZ800",
///       // ...
///     };
/// 
static NSString *const kFIRParameterFlightNumber = @"flight_number"; /// Group/clan/guild ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterGroupID : @"g1",
///       // ...
///     };
/// 
static NSString *const kFIRParameterGroupID = @"group_id"; /// Item category (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemCategory : @"t-shirts",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemCategory = @"item_category"; /// Item ID (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemID : @"p7654",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemID = @"item_id"; /// The Google Place ID (NSString) that /// corresponds to the associated item. Alternatively, you can supply your own custom Location ID. ///
///     NSDictionary *params = @{
///       kFIRParameterItemLocationID : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemLocationID = @"item_location_id"; /// Item name (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterItemName : @"abc",
///       // ...
///     };
/// 
static NSString *const kFIRParameterItemName = @"item_name"; /// Level in game (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterLevel : @(42),
///       // ...
///     };
/// 
static NSString *const kFIRParameterLevel = @"level"; /// Location (NSString). The Google Place ID /// that corresponds to the associated event. Alternatively, you can supply your own custom /// Location ID. ///
///     NSDictionary *params = @{
///       kFIRParameterLocation : @"ChIJiyj437sx3YAR9kUWC8QkLzQ",
///       // ...
///     };
/// 
static NSString *const kFIRParameterLocation = @"location"; /// The advertising or marketing medium, for example: cpc, banner, email, push. Highly recommended /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterMedium : @"email",
///       // ...
///     };
/// 
static NSString *const kFIRParameterMedium = @"medium"; /// Number of nights staying at hotel (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfNights : @(3),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfNights = @"number_of_nights"; /// Number of passengers traveling (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfPassengers : @(11),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfPassengers = @"number_of_passengers"; /// Number of rooms for travel events (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterNumberOfRooms : @(2),
///       // ...
///     };
/// 
static NSString *const kFIRParameterNumberOfRooms = @"number_of_rooms"; /// Flight or Travel origin (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterOrigin : @"Mountain View, CA",
///       // ...
///     };
/// 
static NSString *const kFIRParameterOrigin = @"origin"; /// Purchase price (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterPrice : @(1.0),
///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterPrice = @"price"; /// Purchase quantity (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterQuantity : @(1),
///       // ...
///     };
/// 
static NSString *const kFIRParameterQuantity = @"quantity"; /// Score in game (signed 64-bit integer as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterScore : @(4200),
///       // ...
///     };
/// 
static NSString *const kFIRParameterScore = @"score"; /// The search string/keywords used (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSearchTerm : @"periodic table",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSearchTerm = @"search_term"; /// Shipping cost (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterShipping : @(9.50),
///       kFIRParameterCurrency : @"USD",  // e.g. $9.50 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterShipping = @"shipping"; /// Sign up method (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSignUpMethod : @"google",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSignUpMethod = @"sign_up_method"; /// The origin of your traffic, such as an Ad network (for example, google) or partner (urban /// airship). Identify the advertiser, site, publication, etc. that is sending traffic to your /// property. Highly recommended (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterSource : @"InMobi",
///       // ...
///     };
/// 
static NSString *const kFIRParameterSource = @"source"; /// The departure date, check-in date or rental start date for the item. This should be in /// YYYY-MM-DD format (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterStartDate : @"2015-09-14",
///       // ...
///     };
/// 
static NSString *const kFIRParameterStartDate = @"start_date"; /// Tax amount (double as NSNumber). ///
///     NSDictionary *params = @{
///       kFIRParameterTax : @(1.0),
///       kFIRParameterCurrency : @"USD",  // e.g. $1.00 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterTax = @"tax"; /// If you're manually tagging keyword campaigns, you should use utm_term to specify the keyword /// (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTerm : @"game",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTerm = @"term"; /// A single ID for a ecommerce group transaction (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTransactionID : @"ab7236dd9823",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTransactionID = @"transaction_id"; /// Travel class (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterTravelClass : @"business",
///       // ...
///     };
/// 
static NSString *const kFIRParameterTravelClass = @"travel_class"; /// A context-specific numeric value which is accumulated automatically for each event type. This is /// a general purpose parameter that is useful for accumulating a key metric that pertains to an /// event. Examples include revenue, distance, time and points. Value should be specified as signed /// 64-bit integer or double as NSNumber. Notes: Values for pre-defined currency-related events /// (such as @c kFIREventAddToCart) should be supplied using double as NSNumber and must be /// accompanied by a @c kFIRParameterCurrency parameter. The valid range of accumulated values is /// [-9,223,372,036,854.77, 9,223,372,036,854.77]. ///
///     NSDictionary *params = @{
///       kFIRParameterValue : @(3.99),
///       kFIRParameterCurrency : @"USD",  // e.g. $3.99 USD
///       // ...
///     };
/// 
static NSString *const kFIRParameterValue = @"value"; /// Name of virtual currency type (NSString). ///
///     NSDictionary *params = @{
///       kFIRParameterVirtualCurrencyName : @"virtual_currency_name",
///       // ...
///     };
/// 
static NSString *const kFIRParameterVirtualCurrencyName = @"virtual_currency_name"; ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FIRUserPropertyNames.h ================================================ /// @file FIRUserPropertyNames.h /// /// Predefined user property names. /// /// A UserProperty is an attribute that describes the app-user. By supplying UserProperties, you can /// later analyze different behaviors of various segments of your userbase. You may supply up to 25 /// unique UserProperties per app, and you can use the name and value of your choosing for each one. /// UserProperty names can be up to 24 characters long, may only contain alphanumeric characters and /// underscores ("_"), and must start with an alphabetic character. UserProperty values can be up to /// 36 characters long. The "firebase_" prefix is reserved and should not be used. /// The method used to sign in. For example, "google", "facebook" or "twitter". static NSString *const kFIRUserPropertySignUpMethod = @"sign_up_method"; ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Headers/FirebaseAnalytics.h ================================================ #import "FIRAnalyticsConfiguration.h" #import "FIRApp.h" #import "FIRConfiguration.h" #import "FIROptions.h" #import "FIRAnalytics+AppDelegate.h" #import "FIRAnalytics.h" #import "FIREventNames.h" #import "FIRParameterNames.h" #import "FIRUserPropertyNames.h" ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseAnalytics/Frameworks/FirebaseAnalytics.framework/Modules/module.modulemap ================================================ framework module FirebaseAnalytics { umbrella header "FirebaseAnalytics.h" export * module * { export *} link "sqlite3" link "z" link framework "CoreGraphics" link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRAnalyticsConfiguration.h ================================================ #import /** * This class provides configuration fields for Firebase Analytics. */ @interface FIRAnalyticsConfiguration : NSObject /** * Returns the shared instance of FIRAnalyticsConfiguration. */ + (FIRAnalyticsConfiguration *)sharedInstance; /** * Sets the minimum engagement time in seconds required to start a new session. The default value * is 10 seconds. */ - (void)setMinimumSessionInterval:(NSTimeInterval)minimumSessionInterval; /** * Sets the interval of inactivity in seconds that terminates the current session. The default * value is 1800 seconds (30 minutes). */ - (void)setSessionTimeoutInterval:(NSTimeInterval)sessionTimeoutInterval; /** * Sets whether analytics collection is enabled for this app on this device. This setting is * persisted across app sessions. By default it is enabled. */ - (void)setAnalyticsCollectionEnabled:(BOOL)analyticsCollectionEnabled; /** * Deprecated. Sets whether measurement and reporting are enabled for this app on this device. By * default they are enabled. */ - (void)setIsEnabled:(BOOL)isEnabled DEPRECATED_MSG_ATTRIBUTE("Use setAnalyticsCollectionEnabled: instead."); @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRApp.h ================================================ #import #import @class FIROptions; NS_ASSUME_NONNULL_BEGIN /** A block that takes a BOOL and has no return value. */ typedef void (^FIRAppVoidBoolCallback)(BOOL success); /** * The entry point of Firebase SDKs. * * Initialize and configure FIRApp using +[FIRApp configure] * or other customized ways as shown below. * * The logging system has two modes: default mode and debug mode. In default mode, only logs with * log level Notice, Warning and Error will be sent to device. In debug mode, all logs will be sent * to device. The log levels that Firebase uses are consistent with the ASL log levels. * * Enable debug mode by passing the -FIRDebugEnabled argument to the application. You can add this * argument in the application's Xcode scheme. When debug mode is enabled via -FIRDebugEnabled, * further executions of the application will also be in debug mode. In order to return to default * mode, you must explicitly disable the debug mode with the application argument -FIRDebugDisabled. * * It is also possible to change the default logging level in code by calling setLoggerLevel: on * the FIRConfiguration interface. */ @interface FIRApp : NSObject /** * Configures a default Firebase app. Raises an exception if any configuration step fails. The * default app is named "__FIRAPP_DEFAULT". This method should be called after the app is launched * and before using Firebase services. This method is thread safe. */ + (void)configure; /** * Configures the default Firebase app with the provided options. The default app is named * "__FIRAPP_DEFAULT". Raises an exception if any configuration step fails. This method is thread * safe. * * @param options The Firebase application options used to configure the service. */ + (void)configureWithOptions:(FIROptions *)options; /** * Configures a Firebase app with the given name and options. Raises an exception if any * configuration step fails. This method is thread safe. * * @param name The application's name given by the developer. The name should should only contain Letters, Numbers and Underscore. * @param options The Firebase application options used to configure the services. */ + (void)configureWithName:(NSString *)name options:(FIROptions *)options; /** * Returns the default app, or nil if the default app does not exist. */ + (nullable FIRApp *)defaultApp NS_SWIFT_NAME(defaultApp()); /** * Returns a previously created FIRApp instance with the given name, or nil if no such app exists. * This method is thread safe. */ + (nullable FIRApp *)appNamed:(NSString *)name; /** * Returns the set of all extant FIRApp instances, or nil if there are no FIRApp instances. This * method is thread safe. */ + (nullable NSDictionary *)allApps; /** * Cleans up the current FIRApp, freeing associated data and returning its name to the pool for * future use. This method is thread safe. */ - (void)deleteApp:(FIRAppVoidBoolCallback)completion; /** * FIRApp instances should not be initialized directly. Call +[FIRApp configure], * +[FIRApp configureWithOptions:], or +[FIRApp configureWithNames:options:] directly. */ - (instancetype)init NS_UNAVAILABLE; /** * Gets the name of this app. */ @property(nonatomic, copy, readonly) NSString *name; /** * Gets the options for this app. */ @property(nonatomic, readonly) FIROptions *options; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRConfiguration.h ================================================ #import #import "FIRAnalyticsConfiguration.h" #import "FIRLoggerLevel.h" /** * The log levels used by FIRConfiguration. */ typedef NS_ENUM(NSInteger, FIRLogLevel) { /** Error */ kFIRLogLevelError __deprecated = 0, /** Warning */ kFIRLogLevelWarning __deprecated, /** Info */ kFIRLogLevelInfo __deprecated, /** Debug */ kFIRLogLevelDebug __deprecated, /** Assert */ kFIRLogLevelAssert __deprecated, /** Max */ kFIRLogLevelMax __deprecated = kFIRLogLevelAssert } DEPRECATED_MSG_ATTRIBUTE( "Use -FIRDebugEnabled and -FIRDebugDisabled or setLoggerLevel. See FIRApp.h for more details."); /** * This interface provides global level properties that the developer can tweak, and the singleton * of the Firebase Analytics configuration class. */ @interface FIRConfiguration : NSObject /** Returns the shared configuration object. */ + (FIRConfiguration *)sharedInstance; /** The configuration class for Firebase Analytics. */ @property(nonatomic, readwrite) FIRAnalyticsConfiguration *analyticsConfiguration; /** Global log level. Defaults to kFIRLogLevelError. */ @property(nonatomic, readwrite, assign) FIRLogLevel logLevel DEPRECATED_MSG_ATTRIBUTE( "Use -FIRDebugEnabled and -FIRDebugDisabled or setLoggerLevel. See FIRApp.h for more details."); /** * Sets the logging level for internal Firebase logging. Firebase will only log messages * that are logged at or below loggerLevel. The messages are logged both to the Xcode * console and to the device's log. Note that if an app is running from AppStore, it will * never log above FIRLoggerLevelNotice even if loggerLevel is set to a higher (more verbose) * setting. * * @param loggerLevel The maximum logging level. The default level is set to FIRLoggerLevelNotice. */ - (void)setLoggerLevel:(FIRLoggerLevel)loggerLevel; @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIRLoggerLevel.h ================================================ /** * The log levels used by internal logging. */ typedef NS_ENUM(NSInteger, FIRLoggerLevel) { FIRLoggerLevelError = 3 /*ASL_LEVEL_ERR*/, FIRLoggerLevelWarning = 4 /*ASL_LEVEL_WARNING*/, FIRLoggerLevelNotice = 5 /*ASL_LEVEL_NOTICE*/, FIRLoggerLevelInfo = 6 /*ASL_LEVEL_INFO*/, FIRLoggerLevelDebug = 7 /*ASL_LEVEL_DEBUG*/, FIRLoggerLevelMin = FIRLoggerLevelError, FIRLoggerLevelMax = FIRLoggerLevelDebug }; ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FIROptions.h ================================================ #import /** * This class provides constant fields of Google APIs. */ @interface FIROptions : NSObject /** * Returns the default options. */ + (FIROptions *)defaultOptions; /** * An iOS API key used for authenticating requests from your app, e.g. * @"AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk", used to identify your app to Google servers. */ @property(nonatomic, readonly, copy) NSString *APIKey; /** * The OAuth2 client ID for iOS application used to authenticate Google users, for example * @"12345.apps.googleusercontent.com", used for signing in with Google. */ @property(nonatomic, readonly, copy) NSString *clientID; /** * The tracking ID for Google Analytics, e.g. @"UA-12345678-1", used to configure Google Analytics. */ @property(nonatomic, readonly, copy) NSString *trackingID; /** * The Project Number from the Google Developer's console, for example @"012345678901", used to * configure Google Cloud Messaging. */ @property(nonatomic, readonly, copy) NSString *GCMSenderID; /** * The Android client ID used in Google AppInvite when an iOS app has its Android version, for * example @"12345.apps.googleusercontent.com". */ @property(nonatomic, readonly, copy) NSString *androidClientID; /** * The Google App ID that is used to uniquely identify an instance of an app. */ @property(nonatomic, readonly, copy) NSString *googleAppID; /** * The database root URL, e.g. @"http://abc-xyz-123.firebaseio.com". */ @property(nonatomic, readonly, copy) NSString *databaseURL; /** * The URL scheme used to set up Durable Deep Link service. */ @property(nonatomic, readwrite, copy) NSString *deepLinkURLScheme; /** * The Google Cloud Storage bucket name, e.g. @"abc-xyz-123.storage.firebase.com". */ @property(nonatomic, readonly, copy) NSString *storageBucket; /** * Initializes a customized instance of FIROptions with keys. googleAppID, bundleID and GCMSenderID * are required. Other keys may required for configuring specific services. */ - (instancetype)initWithGoogleAppID:(NSString *)googleAppID bundleID:(NSString *)bundleID GCMSenderID:(NSString *)GCMSenderID APIKey:(NSString *)APIKey clientID:(NSString *)clientID trackingID:(NSString *)trackingID androidClientID:(NSString *)androidClientID databaseURL:(NSString *)databaseURL storageBucket:(NSString *)storageBucket deepLinkURLScheme:(NSString *)deepLinkURLScheme; /** * Initializes a customized instance of FIROptions from the file at the given plist file path. * For example, * NSString *filePath = * [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; * FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; * Returns nil if the plist file does not exist or is invalid. */ - (instancetype)initWithContentsOfFile:(NSString *)plistPath; @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Headers/FirebaseCore.h ================================================ #import "FIRAnalyticsConfiguration.h" #import "FIRApp.h" #import "FIRConfiguration.h" #import "FIRLoggerLevel.h" #import "FIROptions.h" ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseCore/Frameworks/FirebaseCore.framework/Modules/module.modulemap ================================================ framework module FirebaseCore { umbrella header "FirebaseCore.h" export * module * { export *} link "c++" link "z" link framework "CoreGraphics" link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/FirebaseDatabase ================================================ [File too large to display: 35.0 MB] ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataEventType.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef Firebase_FIRDataEventType_h #define Firebase_FIRDataEventType_h /** * This enum is the set of events that you can observe at a Firebase Database location. */ typedef NS_ENUM(NSInteger, FIRDataEventType) { /// A new child node is added to a location. FIRDataEventTypeChildAdded, /// A child node is removed from a location. FIRDataEventTypeChildRemoved, /// A child node at a location changes. FIRDataEventTypeChildChanged, /// A child node moves relative to the other child nodes at a location. FIRDataEventTypeChildMoved, /// Any data changes at a location or, recursively, at any child node. FIRDataEventTypeValue }; #endif ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDataSnapshot.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import NS_ASSUME_NONNULL_BEGIN @class FIRDatabaseReference; /** * A FIRDataSnapshot contains data from a Firebase Database location. Any time you read * Firebase data, you receive the data as a FIRDataSnapshot. * * FIRDataSnapshots are passed to the blocks you attach with observeEventType:withBlock: or observeSingleEvent:withBlock:. * They are efficiently-generated immutable copies of the data at a Firebase Database location. * They can't be modified and will never change. To modify data at a location, * use a FIRDatabaseReference (e.g. with setValue:). */ @interface FIRDataSnapshot : NSObject #pragma mark - Navigating and inspecting a snapshot /** * Gets a FIRDataSnapshot for the location at the specified relative path. * The relative path can either be a simple child key (e.g. 'fred') * or a deeper slash-separated path (e.g. 'fred/name/first'). If the child * location has no data, an empty FIRDataSnapshot is returned. * * @param childPathString A relative path to the location of child data. * @return The FIRDataSnapshot for the child location. */ - (FIRDataSnapshot *)childSnapshotForPath:(NSString *)childPathString; /** * Return YES if the specified child exists. * * @param childPathString A relative path to the location of a potential child. * @return YES if data exists at the specified childPathString, else NO. */ - (BOOL) hasChild:(NSString *)childPathString; /** * Return YES if the DataSnapshot has any children. * * @return YES if this snapshot has any children, else NO. */ - (BOOL) hasChildren; /** * Return YES if the DataSnapshot contains a non-null value. * * @return YES if this snapshot contains a non-null value, else NO. */ - (BOOL) exists; #pragma mark - Data export /** * Returns the raw value at this location, coupled with any metadata, such as priority. * * Priorities, where they exist, are accessible under the ".priority" key in instances of NSDictionary. * For leaf locations with priorities, the value will be under the ".value" key. */ - (id __nullable) valueInExportFormat; #pragma mark - Properties /** * Returns the contents of this data snapshot as native types. * * Data types returned: * + NSDictionary * + NSArray * + NSNumber (also includes booleans) * + NSString * * @return The data as a native object. */ @property (strong, readonly, nonatomic, nullable) id value; /** * Gets the number of children for this DataSnapshot. * * @return An integer indicating the number of children. */ @property (readonly, nonatomic) NSUInteger childrenCount; /** * Gets a FIRDatabaseReference for the location that this data came from. * * @return A FIRDatabaseReference instance for the location of this data. */ @property (nonatomic, readonly, strong) FIRDatabaseReference * ref; /** * The key of the location that generated this FIRDataSnapshot. * * @return An NSString containing the key for the location of this FIRDataSnapshot. */ @property (strong, readonly, nonatomic) NSString* key; /** * An iterator for snapshots of the child nodes in this snapshot. * You can use the native for..in syntax: * * for (FIRDataSnapshot* child in snapshot.children) { * ... * } * * @return An NSEnumerator of the children. */ @property (strong, readonly, nonatomic) NSEnumerator* children; /** * The priority of the data in this FIRDataSnapshot. * * @return The priority as a string, or nil if no priority was set. */ @property (strong, readonly, nonatomic, nullable) id priority; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabase.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDatabaseReference.h" @class FIRApp; NS_ASSUME_NONNULL_BEGIN /** * The entry point for accessing a Firebase Database. You can get an instance by calling * [FIRDatabase database]. To access a location in the database and read or write data, * use [FIRDatabase reference]. */ @interface FIRDatabase : NSObject /** * Gets the instance of FIRDatabase for the default FIRApp. * * @return A FIRDatabase instance. */ + (FIRDatabase *) database NS_SWIFT_NAME(database()); /** * Gets an instance of FIRDatabase for a specific FIRApp. * * @param app The FIRApp to get a FIRDatabase for. * @return A FIRDatabase instance. */ + (FIRDatabase *) databaseForApp:(FIRApp*)app NS_SWIFT_NAME(database(app:)); /** The FIRApp instance to which this FIRDatabase belongs. */ @property (weak, readonly, nonatomic) FIRApp *app; /** * Gets a FIRDatabaseReference for the root of your Firebase Database. */ - (FIRDatabaseReference *) reference; /** * Gets a FIRDatabaseReference for the provided path. * * @param path Path to a location in your Firebase Database. * @return A FIRDatabaseReference pointing to the specified path. */ - (FIRDatabaseReference *) referenceWithPath:(NSString *)path; /** * Gets a FIRDatabaseReference for the provided URL. The URL must be a URL to a path * within this Firebase Database. To create a FIRDatabaseReference to a different database, * create a FIRApp} with a FIROptions object configured with the appropriate database URL. * * @param url A URL to a path within your database. * @return A FIRDatabaseReference for the provided URL. */ - (FIRDatabaseReference *) referenceFromURL:(NSString *)databaseUrl; /** * The Firebase Database client automatically queues writes and sends them to the server at the earliest opportunity, * depending on network connectivity. In some cases (e.g. offline usage) there may be a large number of writes * waiting to be sent. Calling this method will purge all outstanding writes so they are abandoned. * * All writes will be purged, including transactions and onDisconnect writes. The writes will * be rolled back locally, perhaps triggering events for affected event listeners, and the client will not * (re-)send them to the Firebase Database backend. */ - (void)purgeOutstandingWrites; /** * Shuts down our connection to the Firebase Database backend until goOnline is called. */ - (void)goOffline; /** * Resumes our connection to the Firebase Database backend after a previous goOffline call. */ - (void)goOnline; /** * The Firebase Database client will cache synchronized data and keep track of all writes you've * initiated while your application is running. It seamlessly handles intermittent network * connections and re-sends write operations when the network connection is restored. * * However by default your write operations and cached data are only stored in-memory and will * be lost when your app restarts. By setting this value to `YES`, the data will be persisted * to on-device (disk) storage and will thus be available again when the app is restarted * (even when there is no network connectivity at that time). Note that this property must be * set before creating your first Database reference and only needs to be called once per * application. * */ @property (nonatomic) BOOL persistenceEnabled; /** * By default the Firebase Database client will use up to 10MB of disk space to cache data. If the cache grows beyond * this size, the client will start removing data that hasn't been recently used. If you find that your application * caches too little or too much data, call this method to change the cache size. This property must be set before * creating your first FIRDatabaseReference and only needs to be called once per application. * * Note that the specified cache size is only an approximation and the size on disk may temporarily exceed it * at times. Cache sizes smaller than 1 MB or greater than 100 MB are not supported. */ @property (nonatomic) NSUInteger persistenceCacheSizeBytes; /** * Sets the dispatch queue on which all events are raised. The default queue is the main queue. * * Note that this must be set before creating your first Database reference. */ @property (nonatomic, strong) dispatch_queue_t callbackQueue; /** * Enables verbose diagnostic logging. * * @param enabled YES to enable logging, NO to disable. */ + (void) setLoggingEnabled:(BOOL)enabled; /** Retrieve the Firebase Database SDK version. */ + (NSString *) sdkVersion; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseQuery.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDataEventType.h" #import "FIRDataSnapshot.h" NS_ASSUME_NONNULL_BEGIN /** * A FIRDatabaseHandle is used to identify listeners of Firebase Database events. These handles * are returned by observeEventType: and and can later be passed to removeObserverWithHandle: to * stop receiving updates. */ typedef NSUInteger FIRDatabaseHandle; /** * A FIRDatabaseQuery instance represents a query over the data at a particular location. * * You create one by calling one of the query methods (queryOrderedByChild:, queryStartingAtValue:, etc.) * on a FIRDatabaseReference. The query methods can be chained to further specify the data you are interested in * observing */ @interface FIRDatabaseQuery : NSObject #pragma mark - Attach observers to read data /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; #pragma mark - Detaching observers /** * Detach a block previously attached with observeEventType:withBlock:. * * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. */ - (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; /** * Detach all blocks previously attached to this Firebase Database location with observeEventType:withBlock: */ - (void) removeAllObservers; /** * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept * synced, it will not be evicted from the persistent disk cache. * * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. */ - (void) keepSynced:(BOOL)keepSynced; #pragma mark - Querying and limiting /** * queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; /** * queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; /** * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, * queryEndingAtValue:, or queryEqualToValue:. * * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. */ - (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; /** * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child keys. */ - (FIRDatabaseQuery *) queryOrderedByKey; /** * queryOrderedByValue: is used to generate a reference to a view of the data that's been sorted by child value. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child value. */ - (FIRDatabaseQuery *) queryOrderedByValue; /** * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child priorities. */ - (FIRDatabaseQuery *) queryOrderedByPriority; /** * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value * greater than or equal to startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; /** * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. This is most * useful when implementing pagination in a case where multiple nodes can match the startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; /** * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value * less than or equal to endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; /** * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value * less than endValue, or equal to endValue and with a key less than or equal to childKey. This is most useful when * implementing pagination in a case where multiple nodes can match the endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; /** * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal * to the supplied argument. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @return A FIRDatabaseQuery instance, limited to data with the supplied value. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; /** * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value * equal to the supplied argument and with their key equal to childKey. There will be at most one node that matches * because child keys are unique. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @param childKey The name of nodes with the right value * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; #pragma mark - Properties /** * Gets a FIRDatabaseReference for the location of this query. * * @return A FIRDatabaseReference for the location of this query. */ @property (nonatomic, readonly, strong) FIRDatabaseReference * ref; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRDatabaseReference.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRDatabaseQuery.h" #import "FIRDatabase.h" #import "FIRDataSnapshot.h" #import "FIRMutableData.h" #import "FIRTransactionResult.h" #import "FIRServerValue.h" NS_ASSUME_NONNULL_BEGIN @class FIRDatabase; /** * A FIRDatabaseReference represents a particular location in your Firebase Database * and can be used for reading or writing data to that Firebase Database location. * * This class is the starting point for all Firebase Database operations. After you've * obtained your first FIRDatabaseReference via [FIRDatabase reference], you can use it * to read data (ie. observeEventType:withBlock:), write data (ie. setValue:), and to * create new FIRDatabaseReferences (ie. child:). */ @interface FIRDatabaseReference : FIRDatabaseQuery #pragma mark - Getting references to children locations /** * Gets a FIRDatabaseReference for the location at the specified relative path. * The relative path can either be a simple child key (e.g. 'fred') or a * deeper slash-separated path (e.g. 'fred/name/first'). * * @param pathString A relative path from this location to the desired child location. * @return A FIRDatabaseReference for the specified relative path. */ - (FIRDatabaseReference *)child:(NSString *)pathString; /** * childByAppendingPath: is deprecated, use child: instead. */ - (FIRDatabaseReference *)childByAppendingPath:(NSString *)pathString __deprecated_msg("use child: instead"); /** * childByAutoId generates a new child location using a unique key and returns a * FIRDatabaseReference to it. This is useful when the children of a Firebase Database * location represent a list of items. * * The unique key generated by childByAutoId: is prefixed with a client-generated * timestamp so that the resulting list will be chronologically-sorted. * * @return A FIRDatabaseReference for the generated location. */ - (FIRDatabaseReference *) childByAutoId; #pragma mark - Writing data /** Write data to this Firebase Database location. This will overwrite any data at this location and all child locations. Data types that can be set are: - NSString -- @"Hello World" - NSNumber (also includes boolean) -- @YES, @43, @4.333 - NSDictionary -- @{@"key": @"value", @"nested": @{@"another": @"value"} } - NSArray The effect of the write will be visible immediately and the corresponding events will be triggered. Synchronization of the data to the Firebase Database servers will also be started. Passing null for the new value is equivalent to calling remove:; all data at this location or any child location will be deleted. Note that setValue: will remove any priority stored at this location, so if priority is meant to be preserved, you should use setValue:andPriority: instead. @param value The value to be written. */ - (void) setValue:(nullable id)value; /** * The same as setValue: with a block that gets triggered after the write operation has * been committed to the Firebase Database servers. * * @param value The value to be written. * @param block The block to be called after the write has been committed to the Firebase Database servers. */ - (void) setValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * The same as setValue: with an additional priority to be attached to the data being written. * Priorities are used to order items. * * @param value The value to be written. * @param priority The priority to be attached to that data. */ - (void) setValue:(nullable id)value andPriority:(nullable id)priority; /** * The same as setValue:andPriority: with a block that gets triggered after the write operation has * been committed to the Firebase Database servers. * * @param value The value to be written. * @param priority The priority to be attached to that data. * @param block The block to be called after the write has been committed to the Firebase Database servers. */ - (void) setValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Remove the data at this Firebase Database location. Any data at child locations will also be deleted. * * The effect of the delete will be visible immediately and the corresponding events * will be triggered. Synchronization of the delete to the Firebase Database servers will * also be started. * * remove: is equivalent to calling setValue:nil */ - (void) removeValue; /** * The same as remove: with a block that gets triggered after the remove operation has * been committed to the Firebase Database servers. * * @param block The block to be called after the remove has been committed to the Firebase Database servers. */ - (void) removeValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Sets a priority for the data at this Firebase Database location. * Priorities can be used to provide a custom ordering for the children at a location * (if no priorities are specified, the children are ordered by key). * * You cannot set a priority on an empty location. For this reason * setValue:andPriority: should be used when setting initial data with a specific priority * and setPriority: should be used when updating the priority of existing data. * * Children are sorted based on this priority using the following rules: * * Children with no priority come first. * Children with a number as their priority come next. They are sorted numerically by priority (small to large). * Children with a string as their priority come last. They are sorted lexicographically by priority. * Whenever two children have the same priority (including no priority), they are sorted by key. Numeric * keys come first (sorted numerically), followed by the remaining keys (sorted lexicographically). * * Note that priorities are parsed and ordered as IEEE 754 double-precision floating-point numbers. * Keys are always stored as strings and are treated as numbers only when they can be parsed as a * 32-bit integer * * @param priority The priority to set at the specified location. */ - (void) setPriority:(nullable id)priority; /** * The same as setPriority: with a block that is called once the priority has * been committed to the Firebase Database servers. * * @param priority The priority to set at the specified location. * @param block The block that is triggered after the priority has been written on the servers. */ - (void) setPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Updates the values at the specified paths in the dictionary without overwriting other * keys at this location. * * @param values A dictionary of the keys to change and their new values */ - (void) updateChildValues:(NSDictionary *)values; /** * The same as update: with a block that is called once the update has been committed to the * Firebase Database servers * * @param values A dictionary of the keys to change and their new values * @param block The block that is triggered after the update has been written on the Firebase Database servers */ - (void) updateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; #pragma mark - Attaching observers to read data /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * Use removeObserverWithHandle: to stop receiving updates. * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * observeEventType:withBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * observeEventType:andPreviousSiblingKeyWithBlock: is used to listen for data changes at a particular location. * This is the primary way to read data from the Firebase Database. Your block will be triggered * for the initial data and again whenever the data changes. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you will no longer receive new events due to no longer having permission. * * Use removeObserverWithHandle: to stop receiving updates. * * @param eventType The type of event to listen for. * @param block The block that should be called with initial data and updates. It is passed the data as a FIRDataSnapshot * and the previous child's key. * @param cancelBlock The block that should be called if this client no longer has permission to receive these events * @return A handle used to unregister this block later using removeObserverWithHandle: */ - (FIRDatabaseHandle)observeEventType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType withBlock:(void (^)(FIRDataSnapshot *snapshot))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; /** * This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned. In addition, for FIRDataEventTypeChildAdded, FIRDataEventTypeChildMoved, and * FIRDataEventTypeChildChanged events, your block will be passed the key of the previous node by priority order. * * The cancelBlock will be called if you do not have permission to read data at this location. * * @param eventType The type of event to listen for. * @param block The block that should be called. It is passed the data as a FIRDataSnapshot and the previous child's key. * @param cancelBlock The block that will be called if you don't have permission to access this data */ - (void)observeSingleEventOfType:(FIRDataEventType)eventType andPreviousSiblingKeyWithBlock:(void (^)(FIRDataSnapshot *snapshot, NSString *__nullable prevKey))block withCancelBlock:(nullable void (^)(NSError* error))cancelBlock; #pragma mark - Detaching observers /** * Detach a block previously attached with observeEventType:withBlock:. * * @param handle The handle returned by the call to observeEventType:withBlock: which we are trying to remove. */ - (void) removeObserverWithHandle:(FIRDatabaseHandle)handle; /** * By calling `keepSynced:YES` on a location, the data for that location will automatically be downloaded and * kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept * synced, it will not be evicted from the persistent disk cache. * * @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization. */ - (void) keepSynced:(BOOL)keepSynced; /** * Removes all observers at the current reference, but does not remove any observers at child references. * removeAllObservers must be called again for each child reference where a listener was established to remove the observers. */ - (void) removeAllObservers; #pragma mark - Querying and limiting /** * queryLimitedToFirst: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToFirst: will respond to at most the first limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToFirst:(NSUInteger)limit; /** * queryLimitedToLast: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryLimitedToLast: will respond to at most the last limit child nodes. * * @param limit The upper bound, inclusive, for the number of child nodes to receive events for * @return A FIRDatabaseQuery instance, limited to at most limit child nodes. */ - (FIRDatabaseQuery *)queryLimitedToLast:(NSUInteger)limit; /** * queryOrderBy: is used to generate a reference to a view of the data that's been sorted by the values of * a particular child key. This method is intended to be used in combination with queryStartingAtValue:, * queryEndingAtValue:, or queryEqualToValue:. * * @param key The child key to use in ordering data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, ordered by the values of the specified child key. */ - (FIRDatabaseQuery *)queryOrderedByChild:(NSString *)key; /** * queryOrderedByKey: is used to generate a reference to a view of the data that's been sorted by child key. * This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child keys. */ - (FIRDatabaseQuery *) queryOrderedByKey; /** * queryOrderedByPriority: is used to generate a reference to a view of the data that's been sorted by child * priority. This method is intended to be used in combination with queryStartingAtValue:, queryEndingAtValue:, * or queryEqualToValue:. * * @return A FIRDatabaseQuery instance, ordered by child priorities. */ - (FIRDatabaseQuery *) queryOrderedByPriority; /** * queryStartingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue: will respond to events at nodes with a value * greater than or equal to startValue. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue; /** * queryStartingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryStartingAtValue:childKey will respond to events at nodes with a value * greater than startValue, or equal to startValue and with a key greater than or equal to childKey. * * @param startValue The lower bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The lower bound, inclusive, for the key of nodes with value equal to startValue * @return A FIRDatabaseQuery instance, limited to data with value greater than or equal to startValue */ - (FIRDatabaseQuery *)queryStartingAtValue:(nullable id)startValue childKey:(nullable NSString *)childKey; /** * queryEndingAtValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue: will respond to events at nodes with a value * less than or equal to endValue. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue; /** * queryEndingAtValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEndingAtValue:childKey will respond to events at nodes with a value * less than endValue, or equal to endValue and with a key less than or equal to childKey. * * @param endValue The upper bound, inclusive, for the value of data visible to the returned FIRDatabaseQuery * @param childKey The upper bound, inclusive, for the key of nodes with value equal to endValue * @return A FIRDatabaseQuery instance, limited to data with value less than or equal to endValue */ - (FIRDatabaseQuery *)queryEndingAtValue:(nullable id)endValue childKey:(nullable NSString *)childKey; /** * queryEqualToValue: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue: will respond to events at nodes with a value equal * to the supplied argument. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @return A FIRDatabaseQuery instance, limited to data with the supplied value. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value; /** * queryEqualToValue:childKey: is used to generate a reference to a limited view of the data at this location. * The FIRDatabaseQuery instance returned by queryEqualToValue:childKey will respond to events at nodes with a value * equal to the supplied argument with a key equal to childKey. There will be at most one node that matches because * child keys are unique. * * @param value The value that the data returned by this FIRDatabaseQuery will have * @param childKey The key of nodes with the right value * @return A FIRDatabaseQuery instance, limited to data with the supplied value and the key. */ - (FIRDatabaseQuery *)queryEqualToValue:(nullable id)value childKey:(nullable NSString *)childKey; #pragma mark - Managing presence /** * Ensure the data at this location is set to the specified value when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * onDisconnectSetValue: is especially useful for implementing "presence" systems, * where a value should be changed or cleared when a user disconnects * so that he appears "offline" to other users. * * @param value The value to be set after the connection is lost. */ - (void) onDisconnectSetValue:(nullable id)value; /** * Ensure the data at this location is set to the specified value when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers * * @param value The value to be set after the connection is lost. * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectSetValue:(nullable id)value withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data at this location is set to the specified value and priority when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * @param value The value to be set after the connection is lost. * @param priority The priority to be set after the connection is lost. */ - (void) onDisconnectSetValue:(nullable id)value andPriority:(id)priority; /** * Ensure the data at this location is set to the specified value and priority when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * The completion block will be triggered when the operation has been successfully queued up on the Firebase Database servers * * @param value The value to be set after the connection is lost. * @param priority The priority to be set after the connection is lost. * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectSetValue:(nullable id)value andPriority:(nullable id)priority withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data at this location is removed when * the client is disconnected (due to closing the app, navigating * to a new page, or network issues). * * onDisconnectRemoveValue is especially useful for implementing "presence" systems. */ - (void) onDisconnectRemoveValue; /** * Ensure the data at this location is removed when * the client is disconnected (due to closing the app, navigating * to a new page, or network issues). * * onDisconnectRemoveValueWithCompletionBlock: is especially useful for implementing "presence" systems. * * @param block Block to be triggered when the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectRemoveValueWithCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Ensure the data has the specified child values updated when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * * @param values A dictionary of child node keys and the values to set them to after the connection is lost. */ - (void) onDisconnectUpdateChildValues:(NSDictionary *)values; /** * Ensure the data has the specified child values updated when * the client is disconnected (due to closing the browser, navigating * to a new page, or network issues). * * * @param values A dictionary of child node keys and the values to set them to after the connection is lost. * @param block A block that will be called once the operation has been queued up on the Firebase Database servers */ - (void) onDisconnectUpdateChildValues:(NSDictionary *)values withCompletionBlock:(void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; /** * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the * connection is lost, call cancelDisconnectOperations: */ - (void) cancelDisconnectOperations; /** * Cancel any operations that are set to run on disconnect. If you previously called onDisconnectSetValue:, * onDisconnectRemoveValue:, or onDisconnectUpdateChildValues:, and no longer want the values updated when the * connection is lost, call cancelDisconnectOperations: * * @param block A block that will be triggered once the Firebase Database servers have acknowledged the cancel request. */ - (void) cancelDisconnectOperationsWithCompletionBlock:(nullable void (^)(NSError *__nullable error, FIRDatabaseReference * ref))block; #pragma mark - Manual Connection Management /** * Manually disconnect the Firebase Database client from the server and disable automatic reconnection. * * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) * and goOnline( ) methods may be used to manually control the client connection in cases where * a persistent connection is undesirable. * * While offline, the Firebase Database client will no longer receive data updates from the server. However, * all database operations performed locally will continue to immediately fire events, allowing * your application to continue behaving normally. Additionally, each operation performed locally * will automatically be queued and retried upon reconnection to the Firebase Database server. * * To reconnect to the Firebase Database server and begin receiving remote events, see goOnline( ). * Once the connection is reestablished, the Firebase Database client will transmit the appropriate data * and fire the appropriate events so that your client "catches up" automatically. * * Note: Invoking this method will impact all Firebase Database connections. */ + (void) goOffline; /** * Manually reestablish a connection to the Firebase Database server and enable automatic reconnection. * * The Firebase Database client automatically maintains a persistent connection to the Firebase Database server, * which will remain active indefinitely and reconnect when disconnected. However, the goOffline( ) * and goOnline( ) methods may be used to manually control the client connection in cases where * a persistent connection is undesirable. * * This method should be used after invoking goOffline( ) to disable the active connection. * Once reconnected, the Firebase Database client will automatically transmit the proper data and fire * the appropriate events so that your client "catches up" automatically. * * To disconnect from the Firebase Database server, see goOffline( ). * * Note: Invoking this method will impact all Firebase Database connections. */ + (void) goOnline; #pragma mark - Transactions /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult */ - (void) runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block; /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by returning [FIRTransactionResult abort]. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. */ - (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock; /** * Performs an optimistic-concurrency transactional update to the data at this location. Your block will be called with a FIRMutableData * instance that contains the current data at this location. Your block should update this data to the value you * wish to write to this location, and then return an instance of FIRTransactionResult with the new data. * * If, when the operation reaches the server, it turns out that this client had stale data, your block will be run * again with the latest data from the server. * * When your block is run, you may decide to abort the transaction by return [FIRTransactionResult abort]. * * Since your block may be run multiple times, this client could see several immediate states that don't exist on the server. You can suppress those immediate states until the server confirms the final state of the transaction. * * @param block This block receives the current data at this location and must return an instance of FIRTransactionResult * @param completionBlock This block will be triggered once the transaction is complete, whether it was successful or not. It will indicate if there was an error, whether or not the data was committed, and what the current value of the data at this location is. * @param localEvents Set this to NO to suppress events raised for intermediate states, and only get events based on the final state of the transaction. */ - (void)runTransactionBlock:(FIRTransactionResult * (^) (FIRMutableData* currentData))block andCompletionBlock:(nullable void (^) (NSError *__nullable error, BOOL committed, FIRDataSnapshot *__nullable snapshot))completionBlock withLocalEvents:(BOOL)localEvents; #pragma mark - Retrieving String Representation /** * Gets the absolute URL of this Firebase Database location. * * @return The absolute URL of the referenced Firebase Database location. */ - (NSString *) description; #pragma mark - Properties /** * Gets a FIRDatabaseReference for the parent location. * If this instance refers to the root of your Firebase Database, it has no parent, * and therefore parent( ) will return null. * * @return A FIRDatabaseReference for the parent location. */ @property (strong, readonly, nonatomic, nullable) FIRDatabaseReference * parent; /** * Gets a FIRDatabaseReference for the root location * * @return A new FIRDatabaseReference to root location. */ @property (strong, readonly, nonatomic) FIRDatabaseReference * root; /** * Gets the last token in a Firebase Database location (e.g. 'fred' in https://SampleChat.firebaseIO-demo.com/users/fred) * * @return The key of the location this reference points to. */ @property (strong, readonly, nonatomic) NSString* key; /** * Gets the URL for the Firebase Database location referenced by this FIRDatabaseReference. * * @return The url of the location this reference points to. */ @property (strong, readonly, nonatomic) NSString* URL; /** * Gets the FIRDatabase instance associated with this reference. * * @return The FIRDatabase object for this reference. */ @property (strong, readonly, nonatomic) FIRDatabase *database; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRMutableData.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import NS_ASSUME_NONNULL_BEGIN /** * A FIRMutableData instance is populated with data from a Firebase Database location. * When you are using runTransactionBlock:, you will be given an instance containing the current * data at that location. Your block will be responsible for updating that instance to the data * you wish to save at that location, and then returning using [FIRTransactionResult successWithValue:]. * * To modify the data, set its value property to any of the native types support by Firebase Database: * * + NSNumber (includes BOOL) * + NSDictionary * + NSArray * + NSString * + nil / NSNull to remove the data * * Note that changes made to a child FIRMutableData instance will be visible to the parent. */ @interface FIRMutableData : NSObject #pragma mark - Inspecting and navigating the data /** * Returns boolean indicating whether this mutable data has children. * * @return YES if this data contains child nodes. */ - (BOOL) hasChildren; /** * Indicates whether this mutable data has a child at the given path. * * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' * @return YES if this data contains a child at the specified relative path */ - (BOOL) hasChildAtPath:(NSString *)path; /** * Used to obtain a FIRMutableData instance that encapsulates the data at the given relative path. * Note that changes made to the child will be visible to the parent. * * @param path A path string, consisting either of a single segment, like 'child', or multiple segments, 'a/deeper/child' * @return A FIRMutableData instance containing the data at the given path */ - (FIRMutableData *)childDataByAppendingPath:(NSString *)path; #pragma mark - Properties /** * To modify the data contained by this instance of FIRMutableData, set this to any of the native types supported by Firebase Database: * * + NSNumber (includes BOOL) * + NSDictionary * + NSArray * + NSString * + nil / NSNull to remove the data * * Note that setting this value will override the priority at this location. * * @return The current data at this location as a native object */ @property (strong, nonatomic, nullable) id value; /** * Set this property to update the priority of the data at this location. Can be set to the following types: * * + NSNumber * + NSString * + nil / NSNull to remove the priority * * @return The priority of the data at this location */ @property (strong, nonatomic, nullable) id priority; /** * @return The number of child nodes at this location */ @property (readonly, nonatomic) NSUInteger childrenCount; /** * Used to iterate over the children at this location. You can use the native for .. in syntax: * * for (FIRMutableData* child in data.children) { * ... * } * * Note that this enumerator operates on an immutable copy of the child list. So, you can modify the instance * during iteration, but the new additions will not be visible until you get a new enumerator. */ @property (readonly, nonatomic, strong) NSEnumerator* children; /** * @return The key name of this node, or nil if it is the top-most location */ @property (readonly, nonatomic, strong, nullable) NSString* key; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRServerValue.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ NS_ASSUME_NONNULL_BEGIN /** * Placeholder values you may write into Firebase Database as a value or priority * that will automatically be populated by the Firebase Database server. */ @interface FIRServerValue : NSObject /** * Placeholder value for the number of milliseconds since the Unix epoch */ + (NSDictionary *) timestamp; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FIRTransactionResult.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2013 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import #import "FIRMutableData.h" NS_ASSUME_NONNULL_BEGIN /** * Used for runTransactionBlock:. An FIRTransactionResult instance is a container for the results of the transaction. */ @interface FIRTransactionResult : NSObject /** * Used for runTransactionBlock:. Indicates that the new value should be saved at this location * * @param value A FIRMutableData instance containing the new value to be set * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: */ + (FIRTransactionResult *)successWithValue:(FIRMutableData *)value; /** * Used for runTransactionBlock:. Indicates that the current transaction should no longer proceed. * * @return An FIRTransactionResult instance that can be used as a return value from the block given to runTransactionBlock: */ + (FIRTransactionResult *) abort; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Headers/FirebaseDatabase.h ================================================ /* * Firebase iOS Client Library * * Copyright © 2016 Firebase - All Rights Reserved * https://www.firebase.com * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binaryform must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY FIREBASE AS IS AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL FIREBASE BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FirebaseDatabase_h #define FirebaseDatabase_h #import "FIRDatabase.h" #import "FIRDatabaseQuery.h" #import "FIRDatabaseReference.h" #import "FIRDataEventType.h" #import "FIRDataSnapshot.h" #import "FIRMutableData.h" #import "FIRServerValue.h" #import "FIRTransactionResult.h" #endif /* FirebaseDatabase_h */ ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/Modules/module.modulemap ================================================ framework module FirebaseDatabase { umbrella header "FirebaseDatabase.h" export * module * { export * } link framework "CFNetwork" link framework "Security" link framework "SystemConfiguration" link "c++" link "icucore" } ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseDatabase/Frameworks/FirebaseDatabase.framework/NOTICE ================================================ Google LevelDB Copyright (c) 2011 The LevelDB Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- Square Socket Rocket Copyright 2012 Square Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -- APLevelDB Created by Adam Preble on 1/23/12. Copyright (c) 2012 Adam Preble. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseInstanceID/CHANGELOG.md ================================================ # 2017-01-31 -- v1.0.9 - Removed an error being mistakenly logged to the console. # 2016-07-06 -- v1.0.8 - Don't store InstanceID plists in Documents folder. # 2016-06-19 -- v1.0.7 - Fix remote-notifications warning on app submission. # 2016-05-16 -- v1.0.6 - Fix CocoaPod linter issues for InstanceID pod. # 2016-05-13 -- v1.0.5 - Fix Authorization errors for InstanceID tokens. # 2016-05-11 -- v1.0.4 - Reduce wait for InstanceID token during parallel requests. # 2016-04-18 -- v1.0.3 - Change flag to disable swizzling to *FirebaseAppDelegateProxyEnabled*. - Fix incessant Keychain errors while accessing InstanceID. - Fix max retries for fetching IID token. # 2016-04-18 -- v1.0.2 - Register for remote notifications on iOS8+ in the SDK itself. ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FIRInstanceID.h ================================================ #import /** * @memberof FIRInstanceID * * The scope to be used when fetching/deleting a token for Firebase Messaging. */ FOUNDATION_EXPORT NSString * __nonnull const kFIRInstanceIDScopeFirebaseMessaging; /** * Called when the system determines that tokens need to be refreshed. * This method is also called if Instance ID has been reset in which * case, tokens and FCM topic subscriptions also need to be refreshed. * * Instance ID service will throttle the refresh event across all devices * to control the rate of token updates on application servers. */ FOUNDATION_EXPORT NSString * __nonnull const kFIRInstanceIDTokenRefreshNotification; /** * @related FIRInstanceID * * The completion handler invoked when the InstanceID token returns. If * the call fails we return the appropriate `error code` as described below. * * @param token The valid token as returned by InstanceID backend. * * @param error The error describing why generating a new token * failed. See the error codes below for a more detailed * description. */ typedef void(^FIRInstanceIDTokenHandler)( NSString * __nullable token, NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the InstanceID `deleteToken` returns. If * the call fails we return the appropriate `error code` as described below * * @param error The error describing why deleting the token failed. * See the error codes below for a more detailed description. */ typedef void(^FIRInstanceIDDeleteTokenHandler)(NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the app identity is created. If the * identity wasn't created for some reason we return the appropriate error code. * * @param identity A valid identity for the app instance, nil if there was an error * while creating an identity. * @param error The error if fetching the identity fails else nil. */ typedef void(^FIRInstanceIDHandler)(NSString * __nullable identity, NSError * __nullable error); /** * @related FIRInstanceID * * The completion handler invoked when the app identity and all the tokens associated * with it are deleted. Returns a valid error object in case of failure else nil. * * @param error The error if deleting the identity and all the tokens associated with * it fails else nil. */ typedef void(^FIRInstanceIDDeleteHandler)(NSError * __nullable error); /** * @enum FIRInstanceIDError */ typedef NS_ENUM(NSUInteger, FIRInstanceIDError) { // Http related errors. /// Unknown error. FIRInstanceIDErrorUnknown = 0, /// Auth Error -- GCM couldn't validate request from this client. FIRInstanceIDErrorAuthentication = 1, /// NoAccess -- InstanceID service cannot be accessed. FIRInstanceIDErrorNoAccess = 2, /// Timeout -- Request to InstanceID backend timed out. FIRInstanceIDErrorTimeout = 3, /// Network -- No network available to reach the servers. FIRInstanceIDErrorNetwork = 4, /// OperationInProgress -- Another similar operation in progress, /// bailing this one. FIRInstanceIDErrorOperationInProgress = 5, /// InvalidRequest -- Some parameters of the request were invalid. FIRInstanceIDErrorInvalidRequest = 7, }; /** * The APNS token type for the app. If the token type is set to `UNKNOWN` * InstanceID will implicitly try to figure out what the actual token type * is from the provisioning profile. */ typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) { /// Unknown token type. FIRInstanceIDAPNSTokenTypeUnknown, /// Sandbox token type. FIRInstanceIDAPNSTokenTypeSandbox, /// Production token type. FIRInstanceIDAPNSTokenTypeProd, }; /** * Instance ID provides a unique identifier for each app instance and a mechanism * to authenticate and authorize actions (for example, sending a GCM message). * * Instance ID is long lived but, may be reset if the device is not used for * a long time or the Instance ID service detects a problem. * If Instance ID is reset, the app will be notified via * `kFIRInstanceIDTokenRefreshNotification`. * * If the Instance ID has become invalid, the app can request a new one and * send it to the app server. * To prove ownership of Instance ID and to allow servers to access data or * services associated with the app, call * `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. */ @interface FIRInstanceID : NSObject /** * FIRInstanceID. * * @return A shared instance of FIRInstanceID. */ + (nonnull instancetype)instanceID NS_SWIFT_NAME(instanceID()); /** * Unavailable. Use +instanceID instead. */ - (nonnull instancetype)init __attribute__((unavailable("Use +instanceID instead."))); /** * Set APNS token for the application. This APNS token will be used to register * with Firebase Messaging using `token` or * `tokenWithAuthorizedEntity:scope:options:handler`. If the token type is set to * `FIRInstanceIDAPNSTokenTypeUnknown` InstanceID will read the provisioning profile * to find out the token type. * * @param token The APNS token for the application. * @param type The APNS token type for the above token. */ - (void)setAPNSToken:(nonnull NSData *)token type:(FIRInstanceIDAPNSTokenType)type; #pragma mark - Tokens /** * Returns a Firebase Messaging scoped token for the firebase app. * * @return Null Returns null if the device has not yet been registerd with * Firebase Message else returns a valid token. */ - (nullable NSString *)token; /** * Returns a token that authorizes an Entity (example: cloud service) to perform * an action on behalf of the application identified by Instance ID. * * This is similar to an OAuth2 token except, it applies to the * application instance instead of a user. * * This is an asynchronous call. If the token fetching fails for some reason * we invoke the completion callback with nil `token` and the appropriate * error. * * Note, you can only have one `token` or `deleteToken` call for a given * authorizedEntity and scope at any point of time. Making another such call with the * same authorizedEntity and scope before the last one finishes will result in an * error with code `OperationInProgress`. * * @see FIRInstanceID deleteTokenWithAuthorizedEntity:scope:handler: * * @param authorizedEntity Entity authorized by the token. * @param scope Action authorized for authorizedEntity. * @param options The extra options to be sent with your token request. The * value for the `apns_token` should be the NSData object * passed to UIApplication's * `didRegisterForRemoteNotificationsWithDeviceToken` method. * All other keys and values in the options dict need to be * instances of NSString or else they will be discarded. Bundle * keys starting with 'GCM.' and 'GOOGLE.' are reserved. * @param handler The callback handler which is invoked when the token is * successfully fetched. In case of success a valid `token` and * `nil` error are returned. In case of any error the `token` * is nil and a valid `error` is returned. The valid error * codes have been documented above. */ - (void)tokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity scope:(nonnull NSString *)scope options:(nullable NSDictionary *)options handler:(nonnull FIRInstanceIDTokenHandler)handler; /** * Revokes access to a scope (action) for an entity previously * authorized by `[FIRInstanceID tokenWithAuthorizedEntity:scope:options:handler]`. * * This is an asynchronous call. Call this on the main thread since InstanceID lib * is not thread safe. In case token deletion fails for some reason we invoke the * `handler` callback passed in with the appropriate error code. * * Note, you can only have one `token` or `deleteToken` call for a given * authorizedEntity and scope at a point of time. Making another such call with the * same authorizedEntity and scope before the last one finishes will result in an error * with code `OperationInProgress`. * * @param authorizedEntity Entity that must no longer have access. * @param scope Action that entity is no longer authorized to perform. * @param handler The handler that is invoked once the unsubscribe call ends. * In case of error an appropriate error object is returned * else error is nil. */ - (void)deleteTokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity scope:(nonnull NSString *)scope handler:(nonnull FIRInstanceIDDeleteTokenHandler)handler; #pragma mark - Identity /** * Asynchronously fetch a stable identifier that uniquely identifies the app * instance. If the identifier has been revoked or has expired, this method will * return a new identifier. * * * @param handler The handler to invoke once the identifier has been fetched. * In case of error an appropriate error object is returned else * a valid identifier is returned and a valid identifier for the * application instance. */ - (void)getIDWithHandler:(nonnull FIRInstanceIDHandler)handler; /** * Resets Instance ID and revokes all tokens. */ - (void)deleteIDWithHandler:(nonnull FIRInstanceIDDeleteHandler)handler; @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Headers/FirebaseInstanceID.h ================================================ #import "FIRInstanceID.h" ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseInstanceID/Frameworks/FirebaseInstanceID.framework/Modules/module.modulemap ================================================ framework module FirebaseInstanceID { umbrella header "FirebaseInstanceID.h" export * module * { export *} link framework "Foundation" link framework "UIKit" } ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseInstanceID/README.md ================================================ # InstanceID SDK for iOS Instance ID provides a unique ID per instance of your apps and also provides a mechanism to authenticate and authorize actions, like sending messages via Firebase Cloud Messaging (FCM). Please visit [our developer site](https://developers.google.com/instance-id/) for integration instructions, documentation, support information, and terms of service. ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseMessaging/Frameworks/FirebaseMessaging.framework/Headers/FIRMessaging.h ================================================ #import /** * The completion handler invoked once the data connection with FIRMessaging is * established. The data connection is used to send a continous stream of * data and all the FIRMessaging data notifications arrive through this connection. * Once the connection is established we invoke the callback with `nil` error. * Correspondingly if we get an error while trying to establish a connection * we invoke the handler with an appropriate error object and do an * exponential backoff to try and connect again unless successful. * * @param error The error object if any describing why the data connection * to FIRMessaging failed. */ typedef void(^FIRMessagingConnectCompletion)(NSError * __nullable error); /** * Notification sent when the upstream message has been delivered * successfully to the server. The notification object will be the messageID * of the successfully delivered message. */ FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingSendSuccessNotification; /** * Notification sent when the upstream message was failed to be sent to the * server. The notification object will be the messageID of the failed * message. The userInfo dictionary will contain the relevant error * information for the failure. */ FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingSendErrorNotification; /** * Notification sent when the Firebase messaging server deletes pending * messages due to exceeded storage limits. This may occur, for example, when * the device cannot be reached for an extended period of time. * * It is recommended to retrieve any missing messages directly from the * server. */ FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingMessagesDeletedNotification; /** * @enum FIRMessagingError */ typedef NS_ENUM(NSUInteger, FIRMessagingError) { /// Unknown error. FIRMessagingErrorUnknown = 0, /// FIRMessaging couldn't validate request from this client. FIRMessagingErrorAuthentication = 1, /// InstanceID service cannot be accessed. FIRMessagingErrorNoAccess = 2, /// Request to InstanceID backend timed out. FIRMessagingErrorTimeout = 3, /// No network available to reach the servers. FIRMessagingErrorNetwork = 4, /// Another similar operation in progress, bailing this one. FIRMessagingErrorOperationInProgress = 5, /// Some parameters of the request were invalid. FIRMessagingErrorInvalidRequest = 7, }; /// Status for the downstream message received by the app. typedef NS_ENUM(NSInteger, FIRMessagingMessageStatus) { /// Unknown status. FIRMessagingMessageStatusUnknown, /// New downstream message received by the app. FIRMessagingMessageStatusNew, }; /// Information about a downstream message received by the app. @interface FIRMessagingMessageInfo : NSObject /// The status of the downstream message @property(nonatomic, readonly, assign) FIRMessagingMessageStatus status; @end /** * A remote data message received by the app via FCM (not just the APNs interface). * * This is only for devices running iOS 10 or above. To support devices running iOS 9 or below, use * the local and remote notifications handlers defined in UIApplicationDelegate protocol. */ @interface FIRMessagingRemoteMessage : NSObject /// The downstream message received by the application. @property(nonatomic, readonly, strong, nonnull) NSDictionary *appData; @end /** * A protocol to receive data message via FCM for devices running iOS 10 or above. * * To support devices running iOS 9 or below, use the local and remote notifications handlers * defined in UIApplicationDelegate protocol. */ @protocol FIRMessagingDelegate /// The callback to handle data message received via FCM for devices running iOS 10 or above. - (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage; @end /** * Firebase Messaging lets you reliably deliver messages at no cost. * * To send or receive messages, the app must get a * registration token from FIRInstanceID. This token authorizes an * app server to send messages to an app instance. * * In order to receive FIRMessaging messages, declare `application:didReceiveRemoteNotification:`. * * */ @interface FIRMessaging : NSObject /** * Delegate to handle remote data messages received via FCM for devices running iOS 10 or above. */ @property(nonatomic, weak, nullable) id remoteMessageDelegate; /** * FIRMessaging * * @return An instance of FIRMessaging. */ + (nonnull instancetype)messaging NS_SWIFT_NAME(messaging()); /** * Unavailable. Use +messaging instead. */ - (nonnull instancetype)init __attribute__((unavailable("Use +messaging instead."))); #pragma mark - Connect /** * Create a FIRMessaging data connection which will be used to send the data notifications * sent by your server. It will also be used to send ACKS and other messages based * on the FIRMessaging ACKS and other messages based on the FIRMessaging protocol. * * * @param handler The handler to be invoked once the connection is established. * If the connection fails we invoke the handler with an * appropriate error code letting you know why it failed. At * the same time, FIRMessaging performs exponential backoff to retry * establishing a connection and invoke the handler when successful. */ - (void)connectWithCompletion:(nonnull FIRMessagingConnectCompletion)handler; /** * Disconnect the current FIRMessaging data connection. This stops any attempts to * connect to FIRMessaging. Calling this on an already disconnected client is a no-op. * * Call this before `teardown` when your app is going to the background. * Since the FIRMessaging connection won't be allowed to live when in background it is * prudent to close the connection. */ - (void)disconnect; #pragma mark - Topics /** * Asynchronously subscribes to a topic. * * @param topic The name of the topic, for example, @"sports". */ - (void)subscribeToTopic:(nonnull NSString *)topic; /** * Asynchronously unsubscribe from a topic. * * @param topic The name of the topic, for example @"sports". */ - (void)unsubscribeFromTopic:(nonnull NSString *)topic; #pragma mark - Upstream /** * Sends an upstream ("device to cloud") message. * * The message is queued if we don't have an active connection. * You can only use the upstream feature if your FCM implementation * uses the XMPP server protocol. * * @param message Key/Value pairs to be sent. Values must be String, any * other type will be ignored. * @param to A string identifying the receiver of the message. For FCM * project IDs the value is `SENDER_ID@gcm.googleapis.com`. * @param messageID The ID of the message. This is generated by the application. It * must be unique for each message generated by this application. * It allows error callbacks and debugging, to uniquely identify * each message. * @param ttl The time to live for the message. In case we aren't able to * send the message before the TTL expires we will send you a * callback. If 0, we'll attempt to send immediately and return * an error if we're not connected. Otherwise, the message will * be queued. As for server-side messages, we don't return an error * if the message has been dropped because of TTL; this can happen * on the server side, and it would require extra communication. */ - (void)sendMessage:(nonnull NSDictionary *)message to:(nonnull NSString *)receiver withMessageID:(nonnull NSString *)messageID timeToLive:(int64_t)ttl; #pragma mark - Analytics /** * Use this to track message delivery and analytics for messages, typically * when you receive a notification in `application:didReceiveRemoteNotification:`. * However, you only need to call this if you set the `FirebaseAppDelegateProxyEnabled` * flag to NO in your Info.plist. If `FirebaseAppDelegateProxyEnabled` is either missing * or set to YES in your Info.plist, the library will call this automatically. * * @param message The downstream message received by the application. * * @return Information about the downstream message. */ - (nonnull FIRMessagingMessageInfo *)appDidReceiveMessage:(nonnull NSDictionary *)message; @end ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseMessaging/Frameworks/FirebaseMessaging.framework/Headers/FirebaseMessaging.h ================================================ #import "FIRMessaging.h" ================================================ FILE: iOS/User/ezshopUser/Pods/FirebaseMessaging/Frameworks/FirebaseMessaging.framework/Modules/module.modulemap ================================================ framework module FirebaseMessaging { umbrella header "FirebaseMessaging.h" export * module * { export *} link "sqlite3" link "z" link framework "CoreGraphics" link framework "Foundation" link framework "SystemConfiguration" link framework "UIKit" } ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/Foundation/GTMLogger.h ================================================ // // GTMLogger.h // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // // Key Abstractions // ---------------- // // This file declares multiple classes and protocols that are used by the // GTMLogger logging system. The 4 main abstractions used in this file are the // following: // // * logger (GTMLogger) - The main logging class that users interact with. It // has methods for logging at different levels and uses a log writer, a log // formatter, and a log filter to get the job done. // // * log writer (GTMLogWriter) - Writes a given string to some log file, where // a "log file" can be a physical file on disk, a POST over HTTP to some URL, // or even some in-memory structure (e.g., a ring buffer). // // * log formatter (GTMLogFormatter) - Given a format string and arguments as // a va_list, returns a single formatted NSString. A "formatted string" could // be a string with the date prepended, a string with values in a CSV format, // or even a string of XML. // // * log filter (GTMLogFilter) - Given a formatted log message as an NSString // and the level at which the message is to be logged, this class will decide // whether the given message should be logged or not. This is a flexible way // to filter out messages logged at a certain level, messages that contain // certain text, or filter nothing out at all. This gives the caller the // flexibility to dynamically enable debug logging in Release builds. // // This file also declares some classes to handle the common log writer, log // formatter, and log filter cases. Callers can also create their own writers, // formatters, and filters and they can even build them on top of the ones // declared here. Keep in mind that your custom writer/formatter/filter may be // called from multiple threads, so it must be thread-safe. #import #import "GTMDefines.h" // Predeclaration of used protocols that are declared later in this file. @protocol GTMLogWriter, GTMLogFormatter, GTMLogFilter; // GTMLogger // // GTMLogger is the primary user-facing class for an object-oriented logging // system. It is built on the concept of log formatters (GTMLogFormatter), log // writers (GTMLogWriter), and log filters (GTMLogFilter). When a message is // sent to a GTMLogger to log a message, the message is formatted using the log // formatter, then the log filter is consulted to see if the message should be // logged, and if so, the message is sent to the log writer to be written out. // // GTMLogger is intended to be a flexible and thread-safe logging solution. Its // flexibility comes from the fact that GTMLogger instances can be customized // with user defined formatters, filters, and writers. And these writers, // filters, and formatters can be combined, stacked, and customized in arbitrary // ways to suit the needs at hand. For example, multiple writers can be used at // the same time, and a GTMLogger instance can even be used as another // GTMLogger's writer. This allows for arbitrarily deep logging trees. // // A standard GTMLogger uses a writer that sends messages to standard out, a // formatter that smacks a timestamp and a few other bits of interesting // information on the message, and a filter that filters out debug messages from // release builds. Using the standard log settings, a log message will look like // the following: // // 2007-12-30 10:29:24.177 myapp[4588/0xa07d0f60] [lvl=1] foo= // // The output contains the date and time of the log message, the name of the // process followed by its process ID/thread ID, the log level at which the // message was logged (in the previous example the level was 1: // kGTMLoggerLevelDebug), and finally, the user-specified log message itself (in // this case, the log message was @"foo=%@", foo). // // Multiple instances of GTMLogger can be created, each configured their own // way. Though GTMLogger is not a singleton (in the GoF sense), it does provide // access to a shared (i.e., globally accessible) GTMLogger instance. This makes // it convenient for all code in a process to use the same GTMLogger instance. // The shared GTMLogger instance can also be configured in an arbitrary, and // these configuration changes will affect all code that logs through the shared // instance. // // Log Levels // ---------- // GTMLogger has 3 different log levels: Debug, Info, and Error. GTMLogger // doesn't take any special action based on the log level; it simply forwards // this information on to formatters, filters, and writers, each of which may // optionally take action based on the level. Since log level filtering is // performed at runtime, log messages are typically not filtered out at compile // time. The exception to this rule is that calls to the GTMLoggerDebug() macro // *ARE* filtered out of non-DEBUG builds. This is to be backwards compatible // with behavior that many developers are currently used to. Note that this // means that GTMLoggerDebug(@"hi") will be compiled out of Release builds, but // [[GTMLogger sharedLogger] logDebug:@"hi"] will NOT be compiled out. // // Standard loggers are created with the GTMLogLevelFilter log filter, which // filters out certain log messages based on log level, and some other settings. // // In addition to the -logDebug:, -logInfo:, and -logError: methods defined on // GTMLogger itself, there are also C macros that make usage of the shared // GTMLogger instance very convenient. These macros are: // // GTMLoggerDebug(...) // GTMLoggerInfo(...) // GTMLoggerError(...) // // Again, a notable feature of these macros is that GTMLogDebug() calls *will be // compiled out of non-DEBUG builds*. // // Standard Loggers // ---------------- // GTMLogger has the concept of "standard loggers". A standard logger is simply // a logger that is pre-configured with some standard/common writer, formatter, // and filter combination. Standard loggers are created using the creation // methods beginning with "standard". The alternative to a standard logger is a // regular logger, which will send messages to stdout, with no special // formatting, and no filtering. // // How do I use GTMLogger? // ---------------------- // The typical way you will want to use GTMLogger is to simply use the // GTMLogger*() macros for logging from code. That way we can easily make // changes to the GTMLogger class and simply update the macros accordingly. Only // your application startup code (perhaps, somewhere in main()) should use the // GTMLogger class directly in order to configure the shared logger, which all // of the code using the macros will be using. Again, this is just the typical // situation. // // To be complete, there are cases where you may want to use GTMLogger directly, // or even create separate GTMLogger instances for some reason. That's fine, // too. // // Examples // -------- // The following show some common GTMLogger use cases. // // 1. You want to log something as simply as possible. Also, this call will only // appear in debug builds. In non-DEBUG builds it will be completely removed. // // GTMLoggerDebug(@"foo = %@", foo); // // 2. The previous example is similar to the following. The major difference is // that the previous call (example 1) will be compiled out of Release builds // but this statement will not be compiled out. // // [[GTMLogger sharedLogger] logDebug:@"foo = %@", foo]; // // 3. Send all logging output from the shared logger to a file. We do this by // creating an NSFileHandle for writing associated with a file, and setting // that file handle as the logger's writer. // // NSFileHandle *f = [NSFileHandle fileHandleForWritingAtPath:@"/tmp/f.log" // create:YES]; // [[GTMLogger sharedLogger] setWriter:f]; // GTMLoggerError(@"hi"); // This will be sent to /tmp/f.log // // 4. Create a new GTMLogger that will log to a file. This example differs from // the previous one because here we create a new GTMLogger that is different // from the shared logger. // // GTMLogger *logger = [GTMLogger standardLoggerWithPath:@"/tmp/temp.log"]; // [logger logInfo:@"hi temp log file"]; // // 5. Create a logger that writes to stdout and does NOT do any formatting to // the log message. This might be useful, for example, when writing a help // screen for a command-line tool to standard output. // // GTMLogger *logger = [GTMLogger logger]; // [logger logInfo:@"%@ version 0.1 usage", progName]; // // 6. Send log output to stdout AND to a log file. The trick here is that // NSArrays function as composite log writers, which means when an array is // set as the log writer, it forwards all logging messages to all of its // contained GTMLogWriters. // // // Create array of GTMLogWriters // NSArray *writers = [NSArray arrayWithObjects: // [NSFileHandle fileHandleForWritingAtPath:@"/tmp/f.log" create:YES], // [NSFileHandle fileHandleWithStandardOutput], nil]; // // GTMLogger *logger = [GTMLogger standardLogger]; // [logger setWriter:writers]; // [logger logInfo:@"hi"]; // Output goes to stdout and /tmp/f.log // // For futher details on log writers, formatters, and filters, see the // documentation below. // // NOTE: GTMLogger is application level logging. By default it does nothing // with _GTMDevLog/_GTMDevAssert (see GTMDefines.h). An application can choose // to bridge _GTMDevLog/_GTMDevAssert to GTMLogger by providing macro // definitions in its prefix header (see GTMDefines.h for how one would do // that). // @interface GTMLogger : NSObject { @private id writer_; id formatter_; id filter_; } // // Accessors for the shared logger instance // // Returns a shared/global standard GTMLogger instance. Callers should typically // use this method to get a GTMLogger instance, unless they explicitly want // their own instance to configure for their own needs. This is the only method // that returns a shared instance; all the rest return new GTMLogger instances. + (id)sharedLogger; // Sets the shared logger instance to |logger|. Future calls to +sharedLogger // will return |logger| instead. + (void)setSharedLogger:(GTMLogger *)logger; // // Creation methods // // Returns a new autoreleased GTMLogger instance that will log to stdout, using // the GTMLogStandardFormatter, and the GTMLogLevelFilter filter. + (id)standardLogger; // Same as +standardLogger, but logs to stderr. + (id)standardLoggerWithStderr; // Same as +standardLogger but levels >= kGTMLoggerLevelError are routed to // stderr, everything else goes to stdout. + (id)standardLoggerWithStdoutAndStderr; // Returns a new standard GTMLogger instance with a log writer that will // write to the file at |path|, and will use the GTMLogStandardFormatter and // GTMLogLevelFilter classes. If |path| does not exist, it will be created. + (id)standardLoggerWithPath:(NSString *)path; // Returns an autoreleased GTMLogger instance that will use the specified // |writer|, |formatter|, and |filter|. + (id)loggerWithWriter:(id)writer formatter:(id)formatter filter:(id)filter; // Returns an autoreleased GTMLogger instance that logs to stdout, with the // basic formatter, and no filter. The returned logger differs from the logger // returned by +standardLogger because this one does not do any filtering and // does not do any special log formatting; this is the difference between a // "regular" logger and a "standard" logger. + (id)logger; // Designated initializer. This method returns a GTMLogger initialized with the // specified |writer|, |formatter|, and |filter|. See the setter methods below // for what values will be used if nil is passed for a parameter. - (id)initWithWriter:(id)writer formatter:(id)formatter filter:(id)filter; // // Logging methods // // Logs a message at the debug level (kGTMLoggerLevelDebug). - (void)logDebug:(NSString *)fmt, ... NS_FORMAT_FUNCTION(1, 2); // Logs a message at the info level (kGTMLoggerLevelInfo). - (void)logInfo:(NSString *)fmt, ... NS_FORMAT_FUNCTION(1, 2); // Logs a message at the error level (kGTMLoggerLevelError). - (void)logError:(NSString *)fmt, ... NS_FORMAT_FUNCTION(1, 2); // Logs a message at the assert level (kGTMLoggerLevelAssert). - (void)logAssert:(NSString *)fmt, ... NS_FORMAT_FUNCTION(1, 2); // // Accessors // // Accessor methods for the log writer. If the log writer is set to nil, // [NSFileHandle fileHandleWithStandardOutput] is used. - (id)writer; - (void)setWriter:(id)writer; // Accessor methods for the log formatter. If the log formatter is set to nil, // GTMLogBasicFormatter is used. This formatter will format log messages in a // plain printf style. - (id)formatter; - (void)setFormatter:(id)formatter; // Accessor methods for the log filter. If the log filter is set to nil, // GTMLogNoFilter is used, which allows all log messages through. - (id)filter; - (void)setFilter:(id)filter; @end // GTMLogger // Helper functions that are used by the convenience GTMLogger*() macros that // enable the logging of function names. @interface GTMLogger (GTMLoggerMacroHelpers) - (void)logFuncDebug:(const char *)func msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(2, 3); - (void)logFuncInfo:(const char *)func msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(2, 3); - (void)logFuncError:(const char *)func msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(2, 3); - (void)logFuncAssert:(const char *)func msg:(NSString *)fmt, ... NS_FORMAT_FUNCTION(2, 3); @end // GTMLoggerMacroHelpers // The convenience macros are only defined if they haven't already been defined. #ifndef GTMLoggerInfo // Convenience macros that log to the shared GTMLogger instance. These macros // are how users should typically log to GTMLogger. Notice that GTMLoggerDebug() // calls will be compiled out of non-Debug builds. #define GTMLoggerDebug(...) \ [[GTMLogger sharedLogger] logFuncDebug:__func__ msg:__VA_ARGS__] #define GTMLoggerInfo(...) \ [[GTMLogger sharedLogger] logFuncInfo:__func__ msg:__VA_ARGS__] #define GTMLoggerError(...) \ [[GTMLogger sharedLogger] logFuncError:__func__ msg:__VA_ARGS__] #define GTMLoggerAssert(...) \ [[GTMLogger sharedLogger] logFuncAssert:__func__ msg:__VA_ARGS__] // If we're not in a debug build, remove the GTMLoggerDebug statements. This // makes calls to GTMLoggerDebug "compile out" of Release builds #ifndef DEBUG #undef GTMLoggerDebug #define GTMLoggerDebug(...) do {} while(0) #endif #endif // !defined(GTMLoggerInfo) // Log levels. typedef enum { kGTMLoggerLevelUnknown, kGTMLoggerLevelDebug, kGTMLoggerLevelInfo, kGTMLoggerLevelError, kGTMLoggerLevelAssert, } GTMLoggerLevel; // // Log Writers // // Protocol to be implemented by a GTMLogWriter instance. @protocol GTMLogWriter // Writes the given log message to where the log writer is configured to write. - (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level; @end // GTMLogWriter // Simple category on NSFileHandle that makes NSFileHandles valid log writers. // This is convenient because something like, say, +fileHandleWithStandardError // now becomes a valid log writer. Log messages are written to the file handle // with a newline appended. @interface NSFileHandle (GTMFileHandleLogWriter) // Opens the file at |path| in append mode, and creates the file with |mode| // if it didn't previously exist. + (id)fileHandleForLoggingAtPath:(NSString *)path mode:(mode_t)mode; @end // NSFileHandle // This category makes NSArray a GTMLogWriter that can be composed of other // GTMLogWriters. This is the classic Composite GoF design pattern. When the // GTMLogWriter -logMessage:level: message is sent to the array, the array // forwards the message to all of its elements that implement the GTMLogWriter // protocol. // // This is useful in situations where you would like to send log output to // multiple log writers at the same time. Simply create an NSArray of the log // writers you wish to use, then set the array as the "writer" for your // GTMLogger instance. @interface NSArray (GTMArrayCompositeLogWriter) @end // GTMArrayCompositeLogWriter // This category adapts the GTMLogger interface so that it can be used as a log // writer; it's an "adapter" in the GoF Adapter pattern sense. // // This is useful when you want to configure a logger to log to a specific // writer with a specific formatter and/or filter. But you want to also compose // that with a different log writer that may have its own formatter and/or // filter. @interface GTMLogger (GTMLoggerLogWriter) @end // GTMLoggerLogWriter // // Log Formatters // // Protocol to be implemented by a GTMLogFormatter instance. @protocol GTMLogFormatter // Returns a formatted string using the format specified in |fmt| and the va // args specified in |args|. - (NSString *)stringForFunc:(NSString *)func withFormat:(NSString *)fmt valist:(va_list)args level:(GTMLoggerLevel)level NS_FORMAT_FUNCTION(2, 0); @end // GTMLogFormatter // A basic log formatter that formats a string the same way that NSLog (or // printf) would. It does not do anything fancy, nor does it add any data of its // own. @interface GTMLogBasicFormatter : NSObject // Helper method for prettying C99 __func__ and GCC __PRETTY_FUNCTION__ - (NSString *)prettyNameForFunc:(NSString *)func; @end // GTMLogBasicFormatter // A log formatter that formats the log string like the basic formatter, but // also prepends a timestamp and some basic process info to the message, as // shown in the following sample output. // 2007-12-30 10:29:24.177 myapp[4588/0xa07d0f60] [lvl=1] log mesage here @interface GTMLogStandardFormatter : GTMLogBasicFormatter { @private NSDateFormatter *dateFormatter_; // yyyy-MM-dd HH:mm:ss.SSS NSString *pname_; pid_t pid_; } @end // GTMLogStandardFormatter // // Log Filters // // Protocol to be implemented by a GTMLogFilter instance. @protocol GTMLogFilter // Returns YES if |msg| at |level| should be logged; NO otherwise. - (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level; @end // GTMLogFilter // A log filter that filters messages at the kGTMLoggerLevelDebug level out of // non-debug builds. Messages at the kGTMLoggerLevelInfo level are also filtered // out of non-debug builds unless GTMVerboseLogging is set in the environment or // the processes's defaults. Messages at the kGTMLoggerLevelError level are // never filtered. @interface GTMLogLevelFilter : NSObject { @private BOOL verboseLoggingEnabled_; NSUserDefaults *userDefaults_; } @end // GTMLogLevelFilter // A simple log filter that does NOT filter anything out; // -filterAllowsMessage:level will always return YES. This can be a convenient // way to enable debug-level logging in release builds (if you so desire). @interface GTMLogNoFilter : NSObject @end // GTMLogNoFilter // Base class for custom level filters. Not for direct use, use the minimum // or maximum level subclasses below. @interface GTMLogAllowedLevelFilter : NSObject { @private NSIndexSet *allowedLevels_; } @end // A log filter that allows you to set a minimum log level. Messages below this // level will be filtered. @interface GTMLogMininumLevelFilter : GTMLogAllowedLevelFilter // Designated initializer, logs at levels < |level| will be filtered. - (id)initWithMinimumLevel:(GTMLoggerLevel)level; @end // A log filter that allows you to set a maximum log level. Messages whose level // exceeds this level will be filtered. This is really only useful if you have // a composite GTMLogger that is sending the other messages elsewhere. @interface GTMLogMaximumLevelFilter : GTMLogAllowedLevelFilter // Designated initializer, logs at levels > |level| will be filtered. - (id)initWithMaximumLevel:(GTMLoggerLevel)level; @end // For subclasses only @interface GTMLogger (PrivateMethods) - (void)logInternalFunc:(const char *)func format:(NSString *)fmt valist:(va_list)args level:(GTMLoggerLevel)level NS_FORMAT_FUNCTION(2, 0); @end ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/Foundation/GTMLogger.m ================================================ // // GTMLogger.m // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMLogger.h" #import #import #import #import #if !defined(__clang__) && (__GNUC__*10+__GNUC_MINOR__ >= 42) // Some versions of GCC (4.2 and below AFAIK) aren't great about supporting // -Wmissing-format-attribute // when the function is anything more complex than foo(NSString *fmt, ...). // You see the error inside the function when you turn ... into va_args and // attempt to call another function (like vsprintf for example). // So we just shut off the warning for this file. We reenable it at the end. #pragma GCC diagnostic ignored "-Wmissing-format-attribute" #endif // !__clang__ // Reference to the shared GTMLogger instance. This is not a singleton, it's // just an easy reference to one shared instance. static GTMLogger *gSharedLogger = nil; @implementation GTMLogger // Returns a pointer to the shared logger instance. If none exists, a standard // logger is created and returned. + (id)sharedLogger { @synchronized(self) { if (gSharedLogger == nil) { gSharedLogger = [[self standardLogger] retain]; } } return [[gSharedLogger retain] autorelease]; } + (void)setSharedLogger:(GTMLogger *)logger { @synchronized(self) { [gSharedLogger autorelease]; gSharedLogger = [logger retain]; } } + (id)standardLogger { // Don't trust NSFileHandle not to throw @try { id writer = [NSFileHandle fileHandleWithStandardOutput]; id fr = [[[GTMLogStandardFormatter alloc] init] autorelease]; id filter = [[[GTMLogLevelFilter alloc] init] autorelease]; return [[[self alloc] initWithWriter:writer formatter:fr filter:filter] autorelease]; } @catch (id e) { // Ignored } return nil; } + (id)standardLoggerWithStderr { // Don't trust NSFileHandle not to throw @try { id me = [self standardLogger]; [me setWriter:[NSFileHandle fileHandleWithStandardError]]; return me; } @catch (id e) { // Ignored } return nil; } + (id)standardLoggerWithStdoutAndStderr { // We're going to take advantage of the GTMLogger to GTMLogWriter adaptor // and create a composite logger that an outer "standard" logger can use // as a writer. Our inner loggers should apply no formatting since the main // logger does that and we want the caller to be able to change formatters // or add writers without knowing the inner structure of our composite. // Don't trust NSFileHandle not to throw @try { GTMLogBasicFormatter *formatter = [[[GTMLogBasicFormatter alloc] init] autorelease]; GTMLogger *stdoutLogger = [self loggerWithWriter:[NSFileHandle fileHandleWithStandardOutput] formatter:formatter filter:[[[GTMLogMaximumLevelFilter alloc] initWithMaximumLevel:kGTMLoggerLevelInfo] autorelease]]; GTMLogger *stderrLogger = [self loggerWithWriter:[NSFileHandle fileHandleWithStandardError] formatter:formatter filter:[[[GTMLogMininumLevelFilter alloc] initWithMinimumLevel:kGTMLoggerLevelError] autorelease]]; GTMLogger *compositeWriter = [self loggerWithWriter:[NSArray arrayWithObjects: stdoutLogger, stderrLogger, nil] formatter:formatter filter:[[[GTMLogNoFilter alloc] init] autorelease]]; GTMLogger *outerLogger = [self standardLogger]; [outerLogger setWriter:compositeWriter]; return outerLogger; } @catch (id e) { // Ignored } return nil; } + (id)standardLoggerWithPath:(NSString *)path { @try { NSFileHandle *fh = [NSFileHandle fileHandleForLoggingAtPath:path mode:0644]; if (fh == nil) return nil; id me = [self standardLogger]; [me setWriter:fh]; return me; } @catch (id e) { // Ignored } return nil; } + (id)loggerWithWriter:(id)writer formatter:(id)formatter filter:(id)filter { return [[[self alloc] initWithWriter:writer formatter:formatter filter:filter] autorelease]; } + (id)logger { return [[[self alloc] init] autorelease]; } - (id)init { return [self initWithWriter:nil formatter:nil filter:nil]; } - (id)initWithWriter:(id)writer formatter:(id)formatter filter:(id)filter { if ((self = [super init])) { [self setWriter:writer]; [self setFormatter:formatter]; [self setFilter:filter]; } return self; } - (void)dealloc { // Unlikely, but |writer_| may be an NSFileHandle, which can throw @try { [formatter_ release]; [filter_ release]; [writer_ release]; } @catch (id e) { // Ignored } [super dealloc]; } - (id)writer { return [[writer_ retain] autorelease]; } - (void)setWriter:(id)writer { @synchronized(self) { [writer_ autorelease]; writer_ = nil; if (writer == nil) { // Try to use stdout, but don't trust NSFileHandle @try { writer_ = [[NSFileHandle fileHandleWithStandardOutput] retain]; } @catch (id e) { // Leave |writer_| nil } } else { writer_ = [writer retain]; } } } - (id)formatter { return [[formatter_ retain] autorelease]; } - (void)setFormatter:(id)formatter { @synchronized(self) { [formatter_ autorelease]; formatter_ = nil; if (formatter == nil) { @try { formatter_ = [[GTMLogBasicFormatter alloc] init]; } @catch (id e) { // Leave |formatter_| nil } } else { formatter_ = [formatter retain]; } } } - (id)filter { return [[filter_ retain] autorelease]; } - (void)setFilter:(id)filter { @synchronized(self) { [filter_ autorelease]; filter_ = nil; if (filter == nil) { @try { filter_ = [[GTMLogNoFilter alloc] init]; } @catch (id e) { // Leave |filter_| nil } } else { filter_ = [filter retain]; } } } - (void)logDebug:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelDebug]; va_end(args); } - (void)logInfo:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelInfo]; va_end(args); } - (void)logError:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelError]; va_end(args); } - (void)logAssert:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:NULL format:fmt valist:args level:kGTMLoggerLevelAssert]; va_end(args); } @end // GTMLogger @implementation GTMLogger (GTMLoggerMacroHelpers) - (void)logFuncDebug:(const char *)func msg:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelDebug]; va_end(args); } - (void)logFuncInfo:(const char *)func msg:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelInfo]; va_end(args); } - (void)logFuncError:(const char *)func msg:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelError]; va_end(args); } - (void)logFuncAssert:(const char *)func msg:(NSString *)fmt, ... { va_list args; va_start(args, fmt); [self logInternalFunc:func format:fmt valist:args level:kGTMLoggerLevelAssert]; va_end(args); } @end // GTMLoggerMacroHelpers @implementation GTMLogger (PrivateMethods) - (void)logInternalFunc:(const char *)func format:(NSString *)fmt valist:(va_list)args level:(GTMLoggerLevel)level { // Primary point where logging happens, logging should never throw, catch // everything. @try { NSString *fname = func ? [NSString stringWithUTF8String:func] : nil; NSString *msg = [formatter_ stringForFunc:fname withFormat:fmt valist:args level:level]; if (msg && [filter_ filterAllowsMessage:msg level:level]) [writer_ logMessage:msg level:level]; } @catch (id e) { // Ignored } } @end // PrivateMethods @implementation NSFileHandle (GTMFileHandleLogWriter) + (id)fileHandleForLoggingAtPath:(NSString *)path mode:(mode_t)mode { int fd = -1; if (path) { int flags = O_WRONLY | O_APPEND | O_CREAT; fd = open([path fileSystemRepresentation], flags, mode); } if (fd == -1) return nil; return [[[self alloc] initWithFileDescriptor:fd closeOnDealloc:YES] autorelease]; } - (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level { @synchronized(self) { // Closed pipes should not generate exceptions in our caller. Catch here // as well [GTMLogger logInternalFunc:...] so that an exception in this // writer does not prevent other writers from having a chance. @try { NSString *line = [NSString stringWithFormat:@"%@\n", msg]; [self writeData:[line dataUsingEncoding:NSUTF8StringEncoding]]; } @catch (id e) { // Ignored } } } @end // GTMFileHandleLogWriter @implementation NSArray (GTMArrayCompositeLogWriter) - (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level { @synchronized(self) { id child = nil; for (child in self) { if ([child conformsToProtocol:@protocol(GTMLogWriter)]) [child logMessage:msg level:level]; } } } @end // GTMArrayCompositeLogWriter @implementation GTMLogger (GTMLoggerLogWriter) - (void)logMessage:(NSString *)msg level:(GTMLoggerLevel)level { switch (level) { case kGTMLoggerLevelDebug: [self logDebug:@"%@", msg]; break; case kGTMLoggerLevelInfo: [self logInfo:@"%@", msg]; break; case kGTMLoggerLevelError: [self logError:@"%@", msg]; break; case kGTMLoggerLevelAssert: [self logAssert:@"%@", msg]; break; default: // Ignore the message. break; } } @end // GTMLoggerLogWriter @implementation GTMLogBasicFormatter - (NSString *)prettyNameForFunc:(NSString *)func { NSString *name = [func stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *function = @"(unknown)"; if ([name length]) { if (// Objective C __func__ and __PRETTY_FUNCTION__ [name hasPrefix:@"-["] || [name hasPrefix:@"+["] || // C++ __PRETTY_FUNCTION__ and other preadorned formats [name hasSuffix:@")"]) { function = name; } else { // Assume C99 __func__ function = [NSString stringWithFormat:@"%@()", name]; } } return function; } - (NSString *)stringForFunc:(NSString *)func withFormat:(NSString *)fmt valist:(va_list)args level:(GTMLoggerLevel)level { // Performance note: We may want to do a quick check here to see if |fmt| // contains a '%', and if not, simply return 'fmt'. if (!(fmt && args)) return nil; return [[[NSString alloc] initWithFormat:fmt arguments:args] autorelease]; } @end // GTMLogBasicFormatter @implementation GTMLogStandardFormatter - (id)init { if ((self = [super init])) { dateFormatter_ = [[NSDateFormatter alloc] init]; [dateFormatter_ setFormatterBehavior:NSDateFormatterBehavior10_4]; [dateFormatter_ setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"]; pname_ = [[[NSProcessInfo processInfo] processName] copy]; pid_ = [[NSProcessInfo processInfo] processIdentifier]; if (!(dateFormatter_ && pname_)) { [self release]; return nil; } } return self; } - (void)dealloc { [dateFormatter_ release]; [pname_ release]; [super dealloc]; } - (NSString *)stringForFunc:(NSString *)func withFormat:(NSString *)fmt valist:(va_list)args level:(GTMLoggerLevel)level { NSString *tstamp = nil; @synchronized (dateFormatter_) { tstamp = [dateFormatter_ stringFromDate:[NSDate date]]; } return [NSString stringWithFormat:@"%@ %@[%d/%p] [lvl=%d] %@ %@", tstamp, pname_, pid_, pthread_self(), level, [self prettyNameForFunc:func], // |super| has guard for nil |fmt| and |args| [super stringForFunc:func withFormat:fmt valist:args level:level]]; } @end // GTMLogStandardFormatter static NSString *const kVerboseLoggingKey = @"GTMVerboseLogging"; // Check the environment and the user preferences for the GTMVerboseLogging key // to see if verbose logging has been enabled. The environment variable will // override the defaults setting, so check the environment first. // COV_NF_START static BOOL IsVerboseLoggingEnabled(NSUserDefaults *userDefaults) { NSString *value = [[[NSProcessInfo processInfo] environment] objectForKey:kVerboseLoggingKey]; if (value) { // Emulate [NSString boolValue] for pre-10.5 value = [value stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; if ([[value uppercaseString] hasPrefix:@"Y"] || [[value uppercaseString] hasPrefix:@"T"] || [value intValue]) { return YES; } else { return NO; } } return [userDefaults boolForKey:kVerboseLoggingKey]; } // COV_NF_END @implementation GTMLogLevelFilter - (id)init { self = [super init]; if (self) { // Keep a reference to standardUserDefaults, avoiding a crash if client code calls // "NSUserDefaults resetStandardUserDefaults" which releases it from memory. We are still // notified of changes through our instance. Note: resetStandardUserDefaults does not actually // clear settings: // https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/clm/NSUserDefaults/resetStandardUserDefaults // and so should only be called in test code if necessary. userDefaults_ = [[NSUserDefaults standardUserDefaults] retain]; [userDefaults_ addObserver:self forKeyPath:kVerboseLoggingKey options:NSKeyValueObservingOptionNew context:nil]; verboseLoggingEnabled_ = IsVerboseLoggingEnabled(userDefaults_); } return self; } - (void)dealloc { [userDefaults_ removeObserver:self forKeyPath:kVerboseLoggingKey]; [userDefaults_ release]; [super dealloc]; } // In DEBUG builds, log everything. If we're not in a debug build we'll assume // that we're in a Release build. - (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level { #if defined(DEBUG) && DEBUG return YES; #endif BOOL allow = YES; switch (level) { case kGTMLoggerLevelDebug: allow = NO; break; case kGTMLoggerLevelInfo: allow = verboseLoggingEnabled_; break; case kGTMLoggerLevelError: allow = YES; break; case kGTMLoggerLevelAssert: allow = YES; break; default: allow = YES; break; } return allow; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqual:kVerboseLoggingKey]) { verboseLoggingEnabled_ = IsVerboseLoggingEnabled(userDefaults_); } } @end // GTMLogLevelFilter @implementation GTMLogNoFilter - (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level { return YES; // Allow everything through } @end // GTMLogNoFilter @implementation GTMLogAllowedLevelFilter // Private designated initializer - (id)initWithAllowedLevels:(NSIndexSet *)levels { self = [super init]; if (self != nil) { allowedLevels_ = [levels retain]; // Cap min/max level if (!allowedLevels_ || // NSIndexSet is unsigned so only check the high bound, but need to // check both first and last index because NSIndexSet appears to allow // wraparound. ([allowedLevels_ firstIndex] > kGTMLoggerLevelAssert) || ([allowedLevels_ lastIndex] > kGTMLoggerLevelAssert)) { [self release]; return nil; } } return self; } - (id)init { // Allow all levels in default init return [self initWithAllowedLevels:[NSIndexSet indexSetWithIndexesInRange: NSMakeRange(kGTMLoggerLevelUnknown, (kGTMLoggerLevelAssert - kGTMLoggerLevelUnknown + 1))]]; } - (void)dealloc { [allowedLevels_ release]; [super dealloc]; } - (BOOL)filterAllowsMessage:(NSString *)msg level:(GTMLoggerLevel)level { return [allowedLevels_ containsIndex:level]; } @end // GTMLogAllowedLevelFilter @implementation GTMLogMininumLevelFilter - (id)initWithMinimumLevel:(GTMLoggerLevel)level { return [super initWithAllowedLevels:[NSIndexSet indexSetWithIndexesInRange: NSMakeRange(level, (kGTMLoggerLevelAssert - level + 1))]]; } @end // GTMLogMininumLevelFilter @implementation GTMLogMaximumLevelFilter - (id)initWithMaximumLevel:(GTMLoggerLevel)level { return [super initWithAllowedLevels:[NSIndexSet indexSetWithIndexesInRange: NSMakeRange(kGTMLoggerLevelUnknown, level + 1)]]; } @end // GTMLogMaximumLevelFilter #if !defined(__clang__) && (__GNUC__*10+__GNUC_MINOR__ >= 42) // See comment at top of file. #pragma GCC diagnostic error "-Wmissing-format-attribute" #endif // !__clang__ ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/Foundation/GTMNSData+zlib.h ================================================ // // GTMNSData+zlib.h // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import #import "GTMDefines.h" /// Helpers for dealing w/ zlib inflate/deflate calls. @interface NSData (GTMZLibAdditions) // NOTE: For 64bit, none of these apis handle input sizes >32bits, they will // return nil when given such data. To handle data of that size you really // should be streaming it rather then doing it all in memory. #pragma mark Gzip Compression /// Return an autoreleased NSData w/ the result of gzipping the bytes. // // Uses the default compression level. + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length; + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the payload of |data|. // // Uses the default compression level. + (NSData *)gtm_dataByGzippingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of gzipping the payload of |data| using |level| compression level. + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; #pragma mark Zlib "Stream" Compression // NOTE: deflate is *NOT* gzip. deflate is a "zlib" stream. pick which one // you really want to create. (the inflate api will handle either) /// Return an autoreleased NSData w/ the result of deflating the bytes. // // Uses the default compression level. + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the payload of |data|. // // Uses the default compression level. + (NSData *)gtm_dataByDeflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of deflating the payload of |data| using |level| compression level. + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; #pragma mark Uncompress of Gzip or Zlib /// Return an autoreleased NSData w/ the result of decompressing the bytes. // // The bytes to decompress can be zlib or gzip payloads. + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of decompressing the payload of |data|. // // The data to decompress can be zlib or gzip payloads. + (NSData *)gtm_dataByInflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByInflatingData:(NSData *)data error:(NSError **)error; #pragma mark "Raw" Compression Support // NOTE: raw deflate is *NOT* gzip or deflate. it does not include a header // of any form and should only be used within streams here an external crc/etc. // is done to validate the data. The RawInflate apis can be used on data // processed like this. /// Return an autoreleased NSData w/ the result of *raw* deflating the bytes. // // Uses the default compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the payload of |data|. // // Uses the default compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the bytes using |level| compression level. // // |level| can be 1-9, any other values will be clipped to that range. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* deflating the payload of |data| using |level| compression level. // *No* header is added to the resulting data. + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* decompressing the bytes. // // The data to decompress, it should *not* have any header (zlib nor gzip). + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error; /// Return an autoreleased NSData w/ the result of *raw* decompressing the payload of |data|. // // The data to decompress, it should *not* have any header (zlib nor gzip). + (NSData *)gtm_dataByRawInflatingData:(NSData *)data __attribute__((deprecated("Use error variant"))); + (NSData *)gtm_dataByRawInflatingData:(NSData *)data error:(NSError **)error; @end FOUNDATION_EXPORT NSString *const GTMNSDataZlibErrorDomain; FOUNDATION_EXPORT NSString *const GTMNSDataZlibErrorKey; // NSNumber FOUNDATION_EXPORT NSString *const GTMNSDataZlibRemainingBytesKey; // NSNumber typedef NS_ENUM(NSInteger, GTMNSDataZlibError) { GTMNSDataZlibErrorGreaterThan32BitsToCompress = 1024, // An internal zlib error. // GTMNSDataZlibErrorKey will contain the error value. // NSLocalizedDescriptionKey may contain an error string from zlib. // Look in zlib.h for list of errors. GTMNSDataZlibErrorInternal, // There was left over data in the buffer that was not used. // GTMNSDataZlibRemainingBytesKey will contain number of remaining bytes. GTMNSDataZlibErrorDataRemaining }; ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/Foundation/GTMNSData+zlib.m ================================================ // // GTMNSData+zlib.m // // Copyright 2007-2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMNSData+zlib.h" #import #import "GTMDefines.h" #define kChunkSize 1024 NSString *const GTMNSDataZlibErrorDomain = @"com.google.GTMNSDataZlibErrorDomain"; NSString *const GTMNSDataZlibErrorKey = @"GTMNSDataZlibErrorKey"; NSString *const GTMNSDataZlibRemainingBytesKey = @"GTMNSDataZlibRemainingBytesKey"; typedef enum { CompressionModeZlib, CompressionModeGzip, CompressionModeRaw, } CompressionMode; @interface NSData (GTMZlibAdditionsPrivate) + (NSData *)gtm_dataByCompressingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level mode:(CompressionMode)mode error:(NSError **)error; + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length isRawData:(BOOL)isRawData error:(NSError **)error; @end @implementation NSData (GTMZlibAdditionsPrivate) + (NSData *)gtm_dataByCompressingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level mode:(CompressionMode)mode error:(NSError **)error { if (!bytes || !length) { return nil; } #if defined(__LP64__) && __LP64__ // Don't support > 32bit length for 64 bit, see note in header. if (length > UINT_MAX) { if (error) { *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorGreaterThan32BitsToCompress userInfo:nil]; } return nil; } #endif if (level == Z_DEFAULT_COMPRESSION) { // the default value is actually outside the range, so we have to let it // through specifically. } else if (level < Z_BEST_SPEED) { level = Z_BEST_SPEED; } else if (level > Z_BEST_COMPRESSION) { level = Z_BEST_COMPRESSION; } z_stream strm; bzero(&strm, sizeof(z_stream)); int memLevel = 8; // the default int windowBits = 15; // the default switch (mode) { case CompressionModeZlib: // nothing to do break; case CompressionModeGzip: windowBits += 16; // enable gzip header instead of zlib header break; case CompressionModeRaw: windowBits *= -1; // Negative to mean no header. break; } int retCode; if ((retCode = deflateInit2(&strm, level, Z_DEFLATED, windowBits, memLevel, Z_DEFAULT_STRATEGY)) != Z_OK) { // COV_NF_START - no real way to force this in a unittest (we guard all args) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } return nil; // COV_NF_END } // hint the size at 1/4 the input size NSMutableData *result = [NSMutableData dataWithCapacity:(length/4)]; unsigned char output[kChunkSize]; // setup the input strm.avail_in = (unsigned int)length; strm.next_in = (unsigned char*)bytes; // loop to collect the data do { // update what we're passing in strm.avail_out = kChunkSize; strm.next_out = output; retCode = deflate(&strm, Z_FINISH); if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { // COV_NF_START - no real way to force this in a unittest // (in inflate, we can feed bogus/truncated data to test, but an error // here would be some internal issue w/in zlib, and there isn't any real // way to test it) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } deflateEnd(&strm); return nil; // COV_NF_END } // collect what we got unsigned gotBack = kChunkSize - strm.avail_out; if (gotBack > 0) { [result appendBytes:output length:gotBack]; } } while (retCode == Z_OK); // if the loop exits, we used all input and the stream ended _GTMDevAssert(strm.avail_in == 0, @"thought we finished deflate w/o using all input, %u bytes left", strm.avail_in); _GTMDevAssert(retCode == Z_STREAM_END, @"thought we finished deflate w/o getting a result of stream end, code %d", retCode); // clean up deflateEnd(&strm); return result; } // gtm_dataByCompressingBytes:length:compressionLevel:useGzip: + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length isRawData:(BOOL)isRawData error:(NSError **)error { if (!bytes || !length) { return nil; } #if defined(__LP64__) && __LP64__ // Don't support > 32bit length for 64 bit, see note in header. if (length > UINT_MAX) { return nil; } #endif z_stream strm; bzero(&strm, sizeof(z_stream)); // setup the input strm.avail_in = (unsigned int)length; strm.next_in = (unsigned char*)bytes; int windowBits = 15; // 15 to enable any window size if (isRawData) { windowBits *= -1; // make it negative to signal no header. } else { windowBits += 32; // and +32 to enable zlib or gzip header detection. } int retCode; if ((retCode = inflateInit2(&strm, windowBits)) != Z_OK) { // COV_NF_START - no real way to force this in a unittest (we guard all args) if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } return nil; // COV_NF_END } // hint the size at 4x the input size NSMutableData *result = [NSMutableData dataWithCapacity:(length*4)]; unsigned char output[kChunkSize]; // loop to collect the data do { // update what we're passing in strm.avail_out = kChunkSize; strm.next_out = output; retCode = inflate(&strm, Z_NO_FLUSH); if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { if (error) { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:retCode] forKey:GTMNSDataZlibErrorKey]; if (strm.msg) { NSString *message = [NSString stringWithUTF8String:strm.msg]; if (message) { [userInfo setObject:message forKey:NSLocalizedDescriptionKey]; } } *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorInternal userInfo:userInfo]; } inflateEnd(&strm); return nil; } // collect what we got unsigned gotBack = kChunkSize - strm.avail_out; if (gotBack > 0) { [result appendBytes:output length:gotBack]; } } while (retCode == Z_OK); // make sure there wasn't more data tacked onto the end of a valid compressed // stream. if (strm.avail_in != 0) { if (error) { NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInt:strm.avail_in] forKey:GTMNSDataZlibRemainingBytesKey]; *error = [NSError errorWithDomain:GTMNSDataZlibErrorDomain code:GTMNSDataZlibErrorDataRemaining userInfo:userInfo]; } result = nil; } // the only way out of the loop was by hitting the end of the stream _GTMDevAssert(retCode == Z_STREAM_END, @"thought we finished inflate w/o getting a result of stream end, code %d", retCode); // clean up inflateEnd(&strm); return result; } // gtm_dataByInflatingBytes:length:windowBits: @end @implementation NSData (GTMZLibAdditions) + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByGzippingBytes:bytes length:length error:NULL]; } // gtm_dataByGzippingBytes:length: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingBytes:length:error: + (NSData *)gtm_dataByGzippingData:(NSData *)data { return [self gtm_dataByGzippingData:data error:NULL]; } // gtm_dataByGzippingData: + (NSData *)gtm_dataByGzippingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingData:error: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByGzippingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByGzippingBytes:length:level: + (NSData *)gtm_dataByGzippingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingBytes:length:level:error + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByGzippingData:data compressionLevel:level error:NULL]; } // gtm_dataByGzippingData:level: + (NSData *)gtm_dataByGzippingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeGzip error:error]; } // gtm_dataByGzippingData:level:error #pragma mark - + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByDeflatingBytes:bytes length:length error:NULL]; } // gtm_dataByDeflatingBytes:length: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingBytes:length:error + (NSData *)gtm_dataByDeflatingData:(NSData *)data { return [self gtm_dataByDeflatingData:data error:NULL]; } // gtm_dataByDeflatingData: + (NSData *)gtm_dataByDeflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingData: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByDeflatingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByDeflatingBytes:length:level: + (NSData *)gtm_dataByDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingBytes:length:level:error: + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByDeflatingData:data compressionLevel:level error:NULL]; } // gtm_dataByDeflatingData:level: + (NSData *)gtm_dataByDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeZlib error:error]; } // gtm_dataByDeflatingData:level:error: #pragma mark - + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByInflatingBytes:bytes length:length error:NULL]; } // gtm_dataByInflatingBytes:length: + (NSData *)gtm_dataByInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByInflatingBytes:bytes length:length isRawData:NO error:error]; } // gtm_dataByInflatingBytes:length:error: + (NSData *)gtm_dataByInflatingData:(NSData *)data { return [self gtm_dataByInflatingData:data error:NULL]; } // gtm_dataByInflatingData: + (NSData *)gtm_dataByInflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByInflatingBytes:[data bytes] length:[data length] isRawData:NO error:error]; } // gtm_dataByInflatingData: #pragma mark - + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:NULL]; } // gtm_dataByRawDeflatingBytes:length: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error { return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingBytes:length:error: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data { return [self gtm_dataByRawDeflatingData:data error:NULL]; } // gtm_dataByRawDeflatingData: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:Z_DEFAULT_COMPRESSION mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingData:error: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level { return [self gtm_dataByRawDeflatingBytes:bytes length:length compressionLevel:level error:NULL]; } // gtm_dataByRawDeflatingBytes:length:compressionLevel: + (NSData *)gtm_dataByRawDeflatingBytes:(const void *)bytes length:(NSUInteger)length compressionLevel:(int)level error:(NSError **)error{ return [self gtm_dataByCompressingBytes:bytes length:length compressionLevel:level mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingBytes:length:compressionLevel:error: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level { return [self gtm_dataByRawDeflatingData:data compressionLevel:level error:NULL]; } // gtm_dataByRawDeflatingData:compressionLevel: + (NSData *)gtm_dataByRawDeflatingData:(NSData *)data compressionLevel:(int)level error:(NSError **)error { return [self gtm_dataByCompressingBytes:[data bytes] length:[data length] compressionLevel:level mode:CompressionModeRaw error:error]; } // gtm_dataByRawDeflatingData:compressionLevel:error: + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length { return [self gtm_dataByInflatingBytes:bytes length:length error:NULL]; } // gtm_dataByRawInflatingBytes:length: + (NSData *)gtm_dataByRawInflatingBytes:(const void *)bytes length:(NSUInteger)length error:(NSError **)error{ return [self gtm_dataByInflatingBytes:bytes length:length isRawData:YES error:error]; } // gtm_dataByRawInflatingBytes:length:error: + (NSData *)gtm_dataByRawInflatingData:(NSData *)data { return [self gtm_dataByRawInflatingData:data error:NULL]; } // gtm_dataByRawInflatingData: + (NSData *)gtm_dataByRawInflatingData:(NSData *)data error:(NSError **)error { return [self gtm_dataByInflatingBytes:[data bytes] length:[data length] isRawData:YES error:error]; } // gtm_dataByRawInflatingData:error: @end ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/GTMDefines.h ================================================ // // GTMDefines.h // // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // // ============================================================================ #include #include #ifdef __OBJC__ #include #endif // __OBJC__ #if TARGET_OS_IPHONE #include #endif // TARGET_OS_IPHONE // ---------------------------------------------------------------------------- // CPP symbols that can be overridden in a prefix to control how the toolbox // is compiled. // ---------------------------------------------------------------------------- // By setting the GTM_CONTAINERS_VALIDATION_FAILED_LOG and // GTM_CONTAINERS_VALIDATION_FAILED_ASSERT macros you can control what happens // when a validation fails. If you implement your own validators, you may want // to control their internals using the same macros for consistency. #ifndef GTM_CONTAINERS_VALIDATION_FAILED_ASSERT #define GTM_CONTAINERS_VALIDATION_FAILED_ASSERT 0 #endif // Ensure __has_feature and __has_extension are safe to use. // See http://clang-analyzer.llvm.org/annotations.html #ifndef __has_feature // Optional. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif // Give ourselves a consistent way to do inlines. Apple's macros even use // a few different actual definitions, so we're based off of the foundation // one. #if !defined(GTM_INLINE) #if (defined (__GNUC__) && (__GNUC__ == 4)) || defined (__clang__) #define GTM_INLINE static __inline__ __attribute__((always_inline)) #else #define GTM_INLINE static __inline__ #endif #endif // Give ourselves a consistent way of doing externs that links up nicely // when mixing objc and objc++ #if !defined (GTM_EXTERN) #if defined __cplusplus #define GTM_EXTERN extern "C" #define GTM_EXTERN_C_BEGIN extern "C" { #define GTM_EXTERN_C_END } #else #define GTM_EXTERN extern #define GTM_EXTERN_C_BEGIN #define GTM_EXTERN_C_END #endif #endif // Give ourselves a consistent way of exporting things if we have visibility // set to hidden. #if !defined (GTM_EXPORT) #define GTM_EXPORT __attribute__((visibility("default"))) #endif // Give ourselves a consistent way of declaring something as unused. This // doesn't use __unused because that is only supported in gcc 4.2 and greater. #if !defined (GTM_UNUSED) #define GTM_UNUSED(x) ((void)(x)) #endif // _GTMDevLog & _GTMDevAssert // // _GTMDevLog & _GTMDevAssert are meant to be a very lightweight shell for // developer level errors. This implementation simply macros to NSLog/NSAssert. // It is not intended to be a general logging/reporting system. // // Please see http://code.google.com/p/google-toolbox-for-mac/wiki/DevLogNAssert // for a little more background on the usage of these macros. // // _GTMDevLog log some error/problem in debug builds // _GTMDevAssert assert if condition isn't met w/in a method/function // in all builds. // // To replace this system, just provide different macro definitions in your // prefix header. Remember, any implementation you provide *must* be thread // safe since this could be called by anything in what ever situtation it has // been placed in. // // We only define the simple macros if nothing else has defined this. #ifndef _GTMDevLog #ifdef DEBUG #define _GTMDevLog(...) NSLog(__VA_ARGS__) #else #define _GTMDevLog(...) do { } while (0) #endif #endif // _GTMDevLog #ifndef _GTMDevAssert // we directly invoke the NSAssert handler so we can pass on the varargs // (NSAssert doesn't have a macro we can use that takes varargs) #if !defined(NS_BLOCK_ASSERTIONS) #define _GTMDevAssert(condition, ...) \ do { \ if (!(condition)) { \ [[NSAssertionHandler currentHandler] \ handleFailureInFunction:(NSString *) \ [NSString stringWithUTF8String:__PRETTY_FUNCTION__] \ file:(NSString *)[NSString stringWithUTF8String:__FILE__] \ lineNumber:__LINE__ \ description:__VA_ARGS__]; \ } \ } while(0) #else // !defined(NS_BLOCK_ASSERTIONS) #define _GTMDevAssert(condition, ...) do { } while (0) #endif // !defined(NS_BLOCK_ASSERTIONS) #endif // _GTMDevAssert // _GTMCompileAssert // // Note: Software for current compilers should just use _Static_assert directly // instead of this macro. // // _GTMCompileAssert is an assert that is meant to fire at compile time if you // want to check things at compile instead of runtime. For example if you // want to check that a wchar is 4 bytes instead of 2 you would use // _GTMCompileAssert(sizeof(wchar_t) == 4, wchar_t_is_4_bytes_on_OS_X) // Note that the second "arg" is not in quotes, and must be a valid processor // symbol in it's own right (no spaces, punctuation etc). // Wrapping this in an #ifndef allows external groups to define their own // compile time assert scheme. #ifndef _GTMCompileAssert #if __has_feature(c_static_assert) || __has_extension(c_static_assert) #define _GTMCompileAssert(test, msg) _Static_assert((test), #msg) #else // Pre-Xcode 7 support. // // We got this technique from here: // http://unixjunkie.blogspot.com/2007/10/better-compile-time-asserts_29.html #define _GTMCompileAssertSymbolInner(line, msg) _GTMCOMPILEASSERT ## line ## __ ## msg #define _GTMCompileAssertSymbol(line, msg) _GTMCompileAssertSymbolInner(line, msg) #define _GTMCompileAssert(test, msg) \ typedef char _GTMCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] #endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) #endif // _GTMCompileAssert // ---------------------------------------------------------------------------- // CPP symbols defined based on the project settings so the GTM code has // simple things to test against w/o scattering the knowledge of project // setting through all the code. // ---------------------------------------------------------------------------- // Provide a single constant CPP symbol that all of GTM uses for ifdefing // iPhone code. #if TARGET_OS_IPHONE // iPhone SDK // For iPhone specific stuff #define GTM_IPHONE_SDK 1 #if TARGET_IPHONE_SIMULATOR #define GTM_IPHONE_DEVICE 0 #define GTM_IPHONE_SIMULATOR 1 #else #define GTM_IPHONE_DEVICE 1 #define GTM_IPHONE_SIMULATOR 0 #endif // TARGET_IPHONE_SIMULATOR // By default, GTM has provided it's own unittesting support, define this // to use the support provided by Xcode, especially for the Xcode4 support // for unittesting. #ifndef GTM_USING_XCTEST #define GTM_USING_XCTEST 0 #endif #define GTM_MACOS_SDK 0 #else // For MacOS specific stuff #define GTM_MACOS_SDK 1 #define GTM_IPHONE_SDK 0 #define GTM_IPHONE_SIMULATOR 0 #define GTM_IPHONE_DEVICE 0 #ifndef GTM_USING_XCTEST #define GTM_USING_XCTEST 0 #endif #endif // Some of our own availability macros #if GTM_MACOS_SDK #define GTM_AVAILABLE_ONLY_ON_IPHONE UNAVAILABLE_ATTRIBUTE #define GTM_AVAILABLE_ONLY_ON_MACOS #else #define GTM_AVAILABLE_ONLY_ON_IPHONE #define GTM_AVAILABLE_ONLY_ON_MACOS UNAVAILABLE_ATTRIBUTE #endif // GC was dropped by Apple, define the old constant incase anyone still keys // off of it. #ifndef GTM_SUPPORT_GC #define GTM_SUPPORT_GC 0 #endif // Some support for advanced clang static analysis functionality #ifndef NS_RETURNS_RETAINED #if __has_feature(attribute_ns_returns_retained) #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained)) #else #define NS_RETURNS_RETAINED #endif #endif #ifndef NS_RETURNS_NOT_RETAINED #if __has_feature(attribute_ns_returns_not_retained) #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) #else #define NS_RETURNS_NOT_RETAINED #endif #endif #ifndef CF_RETURNS_RETAINED #if __has_feature(attribute_cf_returns_retained) #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) #else #define CF_RETURNS_RETAINED #endif #endif #ifndef CF_RETURNS_NOT_RETAINED #if __has_feature(attribute_cf_returns_not_retained) #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained)) #else #define CF_RETURNS_NOT_RETAINED #endif #endif #ifndef NS_CONSUMED #if __has_feature(attribute_ns_consumed) #define NS_CONSUMED __attribute__((ns_consumed)) #else #define NS_CONSUMED #endif #endif #ifndef CF_CONSUMED #if __has_feature(attribute_cf_consumed) #define CF_CONSUMED __attribute__((cf_consumed)) #else #define CF_CONSUMED #endif #endif #ifndef NS_CONSUMES_SELF #if __has_feature(attribute_ns_consumes_self) #define NS_CONSUMES_SELF __attribute__((ns_consumes_self)) #else #define NS_CONSUMES_SELF #endif #endif #ifndef GTM_NONNULL #if defined(__has_attribute) #if __has_attribute(nonnull) #define GTM_NONNULL(x) __attribute__((nonnull x)) #else #define GTM_NONNULL(x) #endif #else #define GTM_NONNULL(x) #endif #endif // Invalidates the initializer from which it's called. #ifndef GTMInvalidateInitializer #if __has_feature(objc_arc) #define GTMInvalidateInitializer() \ do { \ [self class]; /* Avoid warning of dead store to |self|. */ \ _GTMDevAssert(NO, @"Invalid initializer."); \ return nil; \ } while (0) #else #define GTMInvalidateInitializer() \ do { \ [self release]; \ _GTMDevAssert(NO, @"Invalid initializer."); \ return nil; \ } while (0) #endif #endif #ifndef GTMCFAutorelease // GTMCFAutorelease returns an id. In contrast, Apple's CFAutorelease returns // a CFTypeRef. #if __has_feature(objc_arc) #define GTMCFAutorelease(x) CFBridgingRelease(x) #else #define GTMCFAutorelease(x) ([(id)x autorelease]) #endif #endif #ifdef __OBJC__ // Macro to allow you to create NSStrings out of other macros. // #define FOO foo // NSString *fooString = GTM_NSSTRINGIFY(FOO); #if !defined (GTM_NSSTRINGIFY) #define GTM_NSSTRINGIFY_INNER(x) @#x #define GTM_NSSTRINGIFY(x) GTM_NSSTRINGIFY_INNER(x) #endif // Macro to allow fast enumeration when building for 10.5 or later, and // reliance on NSEnumerator for 10.4. Remember, NSDictionary w/ FastEnumeration // does keys, so pick the right thing, nothing is done on the FastEnumeration // side to be sure you're getting what you wanted. #ifndef GTM_FOREACH_OBJECT #if TARGET_OS_IPHONE || !(MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) #define GTM_FOREACH_ENUMEREE(element, enumeration) \ for (element in enumeration) #define GTM_FOREACH_OBJECT(element, collection) \ for (element in collection) #define GTM_FOREACH_KEY(element, collection) \ for (element in collection) #else #define GTM_FOREACH_ENUMEREE(element, enumeration) \ for (NSEnumerator *_ ## element ## _enum = enumeration; \ (element = [_ ## element ## _enum nextObject]) != nil; ) #define GTM_FOREACH_OBJECT(element, collection) \ GTM_FOREACH_ENUMEREE(element, [collection objectEnumerator]) #define GTM_FOREACH_KEY(element, collection) \ GTM_FOREACH_ENUMEREE(element, [collection keyEnumerator]) #endif #endif // ============================================================================ // GTM_SEL_STRING is for specifying selector (usually property) names to KVC // or KVO methods. // In debug it will generate warnings for undeclared selectors if // -Wunknown-selector is turned on. // In release it will have no runtime overhead. #ifndef GTM_SEL_STRING #ifdef DEBUG #define GTM_SEL_STRING(selName) NSStringFromSelector(@selector(selName)) #else #define GTM_SEL_STRING(selName) @#selName #endif // DEBUG #endif // GTM_SEL_STRING #ifndef GTM_WEAK #if __has_feature(objc_arc_weak) // With ARC enabled, __weak means a reference that isn't implicitly // retained. __weak objects are accessed through runtime functions, so // they are zeroed out, but this requires OS X 10.7+. // At clang r251041+, ARC-style zeroing weak references even work in // non-ARC mode. #define GTM_WEAK __weak #elif __has_feature(objc_arc) // ARC, but targeting 10.6 or older, where zeroing weak references don't // exist. #define GTM_WEAK __unsafe_unretained #else // With manual reference counting, __weak used to be silently ignored. // clang r251041 gives it the ARC semantics instead. This means they // now require a deployment target of 10.7, while some clients of GTM // still target 10.6. In these cases, expand to __unsafe_unretained instead #define GTM_WEAK #endif #endif #endif // __OBJC__ ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: iOS/User/ezshopUser/Pods/GoogleToolboxForMac/README.md ================================================ # GTM: Google Toolbox for Mac # **Project site**
**Discussion group** # Google Toolbox for Mac # A collection of source from different Google projects that may be of use to developers working other iOS or OS X projects. If you find a problem/bug or want a new feature to be included in the Google Toolbox for Mac, please join the [discussion group](http://groups.google.com/group/google-toolbox-for-mac) or submit an [issue](https://github.com/google/google-toolbox-for-mac/issues). ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/README.md ================================================

Kingfisher

codebeat badge

Kingfisher is a lightweight, pure-Swift library for downloading and caching images from the web. This project is heavily inspired by the popular [SDWebImage](https://github.com/rs/SDWebImage). It provides you a chance to use a pure-Swift alternative in your next app. ## Features - [x] Asynchronous image downloading and caching. - [x] `URLSession`-based networking. Basic image processors and filters supplied. - [x] Multiple-layer cache for both memory and disk. - [x] Cancelable downloading and processing tasks to improve performance. - [x] Independent components. Use the downloader or caching system separately as you need. - [x] Prefetching images and showing them from cache later when necessary. - [x] Extensions for `UIImageView`, `NSImage` and `UIButton` to directly set an image from a URL. - [x] Built-in transition animation when setting images. - [x] Extensible image processing and image format support. The simplest use-case is setting an image to an image view with the `UIImageView` extension: ```swift let url = URL(string: "url_of_your_image") imageView.kf.setImage(with: url) ``` Kingfisher will download the image from `url`, send it to both the memory cache and the disk cache, and display it in `imageView`. When you use the same code later, the image will be retrieved from cache and shown immediately. ## Requirements - iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ - Swift 3 (Kingfisher 3.x), Swift 2.3 (Kingfisher 2.x) Main development of Kingfisher will support Swift 3. Only critical bug fixes will be made for Kingfisher 2.x. [Kingfisher 3.0 Migration Guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information. ## Next Steps We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there. * [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project. * [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher! * [API Reference](http://cocoadocs.org/docsets/Kingfisher/) - Lastly, please remember to read the full whenever you may need a more detailed reference. ## Other ### Future of Kingfisher I want to keep Kingfisher lightweight. This framework will focus on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better. ### About the logo The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions? ### Contact Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, just [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well. ### License Kingfisher is released under the MIT license. See LICENSE for details. ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/AnimatedImageView.swift ================================================ // // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2017 Reda Lemeden. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. open class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. public var runLoopMode = RunLoopMode.commonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var isDisplayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { if self.isAnimating { return } else { displayLink.isPaused = false } } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.cgImage } else { layer.contents = image?.cgImage } } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show GIF. override func shouldPreloadAllGIF() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf.imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) animator?.needsPrescaling = needsPrescaling animator?.prepareFramesAsynchronously() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false { layer.setNeedsDisplay() } } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: TimeInterval static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) } // MARK: - Animator class Animator { // MARK: Private property fileprivate let size: CGSize fileprivate let maxFrameCount: Int fileprivate let imageSource: CGImageSource fileprivate var animatedFrames = [AnimatedFrame]() fileprivate let maxTimeStep: TimeInterval = 1.0 fileprivate var frameCount = 0 fileprivate var currentFrameIndex = 0 fileprivate var currentPreloadIndex = 0 fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 fileprivate var needsPrescaling = true /// Loop count of animatd image. private var loopCount = 0 var currentFrame: UIImage? { return frame(at: currentFrameIndex) } var contentMode = UIViewContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - parameter framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) { self.imageSource = source self.contentMode = mode self.size = size self.maxFrameCount = count } func frame(at index: Int) -> Image? { return animatedFrames[safe: index]?.image } func prepareFramesAsynchronously() { preloadQueue.async { [weak self] in self?.prepareFrames() } } private func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0.. AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null } let defaultGIFFrameDuration = 0.100 let frameDuration = imageSource.kf.gifProperties(at: index).map { gifInfo -> Double in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime ?? 0.0 /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See and for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : defaultGIFFrameDuration } ?? defaultGIFFrameDuration let image = Image(cgImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf.resize(to: size, for: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndex currentFrameIndex += 1 currentFrameIndex = currentFrameIndex % animatedFrames.count if animatedFrames.count < frameCount { preloadFrameAsynchronously(at: lastFrameIndex) } return true } private func preloadFrameAsynchronously(at index: Int) { preloadQueue.async { [weak self] in self?.preloadFrame(at: index) } } private func preloadFrame(at index: Int) { animatedFrames[index] = prepareFrame(at: currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } } extension CGImageSource: KingfisherCompatible { } extension Kingfisher where Base: CGImageSource { func gifProperties(at index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] } } extension Array { subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } private func pure(_ value: T) -> [T] { return [value] } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Box.swift ================================================ // // Box.swift // Kingfisher // // Created by WANG WEI on 2016/09/12. // Copyright © 2016年 Wei Wang. All rights reserved. // import Foundation class Box { let value: T init(value: T) { self.value = value } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/CacheSerializer.swift ================================================ // // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. public protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. public struct DefaultCacheSerializer: CacheSerializer { public static let `default` = DefaultCacheSerializer() private init() {} public func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher.image( data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData, onlyFirstFrame: options.onlyLoadFirstFrame) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Filter.swift ================================================ // // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage import Accelerate // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Transformer method which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Supply a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Wrapper for a `Transformer` of CIImage filters. public struct Filter { let transform: Transformer public init(tranform: @escaping Transformer) { self.transform = tranform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let colorImage = colorFilter.outputImage let filter = CIFilter(name: "CISourceOverCompositing")! filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) return filter.outputImage?.cropping(to: input.extent) } } public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { brightness, contrast, saturation, inputEV in Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor) let paramsExposure = [kCIInputEVKey: inputEV] return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure) } } } extension Kingfisher where Base: Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } } public extension Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.", renamed: "kf.apply") public func kf_apply(_ filter: Filter) -> Image { return kf.apply(filter) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Image.swift ================================================ // // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? #endif private var animatedImageDataKey: Void? import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Kingfisher where Base: Image { fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CGFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: - Image Conversion extension Kingfisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // No need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Kingfisher where Base: Image { // MARK: - PNG public func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: - JPEG public func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF public func gifRepresentation() -> Data? { return animatedImageData } } // MARK: - Create images from data extension Kingfisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool, onlyFirstFrame: Bool = false) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary?) -> Double { let gifDefaultFrameDuration = 0.100 guard let gifInfo = gifInfo else { return gifDefaultFrameDuration } let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) else { return nil } let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary gifDuration += frameDuration(from: gifInfo) } images.append(Kingfisher.image(cgImage: imageRef, scale: scale, refImage: nil)) if onlyFirstFrame { break } } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image: Image? if onlyFirstFrame { image = images.first } else { image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration } image?.kf.animatedImageData = data return image #else let image: Image? if preloadAll || onlyFirstFrame { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } image = onlyFirstFrame ? images.first : Kingfisher.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) } else { image = Image(data: data) image?.kf.imageSource = ImageSource(ref: imageSource) } image?.kf.animatedImageData = data return image #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool, onlyFirstFrame: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Kingfisher.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Kingfisher.animated( with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData, onlyFirstFrame: onlyFirstFrame) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Kingfisher where Base: Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: let newSize = self.size.kf.constrained(size) return resize(to: newSize) case .scaleAspectFill: let newSize = self.size.kf.filling(size) return resize(to: newSize) default: return resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func resize(to size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return base #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = Float(max(radius, 2.0)) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. var targetRadius = floor(s * 3.0 * sqrt(2 * Float.pi) / 4.0 + 0.5) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = vImagePixelCount(context.width) let height = vImagePixelCount(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } guard let context = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = createEffectBuffer(context) guard let outContext = beginContext() else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } var outBuffer = createEffectBuffer(outContext) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Kingfisher where Base: Image { var decoded: Image? { return decoded(scale: scale) } func decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = beginContext() else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return base } defer { endContext() } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Kingfisher.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingfisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } public struct CGSizeProxy { fileprivate let base: CGSize init(proxy: CGSize) { base = proxy } } extension CGSize: KingfisherCompatible { public typealias CompatibleType = CGSizeProxy public var kf: CGSizeProxy { return CGSizeProxy(proxy: self) } } extension CGSizeProxy { func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension Kingfisher where Base: Image { func beginContext() -> CGContext? { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return nil } rep.size = size NSGraphicsContext.saveGraphicsState() guard let context = NSGraphicsContext(bitmapImageRep: rep) else { assertionFailure("[Kingfisher] Image contenxt cannot be created.") return nil } NSGraphicsContext.setCurrent(context) return context.cgContext #else UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.scaleBy(x: 1.0, y: -1.0) context?.translateBy(x: 0, y: -size.height) return context #endif } func endContext() { #if os(macOS) NSGraphicsContext.restoreGraphicsState() #else UIGraphicsEndImageContext() #endif } func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return base } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension Float { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Deprecated. Only for back compatibility. extension Image { /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", renamed: "kf.normalized") public func kf_normalized() -> Image { return kf.normalized } // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", renamed: "kf.image") public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return kf.image(withRoundRadius: radius, fit: size) } // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", renamed: "kf.resize") public func kf_resize(to size: CGSize) -> Image { return kf.resize(to: size) } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", renamed: "kf.blurred") public func kf_blurred(withRadius radius: CGFloat) -> Image { return kf.blurred(withRadius: radius) } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", renamed: "kf.overlaying") public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { return kf.overlaying(with: color, fraction: fraction) } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", renamed: "kf.tinted") public func kf_tinted(with color: Color) -> Image { return kf.tinted(with: color) } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", renamed: "kf.adjusted") public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) } } extension Kingfisher where Base: Image { @available(*, deprecated, message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)") public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return image(withRoundRadius: radius, fit: size) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImageCache.swift ================================================ // // ImageCache.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif public extension Notification.Name { /** This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification. The `object` of this notification is the `ImageCache` object which sends the notification. A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed. The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it. */ public static var KingfisherDidCleanDiskCache = Notification.Name.init("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") } /** Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. */ public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" /// It represents a task of retrieving image. You can call `cancel` on it to stop the process. public typealias RetrieveImageDiskTask = DispatchWorkItem /** Cache type of a cached image. - None: The image is not cached yet when retrieving it. - Memory: The image is cached in memory. - Disk: The image is cached in disk. */ public enum CacheType { case none, memory, disk } /// `ImageCache` represents both the memory and disk cache system of Kingfisher. /// While a default image cache object will be used if you prefer the extension methods of Kingfisher, /// you can create your own cache object and configure it as your need. You could use an `ImageCache` /// object to manipulate memory and disk cache for Kingfisher. open class ImageCache { //Memory fileprivate let memoryCache = NSCache() /// The largest cache cost of memory cache. The total cost is pixel count of /// all cached images in memory. /// Default is unlimited. Memory cache will be purged automatically when a /// memory warning notification is received. open var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //Disk fileprivate let ioQueue: DispatchQueue fileprivate var fileManager: FileManager! ///The disk cache location. open let diskCachePath: String /// The default file extension appended to cached files. open var pathExtension: String? /// The longest time duration in second of the cache being stored in disk. /// Default is 1 week (60 * 60 * 24 * 7 seconds). /// Setting this to a negative value will make the disk cache never expiring. open var maxCachePeriodInSecond: TimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week /// The largest disk size can be taken for the cache. It is the total /// allocated size of cached files in bytes. /// Default is no limit. open var maxDiskCacheSize: UInt = 0 fileprivate let processQueue: DispatchQueue /// The default cache. public static let `default` = ImageCache(name: "default") /// Closure that defines the disk cache path from a given path and cacheName. public typealias DiskCachePathClosure = (String?, String) -> String /// The default DiskCachePathClosure public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String { let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! return (dstPath as NSString).appendingPathComponent(cacheName) } /** Init method. Passing a name for the cache. It represents a cache folder in the memory and disk. - parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string. - parameter path: Optional - Location of cache path on disk. If `nil` is passed in (the default value), the `.cachesDirectory` in of your app will be used. - parameter diskCachePathClosure: Closure that takes in an optional initial path string and generates the final disk cache path. You could use it to fully customize your cache path. - returns: The cache object. */ public init(name: String, path: String? = nil, diskCachePathClosure: DiskCachePathClosure = ImageCache.defaultDiskCachePathClosure) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") } let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)" memoryCache.name = cacheName diskCachePath = diskCachePathClosure(path, cacheName) let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)" ioQueue = DispatchQueue(label: ioQueueName) let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)" processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent) ioQueue.sync { fileManager = FileManager() } #if !os(macOS) && !os(watchOS) NotificationCenter.default.addObserver( self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(cleanExpiredDiskCache), name: .UIApplicationWillTerminate, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil) #endif } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Store & Remove /** Store an image to cache. It will be saved to both memory and disk. It is an async operation. - parameter image: The image to be stored. - parameter original: The original data of the image. Kingfisher will use it to check the format of the image and optimize cache size on disk. If `nil` is supplied, the image data will be saved as a normalized PNG file. It is strongly suggested to supply it whenever possible, to get a better performance and disk usage. - parameter key: Key for the image. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. This identifier will be used to generate a corresponding key for the combination of `key` and processor. - parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory. - parameter completionHandler: Called when store operation completes. */ open func store(_ image: Image, original: Data? = nil, forKey key: String, processorIdentifier identifier: String = "", cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, toDisk: Bool = true, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) memoryCache.setObject(image, forKey: computedKey as NSString, cost: image.kf.imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { DispatchQueue.main.async { handler() } } } if toDisk { ioQueue.async { if let data = serializer.data(with: image, original: original) { if !self.fileManager.fileExists(atPath: self.diskCachePath) { do { try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ {} } self.fileManager.createFile(atPath: self.cachePath(forComputedKey: computedKey), contents: data, attributes: nil) } callHandlerInMainQueue() } } else { callHandlerInMainQueue() } } /** Remove the image for key for the cache. It will be opted out from both memory and disk. It is an async operation. - parameter key: Key for the image. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. This identifier will be used to generate a corresponding key for the combination of `key` and processor. - parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory. - parameter completionHandler: Called when removal operation completes. */ open func removeImage(forKey key: String, processorIdentifier identifier: String = "", fromDisk: Bool = true, completionHandler: (() -> Void)? = nil) { let computedKey = key.computedKey(with: identifier) memoryCache.removeObject(forKey: computedKey as NSString) func callHandlerInMainQueue() { if let handler = completionHandler { DispatchQueue.main.async { handler() } } } if fromDisk { ioQueue.async{ do { try self.fileManager.removeItem(atPath: self.cachePath(forComputedKey: computedKey)) } catch _ {} callHandlerInMainQueue() } } else { callHandlerInMainQueue() } } // MARK: - Get data from cache /** Get an image for a key from memory or disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`. - returns: The retrieving task. */ @discardableResult open func retrieveImage(forKey key: String, options: KingfisherOptionsInfo?, completionHandler: ((Image?, CacheType) -> ())?) -> RetrieveImageDiskTask? { // No completion handler. Not start working and early return. guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? let options = options ?? KingfisherEmptyOptionsInfo if let image = self.retrieveImageInMemoryCache(forKey: key, options: options) { options.callbackDispatchQueue.safeAsync { completionHandler(image, .memory) } } else { var sSelf: ImageCache! = self block = DispatchWorkItem(block: { // Begin to load image from disk if let image = sSelf.retrieveImageInDiskCache(forKey: key, options: options) { if options.backgroundDecode { sSelf.processQueue.async { let result = image.kf.decoded(scale: options.scaleFactor) sSelf.store(result, forKey: key, processorIdentifier: options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: false, completionHandler: nil) options.callbackDispatchQueue.safeAsync { completionHandler(result, .memory) sSelf = nil } } } else { sSelf.store(image, forKey: key, processorIdentifier: options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: false, completionHandler: nil ) options.callbackDispatchQueue.safeAsync { completionHandler(image, .disk) sSelf = nil } } } else { // No image found from either memory or disk options.callbackDispatchQueue.safeAsync { completionHandler(nil, .none) sSelf = nil } } }) sSelf.ioQueue.async(execute: block!) } return block } /** Get an image for a key from memory. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ open func retrieveImageInMemoryCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo let computedKey = key.computedKey(with: options.processor.identifier) return memoryCache.object(forKey: computedKey as NSString) as? Image } /** Get an image for a key from disk. - parameter key: Key for the image. - parameter options: Options of retrieving image. If you need to retrieve an image which was stored with a specified `ImageProcessor`, pass the processor in the option too. - returns: The image object if it is cached, or `nil` if there is no such key in the cache. */ open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo let computedKey = key.computedKey(with: options.processor.identifier) return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options) } // MARK: - Clear & Clean /** Clear memory cache. */ @objc public func clearMemoryCache() { memoryCache.removeAllObjects() } /** Clear disk cache. This is an async operation. - parameter completionHander: Called after the operation completes. */ open func clearDiskCache(completion handler: (()->())? = nil) { ioQueue.async { do { try self.fileManager.removeItem(atPath: self.diskCachePath) try self.fileManager.createDirectory(atPath: self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch _ { } if let handler = handler { DispatchQueue.main.async { handler() } } } } /** Clean expired disk cache. This is an async operation. */ @objc fileprivate func cleanExpiredDiskCache() { cleanExpiredDiskCache(completion: nil) } /** Clean expired disk cache. This is an async operation. - parameter completionHandler: Called after the operation completes. */ open func cleanExpiredDiskCache(completion handler: (()->())? = nil) { // Do things in cocurrent io queue ioQueue.async { var (URLsToDelete, diskCacheSize, cachedFiles) = self.travelCachedFiles(onlyForCacheSize: false) for fileURL in URLsToDelete { do { try self.fileManager.removeItem(at: fileURL) } catch _ { } } if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize { let targetSize = self.maxDiskCacheSize / 2 // Sort files by last modify date. We want to clean from the oldest files. let sortedFiles = cachedFiles.keysSortedByValue { resourceValue1, resourceValue2 -> Bool in if let date1 = resourceValue1.contentAccessDate, let date2 = resourceValue2.contentAccessDate { return date1.compare(date2) == .orderedAscending } // Not valid date information. This should not happen. Just in case. return true } for fileURL in sortedFiles { do { try self.fileManager.removeItem(at: fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?.totalFileAllocatedSize { diskCacheSize -= UInt(fileSize) } if diskCacheSize < targetSize { break } } } DispatchQueue.main.async { if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map { $0.lastPathComponent } NotificationCenter.default.post(name: .KingfisherDidCleanDiskCache, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) } handler?() } } } fileprivate func travelCachedFiles(onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) { let diskCacheURL = URL(fileURLWithPath: diskCachePath) let resourceKeys: Set = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey] let expiredDate: Date? = (maxCachePeriodInSecond < 0) ? nil : Date(timeIntervalSinceNow: -maxCachePeriodInSecond) var cachedFiles = [URL: URLResourceValues]() var urlsToDelete = [URL]() var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumerator(at: diskCacheURL, includingPropertiesForKeys: Array(resourceKeys), options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles, errorHandler: nil), let urls = fileEnumerator.allObjects as? [URL] { for fileUrl in urls { do { let resourceValues = try fileUrl.resourceValues(forKeys: resourceKeys) // If it is a Directory. Continue to next file URL. if resourceValues.isDirectory == true { continue } // If this file is expired, add it to URLsToDelete if !onlyForCacheSize, let expiredDate = expiredDate, let lastAccessData = resourceValues.contentAccessDate, (lastAccessData as NSDate).laterDate(expiredDate) == expiredDate { urlsToDelete.append(fileUrl) continue } if let fileSize = resourceValues.totalFileAllocatedSize { diskCacheSize += UInt(fileSize) if !onlyForCacheSize { cachedFiles[fileUrl] = resourceValues } } } catch _ { } } } return (urlsToDelete, diskCacheSize, cachedFiles) } #if !os(macOS) && !os(watchOS) /** Clean expired disk cache when app in background. This is an async operation. In most cases, you should not call this method explicitly. It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. */ @objc public func backgroundCleanExpiredDiskCache() { // if 'sharedApplication()' is unavailable, then return guard let sharedApplication = Kingfisher.shared else { return } func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { sharedApplication.endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = sharedApplication.beginBackgroundTask { endBackgroundTask(&backgroundTask!) } cleanExpiredDiskCache { endBackgroundTask(&backgroundTask!) } } #endif // MARK: - Check cache status /** * Cache result for checking whether an image is cached for a key. */ public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } /** Check whether an image is cached for a key. - parameter key: Key for the image. - returns: The check result. */ open func isImageCached(forKey key: String, processorIdentifier identifier: String = "") -> CacheCheckResult { let computedKey = key.computedKey(with: identifier) if memoryCache.object(forKey: computedKey as NSString) != nil { return CacheCheckResult(cached: true, cacheType: .memory) } let filePath = cachePath(forComputedKey: computedKey) var diskCached = false ioQueue.sync { diskCached = fileManager.fileExists(atPath: filePath) } if diskCached { return CacheCheckResult(cached: true, cacheType: .disk) } return CacheCheckResult(cached: false, cacheType: nil) } /** Get the hash for the key. This could be used for matching files. - parameter key: The key which is used for caching. - parameter identifier: The identifier of processor used. If you are using a processor for the image, pass the identifier of processor to it. - returns: Corresponding hash. */ open func hash(forKey key: String, processorIdentifier identifier: String = "") -> String { let computedKey = key.computedKey(with: identifier) return cacheFileName(forComputedKey: computedKey) } /** Calculate the disk size taken by cache. It is the total allocated size of the cached files in bytes. - parameter completionHandler: Called with the calculated size when finishes. */ open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) { ioQueue.async { let (_, diskCacheSize, _) = self.travelCachedFiles(onlyForCacheSize: true) DispatchQueue.main.async { handler(diskCacheSize) } } } /** Get the cache path for the key. It is useful for projects with UIWebView or anyone that needs access to the local file path. i.e. Replace the `` tag in your HTML. - Note: This method does not guarantee there is an image already cached in the path. It just returns the path that the image should be. You could use `isImageCached(forKey:)` method to check whether the image is cached under that key. */ open func cachePath(forKey key: String, processorIdentifier identifier: String = "") -> String { let computedKey = key.computedKey(with: identifier) return cachePath(forComputedKey: computedKey) } open func cachePath(forComputedKey key: String) -> String { let fileName = cacheFileName(forComputedKey: key) return (diskCachePath as NSString).appendingPathComponent(fileName) } } // MARK: - Internal Helper extension ImageCache { func diskImage(forComputedKey key: String, serializer: CacheSerializer, options: KingfisherOptionsInfo) -> Image? { if let data = diskImageData(forComputedKey: key) { return serializer.image(with: data, options: options) } else { return nil } } func diskImageData(forComputedKey key: String) -> Data? { let filePath = cachePath(forComputedKey: key) return (try? Data(contentsOf: URL(fileURLWithPath: filePath))) } func cacheFileName(forComputedKey key: String) -> String { if let ext = self.pathExtension { return (key.kf.md5 as NSString).appendingPathExtension(ext)! } return key.kf.md5 } } extension Kingfisher where Base: Image { var imageCost: Int { return images == nil ? Int(size.height * size.width * scale * scale) : Int(size.height * size.width * scale * scale) * images!.count } } extension Dictionary { func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } } } #if !os(macOS) && !os(watchOS) // MARK: - For App Extensions extension UIApplication: KingfisherCompatible { } extension Kingfisher where Base: UIApplication { public static var shared: UIApplication? { let selector = NSSelectorFromString("sharedApplication") guard Base.responds(to: selector) else { return nil } return Base.perform(selector).takeUnretainedValue() as? UIApplication } } #endif extension String { func computedKey(with identifier: String) -> String { if identifier.isEmpty { return self } else { return appending("@\(identifier)") } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImageDownloader.swift ================================================ // // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: URLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var url: URL? { return internalTask.originalRequest?.url } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } ///The code of errors which `ImageDownloader` might encountered. public enum KingfisherError: Int { /// badData: The downloaded data is not an image or the data is corrupted. case badData = 10000 /// notModified: The remote server responsed a 304 code. No image data downloaded. case notModified = 10001 /// The HTTP status code in response is not valid. If an invalid /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` /// in `userInfo` to see the code. case invalidStatusCode = 10002 /// notCached: The image rquested is not in cache but .onlyFromCache is activated. case notCached = 10003 /// The URL is invalid. case invalidURL = 20000 /// The downloading task is cancelled before started. case downloadCancelledBeforeStarting = 30000 } /// Key will be used in the `userInfo` of `.invalidStatusCode` public let KingfisherErrorStatusCodeKey = "statusCode" /// Protocol of `ImageDownloader`. public protocol ImageDownloaderDelegate: class { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter url: URL of the original request URL. - parameter response: The response object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) /** Check if a received HTTP status code is valid or not. By default, a status code between 200 to 400 (excluded) is considered as valid. If an invalid code is received, the downloader will raise an .invalidStatusCode error. It has a `userInfo` which includes this statusCode and localizedString error message. - parameter code: The received HTTP status code. - parameter downloader: The `ImageDownloader` object asking for validate status code. - returns: Whether this HTTP status code is valid or not. - Note: If the default 200 to 400 valid code does not suit your need, you can implement this method to change that behavior. */ func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool } extension ImageDownloaderDelegate { public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { return (200..<400).contains(code) } } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponsable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { class ImageFetchLoad { var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? } // MARK: - Public property /// The duration before the download is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) } } /// Whether the download requests should use pipeling or not. Default is false. open var requestsUsePipeling = false fileprivate let sessionHandler: ImageDownloaderSessionHandler fileprivate var session: URLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? // MARK: - Internal property let barrierQueue: DispatchQueue let processQueue: DispatchQueue typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) var fetchLoads = [URL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public static let `default` = ImageDownloader(name: "default") /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) sessionHandler = ImageDownloaderSessionHandler() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) } func fetchLoad(for url: URL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? barrierQueue.sync { fetchLoad = fetchLoads[url] } return fetchLoad } /** Download an image with a URL and option. - parameter url: Target URL. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ @discardableResult open func downloadImage(with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? { return downloadImage(with: url, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } } // MARK: - Download method extension ImageDownloader { func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask?, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) request.httpShouldUsePipelining = requestsUsePipeling if let modifier = options?.modifier { guard let r = modifier.modified(for: request) else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } request = r } // There is a possiblility that request modifier changed the url to `nil` or empty. guard let url = request.url, !url.absoluteString.isEmpty else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) return nil } var downloadTask: RetrieveImageDownloadTask? setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTask(with: request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority dataTask.resume() // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } // A single key may have multiple callbacks. Only download once. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: ((URLSession, ImageFetchLoad) -> Void)) { barrierQueue.sync(flags: .barrier) { let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) fetchLoads[url] = loadObjectForURL if let session = session { started(session, loadObjectForURL) } } } func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { barrierQueue.sync { if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func clean(for url: URL) { barrierQueue.sync(flags: .barrier) { fetchLoads.removeValue(forKey: url) return } } } // MARK: - NSURLSessionDataDelegate /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. // See https://github.com/onevcat/Kingfisher/issues/235 class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let downloader = downloadHolder else { completionHandler(.cancel) return } if let statusCode = (response as? HTTPURLResponse)?.statusCode, let url = dataTask.originalRequest?.url, !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) callCompletionHandlerFailure(error: error, url: url) } completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let downloader = downloadHolder else { return } if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { fetchLoad.responseData.append(data) if let expectedLength = dataTask.response?.expectedContentLength { for content in fetchLoad.contents { DispatchQueue.main.async { content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) } } } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { callCompletionHandlerFailure(error: error!, url: url) return } processImage(for: task, url: url) } /** This method is exposed since the compiler requests. Do not call it. */ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) } private func cleanFetchLoad(for url: URL) { guard let downloader = downloadHolder else { return } downloader.clean(for: url) if downloader.fetchLoads.isEmpty { downloadHolder = nil } } private func callCompletionHandlerFailure(error: Error, url: URL) { guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { return } // We need to clean the fetch load first, before actually calling completion handler. cleanFetchLoad(for: url) for content in fetchLoad.contents { content.options.callbackDispatchQueue.safeAsync { content.callback.completionHandler?(nil, error as NSError, url, nil) } } } private func processImage(for task: URLSessionTask, url: URL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. downloader.processQueue.async { guard let fetchLoad = downloader.fetchLoad(for: url) else { return } self.cleanFetchLoad(for: url) let data = fetchLoad.responseData as Data // Cache the processed images. So we do not need to re-process the image if using the same processor. // Key is the identifier of processor. var imageCache: [String: Image] = [:] for content in fetchLoad.contents { let options = content.options let completionHandler = content.callback.completionHandler let callbackQueue = options.callbackDispatchQueue let processor = options.processor var image = imageCache[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: options) // Add the processed image to cache. // If `image` is nil, nothing will happen (since the key is not existing before). imageCache[processor.identifier] = image } if let image = image { downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) if options.backgroundDecode { let decodedImage = image.kf.decoded(scale: options.scaleFactor) callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } } else { callbackQueue.safeAsync { completionHandler?(image, nil, url, data) } } } else { if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) completionHandler?(nil, notModified, url, nil) continue } let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } } } } } } // Placeholder. For retrieving extension methods of ImageDownloaderDelegate extension ImageDownloader: ImageDownloaderDelegate {} ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImagePrefetcher.swift ================================================ // // ImagePrefetcher.swift // Kingfisher // // Created by Claire Knight on 24/02/2016 // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// Completion block of prefetcher. /// /// - `skippedResources`: An array of resources that are already cached before the prefetching starting. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all. /// - `completedResources`: An array of resources that are downloaded and cached successfully. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ()) /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. /// This is useful when you know a list of image resources and want to download them before showing. public class ImagePrefetcher { /// The maximum concurrent downloads to use when prefetching images. Default is 5. public var maxConcurrentDownloads = 5 private let prefetchResources: [Resource] private let optionsInfo: KingfisherOptionsInfo private var progressBlock: PrefetcherProgressBlock? private var completionHandler: PrefetcherCompletionHandler? private var tasks = [URL: RetrieveImageDownloadTask]() private var pendingResources: ArraySlice private var skippedResources = [Resource]() private var completedResources = [Resource]() private var failedResources = [Resource]() private var stopped = false // The created manager used for prefetch. We will use the helper method in manager. private let manager: KingfisherManager private var finished: Bool { return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty } /** Init an image prefetcher with an array of URLs. The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter urls: The URLs which should be prefetched. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public convenience init(urls: [URL], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { let resources: [Resource] = urls.map { $0 } self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Init an image prefetcher with an array of resources. The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable. After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process. The images already cached will be skipped without downloading again. - parameter resources: The resources which should be prefetched. See `Resource` type for more. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled. - parameter completionHandler: Called when the whole prefetching process finished. - returns: An `ImagePrefetcher` object. - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method. */ public init(resources: [Resource], options: KingfisherOptionsInfo? = nil, progressBlock: PrefetcherProgressBlock? = nil, completionHandler: PrefetcherCompletionHandler? = nil) { prefetchResources = resources pendingResources = ArraySlice(resources) // We want all callbacks from main queue, so we ignore the call back queue in options let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil)) self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo let cache = self.optionsInfo.targetCache let downloader = self.optionsInfo.downloader manager = KingfisherManager(downloader: downloader, cache: cache) self.progressBlock = progressBlock self.completionHandler = completionHandler } /** Start to download the resources and cache them. This can be useful for background downloading of assets that are required for later use in an app. This code will not try and update any UI with the results of the process. */ public func start() { // Since we want to handle the resources cancellation in main thread only. DispatchQueue.main.safeAsync { guard !self.stopped else { assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") self.handleComplete() return } guard self.maxConcurrentDownloads > 0 else { assertionFailure("There should be concurrent downloads value should be at least 1.") self.handleComplete() return } guard self.prefetchResources.count > 0 else { self.handleComplete() return } let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads) for _ in 0 ..< initialConcurentDownloads { if let resource = self.pendingResources.popFirst() { self.startPrefetching(resource) } } } } /** Stop current downloading progress, and cancel any future prefetching activity that might be occuring. */ public func stop() { DispatchQueue.main.safeAsync { if self.finished { return } self.stopped = true self.tasks.forEach { (_, task) -> () in task.cancel() } } } func downloadAndCache(_ resource: Resource) { let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in self.tasks.removeValue(forKey: resource.downloadURL) if let _ = error { self.failedResources.append(resource) } else { self.completedResources.append(resource) } self.reportProgress() if self.stopped { if self.tasks.isEmpty { self.failedResources.append(contentsOf: self.pendingResources) self.handleComplete() } } else { self.reportCompletionOrStartNext() } } let downloadTask = manager.downloadAndCacheImage( with: resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: downloadTaskCompletionHandler, options: optionsInfo) if let downloadTask = downloadTask { tasks[resource.downloadURL] = downloadTask } } func append(cached resource: Resource) { skippedResources.append(resource) reportProgress() reportCompletionOrStartNext() } func startPrefetching(_ resource: Resource) { if optionsInfo.forceRefresh { downloadAndCache(resource) } else { let alreadyInCache = manager.cache.isImageCached(forKey: resource.cacheKey, processorIdentifier: optionsInfo.processor.identifier).cached if alreadyInCache { append(cached: resource) } else { downloadAndCache(resource) } } } func reportProgress() { progressBlock?(skippedResources, failedResources, completedResources) } func reportCompletionOrStartNext() { if let resource = pendingResources.popFirst() { startPrefetching(resource) } else { guard tasks.isEmpty else { return } handleComplete() } } func handleComplete() { completionHandler?(skippedResources, failedResources, completedResources) completionHandler = nil progressBlock = nil } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImageProcessor.swift ================================================ // // ImageProcessor.swift // Kingfisher // // Created by Wei Wang on 2016/08/26. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics /// The item which could be processed by an `ImageProcessor` /// /// - image: Input image /// - data: Input data public enum ImageProcessItem { case image(Image) case data(Data) } /// An `ImageProcessor` would be used to convert some downloaded data to an image. public protocol ImageProcessor { /// Identifier of the processor. It will be used to identify the processor when /// caching and retriving an image. You might want to make sure that processors with /// same properties/functionality have the same identifiers, so correct processed images /// could be retrived with proper key. /// /// - Note: Do not supply an empty string for a customized processor, which is already taken by /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation /// string of your own for the identifier. var identifier: String { get } /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: The return value will be `nil` if processing failed while converting data to image. /// If input item is already an image and there is any errors in processing, the input /// image itself will be returned. /// - Note: Most processor only supports CG-based images. /// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? } typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?) public extension ImageProcessor { /// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor` /// will be "\(self.identifier)|>\(another.identifier)". /// /// - parameter another: An `ImageProcessor` you want to append to `self`. /// /// - returns: The new `ImageProcessor`. It will process the image in the order /// of the two processors concatenated. public func append(another: ImageProcessor) -> ImageProcessor { let newIdentifier = identifier.appending("|>\(another.identifier)") return GeneralProcessor(identifier: newIdentifier) { item, options in if let image = self.process(item: item, options: options) { return another.process(item: .image(image), options: options) } else { return nil } } } } fileprivate struct GeneralProcessor: ImageProcessor { let identifier: String let p: ProcessorImp func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return p(item, options) } } /// The default processor. It convert the input data to a valid image. /// Images of .PNG, .JPEG and .GIF format are supported. /// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image. public struct DefaultImageProcessor: ImageProcessor { /// A default `DefaultImageProcessor` could be used across. public static let `default` = DefaultImageProcessor() public let identifier = "" /// Initialize a `DefaultImageProcessor` /// /// - returns: An initialized `DefaultImageProcessor`. public init() {} public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image case .data(let data): return Kingfisher.image( data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData, onlyFirstFrame: options.onlyLoadFirstFrame) } } } /// Processor for making round corner images. Only CG-based images are supported in macOS, /// if a non-CG image passed in, the processor will do nothing. public struct RoundCornerImageProcessor: ImageProcessor { public let identifier: String /// Corner radius will be applied in processing. public let cornerRadius: CGFloat /// Target size of output image should be. If `nil`, the image will keep its original size after processing. public let targetSize: CGSize? /// Initialize a `RoundCornerImageProcessor` /// /// - parameter cornerRadius: Corner radius will be applied in processing. /// - parameter targetSize: Target size of output image should be. If `nil`, /// the image will keep its original size after processing. /// Default is `nil`. /// /// - returns: An initialized `RoundCornerImageProcessor`. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) { self.cornerRadius = cornerRadius self.targetSize = targetSize if let size = targetSize { self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))" } else { self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))" } } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let size = targetSize ?? image.kf.size return image.kf.image(withRoundRadius: cornerRadius, fit: size) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for resizing images. Only CG-based images are supported in macOS. public struct ResizingImageProcessor: ImageProcessor { public let identifier: String /// Target size of output image should be. public let targetSize: CGSize /// Initialize a `ResizingImageProcessor` /// /// - parameter targetSize: Target size of output image should be. /// /// - returns: An initialized `ResizingImageProcessor`. public init(targetSize: CGSize) { self.targetSize = targetSize self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.resize(to: targetSize) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for /// a better performance. A simulated Gaussian blur with specified blur radius will be applied. public struct BlurImageProcessor: ImageProcessor { public let identifier: String /// Blur radius for the simulated Gaussian blur. public let blurRadius: CGFloat /// Initialize a `BlurImageProcessor` /// /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. /// /// - returns: An initialized `BlurImageProcessor`. public init(blurRadius: CGFloat) { self.blurRadius = blurRadius self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): let radius = blurRadius * options.scaleFactor return image.kf.blurred(withRadius: radius) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for adding an overlay to images. Only CG-based images are supported in macOS. public struct OverlayImageProcessor: ImageProcessor { public var identifier: String /// Overlay color will be used to overlay the input image. public let overlay: Color /// Fraction will be used when overlay the color to image. public let fraction: CGFloat /// Initialize an `OverlayImageProcessor` /// /// - parameter overlay: Overlay color will be used to overlay the input image. /// - parameter fraction: Fraction will be used when overlay the color to image. /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An initialized `OverlayImageProcessor`. public init(overlay: Color, fraction: CGFloat = 0.5) { self.overlay = overlay self.fraction = fraction self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.overlaying(with: overlay, fraction: fraction) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for tint images with color. Only CG-based images are supported. public struct TintImageProcessor: ImageProcessor { public let identifier: String /// Tint color will be used to tint the input image. public let tint: Color /// Initialize a `TintImageProcessor` /// /// - parameter tint: Tint color will be used to tint the input image. /// /// - returns: An initialized `TintImageProcessor`. public init(tint: Color) { self.tint = tint self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.tinted(with: tint) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying some color control to images. Only CG-based images are supported. /// watchOS is not supported. public struct ColorControlsProcessor: ImageProcessor { public let identifier: String /// Brightness changing to image. public let brightness: CGFloat /// Contrast changing to image. public let contrast: CGFloat /// Saturation changing to image. public let saturation: CGFloat /// InputEV changing to image. public let inputEV: CGFloat /// Initialize a `ColorControlsProcessor` /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An initialized `ColorControlsProcessor` public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { self.brightness = brightness self.contrast = contrast self.saturation = saturation self.inputEV = inputEV self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" } public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Processor for applying black and white effect to images. Only CG-based images are supported. /// watchOS is not supported. public struct BlackWhiteProcessor: ImageProcessor { public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" /// Initialize a `BlackWhiteProcessor` /// /// - returns: An initialized `BlackWhiteProcessor` public init() {} public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) .process(item: item, options: options) } } /// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally. /// /// - parameter left: First processor. /// - parameter right: Second processor. /// /// - returns: The concatenated processor. public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { return left.append(another: right) } fileprivate extension Color { var hex: String { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rInt = Int(r * 255) << 24 let gInt = Int(g * 255) << 16 let bInt = Int(b * 255) << 8 let aInt = Int(a * 255) let rgba = rInt | gInt | bInt | aInt return String(format:"#%08x", rgba) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImageTransition.swift ================================================ // // ImageTransition.swift // Kingfisher // // Created by Wei Wang on 15/9/18. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) // Not implemented for macOS and watchOS yet. import AppKit /// Image transition is not supported on macOS. public enum ImageTransition { case none var duration: TimeInterval { return 0 } } #elseif os(watchOS) import UIKit /// Image transition is not supported on watchOS. public enum ImageTransition { case none var duration: TimeInterval { return 0 } } #else import UIKit /** Transition effect which will be used when an image downloaded and set by `UIImageView` extension API in Kingfisher. You can assign an enum value with transition duration as an item in `KingfisherOptionsInfo` to enable the animation transition. Apple's UIViewAnimationOptions is used under the hood. For custom transition, you should specified your own transition options, animations and comletion handler as well. */ public enum ImageTransition { /// No animation transistion. case none /// Fade in the loaded image. case fade(TimeInterval) /// Flip from left transition. case flipFromLeft(TimeInterval) /// Flip from right transition. case flipFromRight(TimeInterval) /// Flip from top transition. case flipFromTop(TimeInterval) /// Flip from bottom transition. case flipFromBottom(TimeInterval) /// Custom transition. case custom(duration: TimeInterval, options: UIViewAnimationOptions, animations: ((UIImageView, UIImage) -> Void)?, completion: ((Bool) -> Void)?) var duration: TimeInterval { switch self { case .none: return 0 case .fade(let duration): return duration case .flipFromLeft(let duration): return duration case .flipFromRight(let duration): return duration case .flipFromTop(let duration): return duration case .flipFromBottom(let duration): return duration case .custom(let duration, _, _, _): return duration } } var animationOptions: UIViewAnimationOptions { switch self { case .none: return [] case .fade(_): return .transitionCrossDissolve case .flipFromLeft(_): return .transitionFlipFromLeft case .flipFromRight(_): return .transitionFlipFromRight case .flipFromTop(_): return .transitionFlipFromTop case .flipFromBottom(_): return .transitionFlipFromBottom case .custom(_, let options, _, _): return options } } var animations: ((UIImageView, UIImage) -> Void)? { switch self { case .custom(_, _, let animations, _): return animations default: return { $0.image = $1 } } } var completion: ((Bool) -> Void)? { switch self { case .custom(_, _, _, let completion): return completion default: return nil } } } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift ================================================ // // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif // MARK: - Extension methods. /** * Set image to use from web. */ extension Kingfisher where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.image = placeholder completionHandler?(nil, nil, .none, nil) return .empty } var options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.image = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) if base.shouldPreloadAllGIF() { options.append(.preloadAllGIFData) } let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { return } self.setImageTask(nil) guard let image = image else { maybeIndicator?.stopAnimatingView() completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { maybeIndicator?.stopAnimatingView() strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } #if !os(macOS) UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) #endif } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { newIndicator.view.frame = base.frame newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage") @discardableResult public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask") public func kf_cancelDownloadTask() { kf.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType") public var kf_indicatorType: IndicatorType { get { return kf.indicatorType } set { kf.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `kf_indicatorType` is `.none`. public private(set) var kf_indicator: Indicator? { get { return kf.indicator } set { kf.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } } extension ImageView { func shouldPreloadAllGIF() -> Bool { return true } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Indicator.swift ================================================ // // Indicator.swift // Kingfisher // // Created by João D. Moreira on 30/08/16. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif #if os(macOS) public typealias IndicatorView = NSView #else public typealias IndicatorView = UIView #endif public enum IndicatorType { /// No indicator. case none /// Use system activity indicator. case activity /// Use an image as indicator. GIF is supported. case image(imageData: Data) /// Use a custom indicator, which conforms to the `Indicator` protocol. case custom(indicator: Indicator) } // MARK: - Indicator Protocol public protocol Indicator { func startAnimatingView() func stopAnimatingView() var viewCenter: CGPoint { get set } var view: IndicatorView { get } } extension Indicator { #if os(macOS) public var viewCenter: CGPoint { get { let frame = view.frame return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) } set { let frame = view.frame let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, y: newValue.y - frame.size.height / 2.0, width: frame.size.width, height: frame.size.height) view.frame = newFrame } } #else public var viewCenter: CGPoint { get { return view.center } set { view.center = newValue } } #endif } // MARK: - ActivityIndicator // Displays a NSProgressIndicator / UIActivityIndicatorView struct ActivityIndicator: Indicator { #if os(macOS) private let activityIndicatorView: NSProgressIndicator #else private let activityIndicatorView: UIActivityIndicatorView #endif var view: IndicatorView { return activityIndicatorView } func startAnimatingView() { #if os(macOS) activityIndicatorView.startAnimation(nil) #else activityIndicatorView.startAnimating() #endif activityIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) activityIndicatorView.stopAnimation(nil) #else activityIndicatorView.stopAnimating() #endif activityIndicatorView.isHidden = true } init() { #if os(macOS) activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) activityIndicatorView.controlSize = .small activityIndicatorView.style = .spinningStyle #else #if os(tvOS) let indicatorStyle = UIActivityIndicatorViewStyle.white #else let indicatorStyle = UIActivityIndicatorViewStyle.gray #endif activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } } // MARK: - ImageIndicator // Displays an ImageView. Supports gif struct ImageIndicator: Indicator { private let animatedImageIndicatorView: ImageView var view: IndicatorView { return animatedImageIndicatorView } init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) { var options = options // Use normal image view to show gif, so we need to preload all gif data. if !options.preloadAllGIFData { options.append(.preloadAllGIFData) } guard let image = processor.process(item: .data(data), options: options) else { return nil } animatedImageIndicatorView = ImageView() animatedImageIndicatorView.image = image #if os(macOS) // Need for gif to animate on macOS self.animatedImageIndicatorView.imageScaling = .scaleNone self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true #else animatedImageIndicatorView.contentMode = .center animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } func startAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = true #else animatedImageIndicatorView.startAnimating() #endif animatedImageIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = false #else animatedImageIndicatorView.stopAnimating() #endif animatedImageIndicatorView.isHidden = true } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Kingfisher.h ================================================ // // Kingfisher.h // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import //! Project version number for Kingfisher. FOUNDATION_EXPORT double KingfisherVersionNumber; //! Project version string for Kingfisher. FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Kingfisher.swift ================================================ // // Kingfisher.swift // Kingfisher // // Created by Wei Wang on 16/9/14. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import ImageIO #if os(macOS) import AppKit public typealias Image = NSImage public typealias Color = NSColor public typealias ImageView = NSImageView typealias Button = NSButton #else import UIKit public typealias Image = UIImage public typealias Color = UIColor #if !os(watchOS) public typealias ImageView = UIImageView typealias Button = UIButton #endif #endif public final class Kingfisher { public let base: Base public init(_ base: Base) { self.base = base } } /** A type that has Kingfisher extensions. */ public protocol KingfisherCompatible { associatedtype CompatibleType var kf: CompatibleType { get } } public extension KingfisherCompatible { public var kf: Kingfisher { get { return Kingfisher(self) } } } extension Image: KingfisherCompatible { } #if !os(watchOS) extension ImageView: KingfisherCompatible { } extension Button: KingfisherCompatible { } #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/KingfisherManager.swift ================================================ // // KingfisherManager.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> ()) public typealias CompletionHandler = ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> ()) /// RetrieveImageTask represents a task of image retrieving process. /// It contains an async task of getting image from disk and from network. public class RetrieveImageTask { public static let empty = RetrieveImageTask() // If task is canceled before the download task started (which means the `downloadTask` is nil), // the download task should not begin. var cancelledBeforeDownloadStarting: Bool = false /// The disk retrieve task in this image task. Kingfisher will try to look up in cache first. This task represent the cache search task. @available(*, deprecated, message: "diskRetrieveTask is not in use anymore. You cannot cancel a disk retrieve task anymore once it started.") public var diskRetrieveTask: RetrieveImageDiskTask? /// The network retrieve task in this image task. public var downloadTask: RetrieveImageDownloadTask? /** Cancel current task. If this task is already done, do nothing. */ public func cancel() { if let downloadTask = downloadTask { downloadTask.cancel() } else { cancelledBeforeDownloadStarting = true } } } /// Error domain of Kingfisher public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error" /// Main manager class of Kingfisher. It connects Kingfisher downloader and cache. /// You can use this class to retrieve an image via a specified URL from web or cache. public class KingfisherManager { /// Shared manager used by the extensions across Kingfisher. public static let shared = KingfisherManager() /// Cache used by this manager public var cache: ImageCache /// Downloader used by this manager public var downloader: ImageDownloader convenience init() { self.init(downloader: .default, cache: .default) } init(downloader: ImageDownloader, cache: ImageCache) { self.downloader = downloader self.cache = cache } /** Get an image with resource. If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first. If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`. These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called every time downloaded data changed. This could be used as a progress UI. - parameter completionHandler: Called when the whole retrieving process finished. - returns: A `RetrieveImageTask` task object. You can use this object to cancel the task. */ @discardableResult public func retrieveImage(with resource: Resource, options: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let task = RetrieveImageTask() if let options = options, options.forceRefresh { _ = downloadAndCacheImage( with: resource.downloadURL, forKey: resource.cacheKey, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options) } else { tryToRetrieveImageFromCache( forKey: resource.cacheKey, with: resource.downloadURL, retrieveImageTask: task, progressBlock: progressBlock, completionHandler: completionHandler, options: options) } return task } @discardableResult func downloadAndCacheImage(with url: URL, forKey key: String, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: KingfisherOptionsInfo?) -> RetrieveImageDownloadTask? { let options = options ?? KingfisherEmptyOptionsInfo let downloader = options.downloader return downloader.downloadImage(with: url, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { receivedSize, totalSize in progressBlock?(receivedSize, totalSize) }, completionHandler: { image, error, imageURL, originalData in let targetCache = options.targetCache if let error = error, error.code == KingfisherError.notModified.rawValue { // Not modified. Try to find the image from cache. // (The image should be in cache. It should be guaranteed by the framework users.) targetCache.retrieveImage(forKey: key, options: options, completionHandler: { (cacheImage, cacheType) -> () in completionHandler?(cacheImage, nil, cacheType, url) }) return } if let image = image, let originalData = originalData { targetCache.store(image, original: originalData, forKey: key, processorIdentifier:options.processor.identifier, cacheSerializer: options.cacheSerializer, toDisk: !options.cacheMemoryOnly, completionHandler: nil) } completionHandler?(image, error, .none, url) }) } func tryToRetrieveImageFromCache(forKey key: String, with url: URL, retrieveImageTask: RetrieveImageTask, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?, options: KingfisherOptionsInfo?) { let diskTaskCompletionHandler: CompletionHandler = { (image, error, cacheType, imageURL) -> () in completionHandler?(image, error, cacheType, imageURL) } let targetCache = options?.targetCache ?? cache targetCache.retrieveImage(forKey: key, options: options, completionHandler: { image, cacheType in if image != nil { diskTaskCompletionHandler(image, nil, cacheType, url) } else if let options = options, options.onlyFromCache { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notCached.rawValue, userInfo: nil) diskTaskCompletionHandler(nil, error, .none, url) } else { self.downloadAndCacheImage( with: url, forKey: key, retrieveImageTask: retrieveImageTask, progressBlock: progressBlock, completionHandler: diskTaskCompletionHandler, options: options) } } ) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift ================================================ // // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /** * KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher. */ public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]() /** Items could be added into KingfisherOptionsInfo. */ public enum KingfisherOptionsInfoItem { /// The associated value of this member should be an ImageCache object. Kingfisher will use the specified /// cache object when handling related operations, including trying to retrieve the cached images and store /// the downloaded image to it. case targetCache(ImageCache) /// The associated value of this member should be an ImageDownloader object. Kingfisher will use this /// downloader to download the images. case downloader(ImageDownloader) /// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `ForceTransition` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used. case downloadPriority(Float) /// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `Transition` option for more. case forceTransition /// If set, `Kingfisher` will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, `Kingfisher` will only try to retrieve the image from cache not from network. case onlyFromCache /// Decode the image in background thread before using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks. case callbackDispatchQueue(DispatchQueue?) /// The associated value of this member will be used as the scale factor when converting retrieved data to an image. /// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing /// with 2x or 3x retina images. case scaleFactor(CGFloat) /// Whether all the GIF data should be preloaded. Default it false, which means following frames will be /// loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly /// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload /// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use /// corresponding image view type instead of setting this option. case preloadAllGIFData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the request. You can modify the request for some customizing purpose, /// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request /// will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using /// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the /// image view. `DefaultImageProcessor.default` will be used by default. case processor(ImageProcessor) /// Supply an `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// `DefaultCacheSerializer.default` will be used by default. case cacheSerializer(CacheSerializer) /// Keep the existing image while setting another image to an image view. /// By setting this option, the placeholder image parameter of imageview extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from a GIF file as a single image. /// Loading a lot of GIFs may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a GIF image. /// This option will be ignored if the target image is not GIF. case onlyLoadFirstFrame } precedencegroup ItemComparisonPrecedence { associativity: none higherThan: LogicalConjunctionPrecedence } infix operator <== : ItemComparisonPrecedence // This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values. func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool { switch (lhs, rhs) { case (.targetCache(_), .targetCache(_)): return true case (.downloader(_), .downloader(_)): return true case (.transition(_), .transition(_)): return true case (.downloadPriority(_), .downloadPriority(_)): return true case (.forceRefresh, .forceRefresh): return true case (.forceTransition, .forceTransition): return true case (.cacheMemoryOnly, .cacheMemoryOnly): return true case (.onlyFromCache, .onlyFromCache): return true case (.backgroundDecode, .backgroundDecode): return true case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true case (.scaleFactor(_), .scaleFactor(_)): return true case (.preloadAllGIFData, .preloadAllGIFData): return true case (.requestModifier(_), .requestModifier(_)): return true case (.processor(_), .processor(_)): return true case (.cacheSerializer(_), .cacheSerializer(_)): return true case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true default: return false } } extension Collection where Iterator.Element == KingfisherOptionsInfoItem { func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? { return index { $0 <== target }.flatMap { self[$0] } } func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] { return self.filter { !($0 <== target) } } } public extension Collection where Iterator.Element == KingfisherOptionsInfoItem { /// The target `ImageCache` which is used. public var targetCache: ImageCache { if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)), case .targetCache(let cache) = item { return cache } return ImageCache.default } /// The `ImageDownloader` which is specified. public var downloader: ImageDownloader { if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)), case .downloader(let downloader) = item { return downloader } return ImageDownloader.default } /// Member for animation transition when using UIImageView. public var transition: ImageTransition { if let item = firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = item { return transition } return ImageTransition.none } /// A `Float` value set as the priority of image download task. The value for it should be /// between 0.0~1.0. public var downloadPriority: Float { if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)), case .downloadPriority(let priority) = item { return priority } return URLSessionTask.defaultPriority } /// Whether an image will be always downloaded again or not. public var forceRefresh: Bool { return contains{ $0 <== .forceRefresh } } /// Whether the transition should always happen or not. public var forceTransition: Bool { return contains{ $0 <== .forceTransition } } /// Whether cache the image only in memory or not. public var cacheMemoryOnly: Bool { return contains{ $0 <== .cacheMemoryOnly } } /// Whether only load the images from cache or not. public var onlyFromCache: Bool { return contains{ $0 <== .onlyFromCache } } /// Whether the image should be decoded in background or not. public var backgroundDecode: Bool { return contains{ $0 <== .backgroundDecode } } /// Whether the image data should be all loaded at once if it is a GIF. public var preloadAllGIFData: Bool { return contains { $0 <== .preloadAllGIFData } } /// The queue of callbacks should happen from Kingfisher. public var callbackDispatchQueue: DispatchQueue { if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)), case .callbackDispatchQueue(let queue) = item { return queue ?? DispatchQueue.main } return DispatchQueue.main } /// The scale factor which should be used for the image. public var scaleFactor: CGFloat { if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)), case .scaleFactor(let scale) = item { return scale } return 1.0 } /// The `ImageDownloadRequestModifier` will be used before sending a download request. public var modifier: ImageDownloadRequestModifier { if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)), case .requestModifier(let modifier) = item { return modifier } return NoModifier.default } /// `ImageProcessor` for processing when the downloading finishes. public var processor: ImageProcessor { if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)), case .processor(let processor) = item { return processor } return DefaultImageProcessor.default } /// `CacheSerializer` to convert image to data for storing in cache. public var cacheSerializer: CacheSerializer { if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)), case .cacheSerializer(let cacheSerializer) = item { return cacheSerializer } return DefaultCacheSerializer.default } /// Keep the existing image while setting another image to an image view. /// Or the placeholder will be used while downloading. public var keepCurrentImageWhileLoading: Bool { return contains { $0 <== .keepCurrentImageWhileLoading } } public var onlyLoadFirstFrame: Bool { return contains { $0 <== .onlyLoadFirstFrame } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/RequestModifier.swift ================================================ // // RequestModifier.swift // Kingfisher // // Created by Wei Wang on 2016/09/05. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Request modifier of image downloader. public protocol ImageDownloadRequestModifier { func modified(for request: URLRequest) -> URLRequest? } struct NoModifier: ImageDownloadRequestModifier { static let `default` = NoModifier() private init() {} func modified(for request: URLRequest) -> URLRequest? { return request } } public struct AnyModifier: ImageDownloadRequestModifier { let block: (URLRequest) -> URLRequest? public func modified(for request: URLRequest) -> URLRequest? { return block(request) } public init(modify: @escaping (URLRequest) -> URLRequest? ) { block = modify } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/Resource.swift ================================================ // // Resource.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// `Resource` protocol defines how to download and cache a resource from network. public protocol Resource { /// The key used in cache. var cacheKey: String { get } /// The target image URL. var downloadURL: URL { get } } /** ImageResource is a simple combination of `downloadURL` and `cacheKey`. When passed to image view set methods, Kingfisher will try to download the target image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache. */ public struct ImageResource: Resource { /// The key used in cache. public let cacheKey: String /// The target image URL. public let downloadURL: URL /** Create a resource. - parameter downloadURL: The target image URL. - parameter cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key. - returns: A resource. */ public init(downloadURL: URL, cacheKey: String? = nil) { self.downloadURL = downloadURL self.cacheKey = cacheKey ?? downloadURL.absoluteString } } /** URL conforms to `Resource` in Kingfisher. The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`. If you need customize the url and/or cache key, use `ImageResource` instead. */ extension URL: Resource { public var cacheKey: String { return absoluteString } public var downloadURL: URL { return self } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/String+MD5.swift ================================================ // // String+MD5.swift // Kingfisher // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset and modified version of CryptoSwift as an alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation public struct StringProxy { fileprivate let base: String init(proxy: String) { base = proxy } } extension String: KingfisherCompatible { public typealias CompatibleType = StringProxy public var kf: CompatibleType { return StringProxy(proxy: self) } } extension StringProxy { var md5: String { if let data = base.data(using: .utf8, allowLossyConversion: true) { let message = data.withUnsafeBytes { bytes -> [UInt8] in return Array(UnsafeBufferPointer(start: bytes, count: data.count)) } let MD5Calculator = MD5(message) let MD5Data = MD5Calculator.calculate() let MD5String = NSMutableString() for c in MD5Data { MD5String.appendFormat("%02x", c) } return MD5String as String } else { return base } } } /** array of bytes, little-endian representation */ func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout.size * 8) let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) valuePointer.pointee = value let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0...size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } return bytes } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(_ arrayOfBytes: [UInt8]) { append(arrayOfBytes, length: arrayOfBytes.count) } } protocol HashProtocol { var message: Array { get } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len: Int) -> Array } extension HashProtocol { func prepare(_ len: Int) -> Array { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array(repeating: 0, count: counter) return tmpMessage } } func toUInt32Array(_ slice: ArraySlice) -> Array { var result = Array() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout.size) { let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 let d3 = UInt32(slice[idx]) let val: UInt32 = d0 | d1 | d2 | d3 result.append(val) } return result } struct BytesIterator: IteratorProtocol { let chunkSize: Int let data: [UInt8] init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } var offset = 0 mutating func next() -> ArraySlice? { let end = min(chunkSize, data.count - offset) let result = data[offset.. 0 ? result : nil } } struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] func makeIterator() -> BytesIterator { return BytesIterator(chunkSize: chunkSize, data: data) } } func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5: HashProtocol { static let size = 16 // 128 / 8 let message: [UInt8] init (_ message: [UInt8]) { self.message = message } /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> [UInt8] { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // hash values var hh = hashes // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reversed() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian let r1 = UInt8(itemLE & 0xff) let r2 = UInt8((itemLE >> 8) & 0xff) let r3 = UInt8((itemLE >> 16) & 0xff) let r4 = UInt8((itemLE >> 24) & 0xff) result += [r1, r2, r3, r4] } return result } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/ThreadHelper.swift ================================================ // // ThreadHelper.swift // Kingfisher // // Created by Wei Wang on 15/10/9. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension DispatchQueue { // This method will dispatch the `block` to self. // If `self` is the main queue, and current thread is main thread, the block // will be invoked immediately instead of being dispatched. func safeAsync(_ block: @escaping ()->()) { if self === DispatchQueue.main && Thread.isMainThread { block() } else { async { block() } } } } ================================================ FILE: iOS/User/ezshopUser/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift ================================================ // // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2017 Wei Wang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: - Set Images /** * Set image to use in button from web for a specified state. */ extension Kingfisher where Base: UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setImage(placeholder, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } setWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL(for: state) else { return } self.setImageTask(nil) if image != nil { strongBase.setImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelImageDownloadTask() { imageTask?.cancel() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setBackgroundImage(placeholder, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = options ?? KingfisherEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } setBackgroundWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.backgroundWebURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: { [weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else { return } self.setBackgroundImageTask(nil) if image != nil { strongBase.setBackgroundImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setBackgroundImageTask(task) return task } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ public func webURL(for state: UIControlState) -> URL? { return webURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setWebURL(_ url: URL, for state: UIControlState) { webURLs[NSNumber(value:state.rawValue)] = url } fileprivate var webURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setWebURLs(dictionary!) } return dictionary! } fileprivate func setWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var lastBackgroundURLKey: Void? private var backgroundImageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ public func backgroundWebURL(for state: UIControlState) -> URL? { return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setBackgroundWebURL(_ url: URL, for state: UIControlState) { backgroundWebURLs[NSNumber(value:state.rawValue)] = url } fileprivate var backgroundWebURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setBackgroundWebURLs(dictionary!) } return dictionary! } fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var backgroundImageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask } fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web for a specified state. Deprecated. Use `kf` namespacing instead. */ extension UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setImage` instead.", renamed: "kf.setImage") public func kf_setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", renamed: "kf.cancelImageDownloadTask") public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setBackgroundImage` instead.", renamed: "kf.setBackgroundImage") public func kf_setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelBackgroundImageDownloadTask` instead.", renamed: "kf.cancelBackgroundImageDownloadTask") public func kf_cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() } /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.webURL` instead.", renamed: "kf.webURL") public func kf_webURL(for state: UIControlState) -> URL? { return kf.webURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL, for state: UIControlState) { kf.setWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.webURLs") fileprivate var kf_webURLs: NSMutableDictionary { return kf.webURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURLs") fileprivate func kf_setWebURLs(_ URLs: NSMutableDictionary) { kf.setWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.backgroundWebURL` instead.", renamed: "kf.backgroundWebURL") public func kf_backgroundWebURL(for state: UIControlState) -> URL? { return kf.backgroundWebURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURL") fileprivate func kf_setBackgroundWebURL(_ url: URL, for state: UIControlState) { kf.setBackgroundWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundWebURLs") fileprivate var kf_backgroundWebURLs: NSMutableDictionary { return kf.backgroundWebURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURLs") fileprivate func kf_setBackgroundWebURLs(_ URLs: NSMutableDictionary) { kf.setBackgroundWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundImageTask") fileprivate var kf_backgroundImageTask: RetrieveImageTask? { return kf.backgroundImageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundImageTask") fileprivate func kf_setBackgroundImageTask(_ task: RetrieveImageTask?) { return kf.setBackgroundImageTask(task) } } ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 00E8E6EA851CA7C56F18EF3FB88995C8 /* Type.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 61399E0E4922FA39AFB05E4DB44409A6 /* Type.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 0B68193A407CAF9775F65787B3357266 /* SourceContext.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B3EFA614851F8D2D39514F535FF6DF2 /* SourceContext.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 0E9CC28AC8E34FE8E1C87E933E04BC7A /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37D686F38E816CC415B2E75E0C413C0C /* ImageProcessor.swift */; }; 0FF8F27F896850DB2973C4E26EC1F7EE /* GTMLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 376EFE700189AC33EF1EA0ED4A96D0DD /* GTMLogger.h */; settings = {ATTRIBUTES = (Public, ); }; }; 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD8F6DC1115CB144FF92AB6EAAF28F71 /* Timeline.swift */; }; 111F6A0D947700AC302CC02AE240F5A9 /* Empty.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = A7CB0B1DB7D26F408CAC488ABDACDD36 /* Empty.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 179523942E7D1E3EB210EF05E2C7AE79 /* Kingfisher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F88FD47527B6B1FD98BD48BF2C8C24F /* Kingfisher.h */; settings = {ATTRIBUTES = (Public, ); }; }; 17C46464C5B0BA51B9C6DD71636EAB0D /* Duration.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = E5AE67002B81E12762E4FD8531EBD904 /* Duration.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D20F91D5BAFBD5486CACD60D66BB8494 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 20FFCB796689940613A141013D758B10 /* SwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0AC90461C675619A8EDBA7D47F06131C /* SwiftyJSON-dummy.m */; }; 224F0B7749932D29C10252DE7AA897FF /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; 23B0DBDBE851016D8C15546F4DC260E2 /* GPBRuntimeTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = D4AFECCCD1BB9E1D39EE664F889B27EE /* GPBRuntimeTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; 26CDCF6645185C520134E1320B9147E6 /* Api.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = C1637B52DA9F9822EF99E453372174D2 /* Api.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 27BB7A8E478121DC29F5CE34A71E4DC3 /* FieldMask.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 1C3275E775A0E51BA71C6F504A75EAC5 /* FieldMask.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2B2882EDBFFB475408DD1C3F732C3003 /* GPBCodedInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 97C3723D6E7B60CC996C1E6C77420298 /* GPBCodedInputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; 2D7702EDC73F54AD4C21555F63212F8E /* GPBWellKnownTypes.m in Sources */ = {isa = PBXBuildFile; fileRef = 5A12BB87FFB15F38B8157D22062AEFA8 /* GPBWellKnownTypes.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 2E5E570FFC49EF98550401421A243C0F /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F70907D59C28A561718AB74E9869015 /* CacheSerializer.swift */; }; 31F6C6283ABB7B2A7A4840A82B9C5EEA /* Pods-ezshopUser-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = EB8E9341FBA1A36B81A706F7CB73BC2D /* Pods-ezshopUser-dummy.m */; }; 323DA451C68C598E0292CD89A30C064B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; 33395912F2FFA355C4C36B7EDEAA3DA7 /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 015E884095ABEA9EED1A37D11863CF3C /* ImageView+Kingfisher.swift */; }; 33A14E817C0FA585D5DA3A55E453299D /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE8F49ABF4D9A6F33B02DF6899B3145D /* Image.swift */; }; 3410282527236BAE6C77E760206A2860 /* GPBMessage_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = E0DFF23FA7BE9E6B2895EB02D9BECE5B /* GPBMessage_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; 3414E1D9CB15149A296E16C45967B021 /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F35D386A8371B862446ADC3DDC9D6FF /* ImagePrefetcher.swift */; }; 342AE33215135AD56B73580012DC22AB /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C844058A839BBD30AEBB9F89E6F5DC8 /* AnimatedImageView.swift */; }; 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB8B4236B1B9D5F60E68971568825241 /* TaskDelegate.swift */; }; 378409D4B120DB191348A8B0C9B61F88 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; 378B44CAA91C2106076668FDE72E1E02 /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21402C2B37A0133143EA232F3C53B300 /* KingfisherOptionsInfo.swift */; }; 3A85B73C819D7077CC2A2A37BA95CB87 /* GPBWireFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = 2228AAD69DCAB7D0957FBC4384855A87 /* GPBWireFormat.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 3B967DF26BEF9DC06380CF94487CC694 /* GPBExtensionInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = 6C8BC28DEB1A8D9445493937CFD90696 /* GPBExtensionInternals.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 3E3B4CF239527A39CD308EBA9676FD8F /* GTMDefines.h in Headers */ = {isa = PBXBuildFile; fileRef = E9315BB455F8D4C316FFC5ED322BAA48 /* GTMDefines.h */; settings = {ATTRIBUTES = (Public, ); }; }; 3FC2DEED5FBD8B67ECB0CD4EC1D38954 /* Empty.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 65E9DC7A7149403C5FB3CD7F43EB9CD3 /* Empty.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 4089E39F76F86466B8DDD39A1C1ABB6B /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC37DCFDC0C97496BC8D398BFC62FB6B /* Filter.swift */; }; 453AFD82272E1ABF8A688622A527C8C1 /* GPBMessage.m in Sources */ = {isa = PBXBuildFile; fileRef = 0A8045B466C02A11EC535FEA5D499969 /* GPBMessage.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 4A8B2322D0DF6C4A2AB5EADED4281BC2 /* GPBMessage.h in Headers */ = {isa = PBXBuildFile; fileRef = AD1FD04F39E4B8D6F3C507A7D400971A /* GPBMessage.h */; settings = {ATTRIBUTES = (Public, ); }; }; 4C6E09361DDBF58B631DD4848A4F17BA /* Timestamp.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 12F79A2491EC1052229C66AF62DCBB41 /* Timestamp.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 4CC855EE8E2A3D5B8B61865B34F028EA /* GPBArray.m in Sources */ = {isa = PBXBuildFile; fileRef = 9C3429D5F9C6935BC41ED6357D9EBAB2 /* GPBArray.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 4E59744DDACFECB37D3531E504228AA1 /* AlamofireSwiftyJSON-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = E58F047CCD125933FEEA820C88B43CDF /* AlamofireSwiftyJSON-dummy.m */; }; 4EC5C27621EB68BF8E77415F7FC1CF80 /* GPBDictionary.m in Sources */ = {isa = PBXBuildFile; fileRef = D8F525FFBF0F3C8F35A2A24072AE3F1E /* GPBDictionary.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 5068EA401BAAC807CB5699005DEF8E03 /* SwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 34923E8B7E5B2514F5F29B7B9E625EB9 /* SwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 52A280AB4852FDE92DF09B5E79D5C2AA /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C428BEE819C0B2E1253E729F5F60893 /* Indicator.swift */; }; 52B675FC8950B51FC33300A1ECD5F275 /* GPBDictionary_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B043E1D8A0434AE5EFE708444D795C7 /* GPBDictionary_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5338F8282895A05C3A35A3AA1D243716 /* Protobuf-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E8D57DC48A636A589C8E82329849BF14 /* Protobuf-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0017EE26E403D8D5F57C9A12A52407C8 /* Request.swift */; }; 554E50D6FB68B117CBFD447233C60EBE /* GPBRootObject_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = F633F2162DFB17DBA6CAE4A7BC8106F5 /* GPBRootObject_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5553EC47014ED2AE8BB342FF926C272F /* GPBUtilities_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 6E1422A205CCC6C2A68F3BCDC65A2681 /* GPBUtilities_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; 59BE44195191D46A245AAB3F8B5BA4A4 /* AlamofireSwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 023357B17131C50242F505F95416C2E0 /* AlamofireSwiftyJSON.swift */; }; 5CDAF5ECEE4EFE5F52E8825C007671EA /* GPBBootstrap.h in Headers */ = {isa = PBXBuildFile; fileRef = F7FB132539A7FA180E8AEA864C4C281D /* GPBBootstrap.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5F577A91C5A251FB08C01DB9FF8FFED4 /* GPBProtocolBuffers_RuntimeSupport.h in Headers */ = {isa = PBXBuildFile; fileRef = B3DCE1AFAC5A620684FCBD064A8DEF43 /* GPBProtocolBuffers_RuntimeSupport.h */; settings = {ATTRIBUTES = (Public, ); }; }; 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C71F9CBF999BBC827CCA1BAEC26C753 /* DispatchQueue+Alamofire.swift */; }; 6170BF4DE14D79BF6D97BF558911DEB3 /* Pods-ezshopUser-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 69FFF772582D154D8B1411854ECCB7F6 /* Pods-ezshopUser-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06A7ED339F0AD550AF7D3E627E95C93F /* ServerTrustPolicy.swift */; }; 6404C09FAB58402D628CAD8E433C8FE1 /* GPBDescriptor.m in Sources */ = {isa = PBXBuildFile; fileRef = 10F1B5479F8FA587D557FC49797800EC /* GPBDescriptor.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 64418457D16D9A2F28F496AC75FC7DBD /* GoogleToolboxForMac-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3508F0681A4023F6622C8AC9FADD27D7 /* GoogleToolboxForMac-dummy.m */; }; 6A375593407BC7937234B2B6A0811760 /* Kingfisher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 550EE5625D6BE69D1DAC99BD07DABB93 /* Kingfisher-dummy.m */; }; 6CD63E1564618B6213B98E0ABBC3127C /* ThreadHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC1BF5F2D25F2F3A30CE62E356EADDA7 /* ThreadHelper.swift */; }; 6D707BB31820B5F79A0B4AE74FE786FF /* Struct.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = D87B3C76A56E9DD3F45B0ABB0BA03D03 /* Struct.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6DA770087D354CDCD3889CDAE7C4C698 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98A1EFB7523BA19CC4A787D090C18C42 /* Box.swift */; }; 6DC7F9312F5A2D7036531D58527AC26F /* SwiftyJSON.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FEE0EC74C691AC5FE81E21053351EF33 /* SwiftyJSON.framework */; }; 6EA2232FA2BA69E7A974C24997CD5CEF /* Api.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 3BDA01C3BF4935E4D1CF57B5BE874C37 /* Api.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6EA5E49A3A0877A57949394E30CC8565 /* GPBCodedOutputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = AB8F4A25DE195A40D43899139AC28E11 /* GPBCodedOutputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; 755F55A7D577254B73EA7FEABA8E98E0 /* GTMNSData+zlib.h in Headers */ = {isa = PBXBuildFile; fileRef = 1370A8CD06F55CD39311C1D55A9AB0EC /* GTMNSData+zlib.h */; settings = {ATTRIBUTES = (Public, ); }; }; 75BD15665AE7C10FEC4F64CF9CDA2221 /* GPBUnknownFieldSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 388E90C7B8E020B09466C3A20CCF3D1F /* GPBUnknownFieldSet.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 75D5A69C61A68922B148CA71F0172E19 /* GPBWellKnownTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = BCBBB5C49100843EA7A2F4051A6A8868 /* GPBWellKnownTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; 7636F846675C9F4ED96E00C6C19A4890 /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC50FD950B40E66F948C91F67B79F052 /* KingfisherManager.swift */; }; 7685F73DC6AF03B4A47DDE9B5FC5AFCD /* GPBUnknownFieldSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 2399407BB6B32E11C2AB3C8E2ED57107 /* GPBUnknownFieldSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; 77C5A81B67F4C3A2890826E534AF53DD /* AlamofireSwiftyJSON-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8C7870986BB014C3DF72DB43101609BE /* AlamofireSwiftyJSON-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 79FE946262490B5FF43FEA8A3ECB51D9 /* SourceContext.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B6E55E81F578FA94A49A421048724BE /* SourceContext.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E918145C65843E6CAF5984FA7B3CF41 /* SessionDelegate.swift */; }; 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD113341C96346B25BDB79A7D73C6AF9 /* Result.swift */; }; 7FE7F76FB02A5027A6597578BD7D7D0F /* Any.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 7DC9C4A44B9F0F833EB3E08ACB7476BD /* Any.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 8526A013821844B0CD77FFF8C7EA7B34 /* GPBProtocolBuffers.h in Headers */ = {isa = PBXBuildFile; fileRef = 6287849BDEE4BA309FB7331612394E21 /* GPBProtocolBuffers.h */; settings = {ATTRIBUTES = (Public, ); }; }; 86B7DA678C8705523C300947117C0706 /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA5A7CC657402D18E3CA3CE9F983D5B2 /* ImageTransition.swift */; }; 87C5C03722DEBE6F410B3C5B6460FE3C /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F24296F49D19BE50D11888CFA850E9EF /* Alamofire.framework */; }; 87D4CADFC296262AF19DBE6F6D0188B4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; 8DA7E6883118CB3C8132B64D3D43AE0B /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = F95792901223019B294F94192BB0A545 /* Resource.swift */; }; 8FC05594728E7F30D90316E8945B5BFE /* GPBCodedInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 5525C5C27CD4068ACCDEBFFA6C97F3C0 /* GPBCodedInputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 9101CEA8562055177732244271008BBB /* GTMNSData+zlib.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A485F7C17155623DD79D981309762F1 /* GTMNSData+zlib.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; 92136C6584624998D5005F46C70A628B /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 90A1C8BDCA9E4C18B340062204EA9C4C /* CFNetwork.framework */; }; 95150D776F156226116B93DDBAD3B789 /* Protobuf-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3426E7B9996557B3C28A8EAE9D13B334 /* Protobuf-dummy.m */; }; 95398F0CC3450C855C578A06F298DF8D /* GPBExtensionRegistry.h in Headers */ = {isa = PBXBuildFile; fileRef = 03ACF216004FC21F8E55867AD5ED3386 /* GPBExtensionRegistry.h */; settings = {ATTRIBUTES = (Public, ); }; }; 9576DCFA6C5D93AA57F5D855A8AEE496 /* Duration.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = DF2598F6B11375B50341ED3423586795 /* Duration.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; 985CD33D98AD4F6311964B831D842612 /* Struct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 3F555682E5B64EC452CE24A7274FBE7C /* Struct.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 9C99E45B90BD95712D9878994BFC8B88 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82B26668D8AAE3B145611B17DBA167E8 /* AFError.swift */; }; 9F826F893E86EB86591B637A1CE4B13A /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA775BA2775D27D8A1EBB7D78DB02E6F /* String+MD5.swift */; }; A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E57E89B2D9C9E36F1AC9B97B01573EDF /* NetworkReachabilityManager.swift */; }; A4228F2845CE06BD24D5A863D6E45181 /* GPBWireFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = 8365C78E503339DDD330269D7EE945FB /* GPBWireFormat.h */; settings = {ATTRIBUTES = (Public, ); }; }; A4BA9026A393266E08D360A2B19D62B7 /* GPBUnknownField.m in Sources */ = {isa = PBXBuildFile; fileRef = 3445849ED1BC9E3E91DC1C7B79B240B2 /* GPBUnknownField.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; A55F6C23ECB45FC1C0D5B8A76908DDA0 /* GPBExtensionRegistry.m in Sources */ = {isa = PBXBuildFile; fileRef = D85DF1FABEC77A0DAFAA7036D75166D0 /* GPBExtensionRegistry.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; A5CE453D368326CCFE2ECA3034306EAA /* SwiftyJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = F76D1E452CE5C40A8BF8BFC488754336 /* SwiftyJSON.swift */; }; A7A7128944AD30A4C975CC707CAABA9E /* Wrappers.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 34124ADE309AF6601C988CEF79258B04 /* Wrappers.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; A8F35D1EBAEF99D38F02A0B8CA5D8FBE /* Kingfisher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7810A863313DCB62275204D0DD8057D3 /* Kingfisher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = DEE47E9A755AF7F5BC23047B06BB7803 /* Alamofire-dummy.m */; }; AB4F0970071E34D0384341466E0468EF /* GTMLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = C2D8C224B02C7AE77A00C5DF9AF1D02E /* GTMLogger.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; AC10566128ACA11212EA7DB956620226 /* GPBDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 3367D26B98255075507CCBE313DD2A80 /* GPBDictionary.h */; settings = {ATTRIBUTES = (Public, ); }; }; AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9214AC4B970DD95C124DAA0F299B7737 /* SessionManager.swift */; }; AF064D0F53E54165493C9DB282B8B374 /* Type.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F937A2E4B31957AD2175578718F135F7 /* Type.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = D83C9D62E6C76E35925E276E2F9E8EA2 /* MultipartFormData.swift */; }; BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8196F690597E27125ABCD8269935E3ED /* Validation.swift */; }; BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A12C1915E74E1191B53186485D1AA73 /* ParameterEncoding.swift */; }; C4752D0EFF8A8C803DA71E2445870710 /* Wrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = B5D691F7C0CC32DE14055D8A2B0D93EA /* Wrappers.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; C4D1E650D8529AFB35BCBD8C281294DF /* GPBArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 3532359B8B52B16BD9C7C687A1CD07AA /* GPBArray.h */; settings = {ATTRIBUTES = (Public, ); }; }; C8165AE5AC7E4B0016A2294FCD3E0AA2 /* GPBCodedOutputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 42CE5044006B1899F209D024ACAA6ACD /* GPBCodedOutputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; C8B9BC8AF83613F0AB1269209150B15C /* GPBExtensionInternals.h in Headers */ = {isa = PBXBuildFile; fileRef = 4AFE1C87768801F990AB7E6B1E81A04B /* GPBExtensionInternals.h */; settings = {ATTRIBUTES = (Public, ); }; }; C9CC5ED97D29C6C3DE22B78A9AA2AD91 /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D793932C0881AB718CB4A7EBD697FCA /* Kingfisher.swift */; }; CA7718794BD71A1C5A5E0820F76C3692 /* FieldMask.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = A8703C9BDADFF8EFA1268F98992CFFFB /* FieldMask.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA4F38320587D354C68987BEB930518F /* Response.swift */; }; D070E49D39268ECBE512026EC5CBF2A6 /* GPBRootObject.m in Sources */ = {isa = PBXBuildFile; fileRef = D233AE44039C91F17E38C0A7CC0264DC /* GPBRootObject.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; D08A54A24BBD582599244BB16024D7E3 /* GPBCodedInputStream_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = B01E408E931A162D54711F2D8C64C5C8 /* GPBCodedInputStream_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; D50931201EE99B301301F42393DF189B /* GPBDescriptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 2472056CDCC04B218F68A938DA0F3AE6 /* GPBDescriptor.h */; settings = {ATTRIBUTES = (Public, ); }; }; D80AB0EBA39A6EE0DF7CFAC7974698CA /* GPBUnknownFieldSet_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 85CAAE47903B984CCEF10C64FED57E29 /* GPBUnknownFieldSet_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC6080C64C269628C3F5107BE87055E2 /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D2A1351E4207F3AB5385D4FF20E2C53 /* ImageDownloader.swift */; }; DEAA3A9A9710B0567CA98E618C137608 /* GPBUnknownField.h in Headers */ = {isa = PBXBuildFile; fileRef = 8F939A9917A756519BB11774E9D7234E /* GPBUnknownField.h */; settings = {ATTRIBUTES = (Public, ); }; }; DF6D5769A321A040E12EE3C75C2C55D1 /* GPBUnknownField_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 7F537DC4231346EB9D6358636348BDAD /* GPBUnknownField_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; E2B615E1D93DCD721BAB1ACC50BA144E /* GPBRootObject.h in Headers */ = {isa = PBXBuildFile; fileRef = AA0E980AC9FF4578482D67C373AD6A2C /* GPBRootObject.h */; settings = {ATTRIBUTES = (Public, ); }; }; E37A508E9EDE338F47C8AD7F2DABB1AB /* GPBDescriptor_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 764CCF71C04B9D56B0A589A8B94697C1 /* GPBDescriptor_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; E4258CB32A838760B5803E7086724F0D /* GPBUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = F0E8C736B3E668F9A737147D133C0BE9 /* GPBUtilities.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; EA064ADB856A4CF4E6DD67787FF35D36 /* Any.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = 6744651C19700C0D4344482E8E1CB6EF /* Any.pbobjc.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; EA816A580C3858934ED6FE92040C26DD /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A9AA103C42618131066BBF82532F48 /* RequestModifier.swift */; }; ED66F8BD1D43065D931F2C8890806447 /* GoogleToolboxForMac-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AD9086AC3D8C1804078A700A89ADB6DB /* GoogleToolboxForMac-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; EE89512E8D36E67CDC525DB9D5BBF5A7 /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46A9AFC3851E2FA39D73B26A57C8CA75 /* UIButton+Kingfisher.swift */; }; EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A9449DA0F0D0C2028D7A4203E962185 /* Notifications.swift */; }; F0D9C922408F7EDE7FEA43079A43C867 /* Timestamp.pbobjc.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F8623CD7F77917BCB2E2474401E2D56 /* Timestamp.pbobjc.h */; settings = {ATTRIBUTES = (Public, ); }; }; F0DA3F38ECCA723EF832E2F746C7CFF0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */; }; F1679BFE4FF39E1909E87E5345515E3C /* GPBArray_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = 37DD052CABC84C78C1B2B7ABA9C8C576 /* GPBArray_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3723EAA3E2CED82A6F296E9D449B512F /* ResponseSerialization.swift */; }; F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75FCB10083216ED1E69476F1104850A7 /* Alamofire.swift */; }; F8E957950566622A3E4B61AACE8F0B4A /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FDA8F60E56D6CD0C29874DD73DC7E6E /* ImageCache.swift */; }; FC368C6D8E82D17BB8CB7956BB67B875 /* GPBCodedOutputStream_PackagePrivate.h in Headers */ = {isa = PBXBuildFile; fileRef = D498A80C334BDFFFC5968FD64ECBABB1 /* GPBCodedOutputStream_PackagePrivate.h */; settings = {ATTRIBUTES = (Public, ); }; }; FCBA7A5E42E0FAC55B37FA0B5B2F51C6 /* GPBUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = E11E039C349D10336D58A595E92E82BD /* GPBUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 2482E32FAEC37CB313F3C622BDC5643E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 61E5C1379DC63FAC57AF48F891CFB123; remoteInfo = AlamofireSwiftyJSON; }; 44499CB1CAC5DD785DF381C693D5AD65 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C4944FEC314D1A66588651D006273ADE; remoteInfo = Kingfisher; }; 50DFA62826566C291F52E77FE2979E38 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; 91FD6C13D7AFF34721D4FD73C6670538 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C68748E71A3DDB40B0AAF4BC0A8F9030; remoteInfo = SwiftyJSON; }; 9E39825F79A07D7716D92B12FE467B44 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 21811172B39AFCC0543A13D0C8851A3C; remoteInfo = Protobuf; }; 9FDAF5C6C834BA59530A0169BB8EB750 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = 88E9EC28B8B46C3631E6B242B50F4442; remoteInfo = Alamofire; }; E5EC3AE45F34BF5E9209817976A01A23 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C5B80060FE8C664DF08841000F41D515; remoteInfo = GoogleToolboxForMac; }; F6814470266156FFDECCFBF764C454DA /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; proxyType = 1; remoteGlobalIDString = C68748E71A3DDB40B0AAF4BC0A8F9030; remoteInfo = SwiftyJSON; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ 0017EE26E403D8D5F57C9A12A52407C8 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; 00B18B258C83F13D7E9A6BC2C470D918 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; 015E884095ABEA9EED1A37D11863CF3C /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ImageView+Kingfisher.swift"; path = "Sources/ImageView+Kingfisher.swift"; sourceTree = ""; }; 023357B17131C50242F505F95416C2E0 /* AlamofireSwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireSwiftyJSON.swift; path = Source/AlamofireSwiftyJSON.swift; sourceTree = ""; }; 03ACF216004FC21F8E55867AD5ED3386 /* GPBExtensionRegistry.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBExtensionRegistry.h; path = objectivec/GPBExtensionRegistry.h; sourceTree = ""; }; 06A7ED339F0AD550AF7D3E627E95C93F /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; 06C543665332C42D6BC9E2381EEBA966 /* Pods-ezshopUser.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ezshopUser.debug.xcconfig"; sourceTree = ""; }; 07D2BB4F514782F4380125C7F3B348A5 /* Pods-ezshopUser-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ezshopUser-frameworks.sh"; sourceTree = ""; }; 08022507F0AC050C0927D291E2695207 /* GoogleToolboxForMac.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GoogleToolboxForMac.framework; path = GoogleToolboxForMac.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 0A12C1915E74E1191B53186485D1AA73 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; 0A4E005A4CD207B854332863444D36C9 /* SwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftyJSON.xcconfig; sourceTree = ""; }; 0A8045B466C02A11EC535FEA5D499969 /* GPBMessage.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBMessage.m; path = objectivec/GPBMessage.m; sourceTree = ""; }; 0AC90461C675619A8EDBA7D47F06131C /* SwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftyJSON-dummy.m"; sourceTree = ""; }; 0D76ADD39984876AEAE8D5CE4946F7D2 /* Pods-ezshopUser.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-ezshopUser.modulemap"; sourceTree = ""; }; 0F70907D59C28A561718AB74E9869015 /* CacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CacheSerializer.swift; path = Sources/CacheSerializer.swift; sourceTree = ""; }; 10F1B5479F8FA587D557FC49797800EC /* GPBDescriptor.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBDescriptor.m; path = objectivec/GPBDescriptor.m; sourceTree = ""; }; 11CB7EB8D22A301400C0565A686824D7 /* Kingfisher.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.xcconfig; sourceTree = ""; }; 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 121DCC5ABFA4534BA03C49AD806C4788 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 12EE78E0A5094E8A289D185AC82C0CAA /* Pods-ezshopUser.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-ezshopUser.release.xcconfig"; sourceTree = ""; }; 12F79A2491EC1052229C66AF62DCBB41 /* Timestamp.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Timestamp.pbobjc.m; path = objectivec/google/protobuf/Timestamp.pbobjc.m; sourceTree = ""; }; 1370A8CD06F55CD39311C1D55A9AB0EC /* GTMNSData+zlib.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "GTMNSData+zlib.h"; path = "Foundation/GTMNSData+zlib.h"; sourceTree = ""; }; 1498AE1B7EF1B0ECE1719D09807F7B38 /* FirebaseDatabase.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseDatabase.framework; path = Frameworks/FirebaseDatabase.framework; sourceTree = ""; }; 1A485F7C17155623DD79D981309762F1 /* GTMNSData+zlib.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "GTMNSData+zlib.m"; path = "Foundation/GTMNSData+zlib.m"; sourceTree = ""; }; 1C3275E775A0E51BA71C6F504A75EAC5 /* FieldMask.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FieldMask.pbobjc.h; path = objectivec/google/protobuf/FieldMask.pbobjc.h; sourceTree = ""; }; 21402C2B37A0133143EA232F3C53B300 /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherOptionsInfo.swift; path = Sources/KingfisherOptionsInfo.swift; sourceTree = ""; }; 21616BB6570ECD53F1AEE82C6375E3DD /* AlamofireSwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = AlamofireSwiftyJSON.modulemap; sourceTree = ""; }; 2228AAD69DCAB7D0957FBC4384855A87 /* GPBWireFormat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBWireFormat.m; path = objectivec/GPBWireFormat.m; sourceTree = ""; }; 2399407BB6B32E11C2AB3C8E2ED57107 /* GPBUnknownFieldSet.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownFieldSet.h; path = objectivec/GPBUnknownFieldSet.h; sourceTree = ""; }; 2472056CDCC04B218F68A938DA0F3AE6 /* GPBDescriptor.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDescriptor.h; path = objectivec/GPBDescriptor.h; sourceTree = ""; }; 2AA988D13EC45E80138C7B60A34FDF47 /* Protobuf.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Protobuf.modulemap; sourceTree = ""; }; 2B48F4313F780926BFD002DD0BF0D583 /* Pods-ezshopUser-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-ezshopUser-acknowledgements.plist"; sourceTree = ""; }; 2F8623CD7F77917BCB2E2474401E2D56 /* Timestamp.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Timestamp.pbobjc.h; path = objectivec/google/protobuf/Timestamp.pbobjc.h; sourceTree = ""; }; 3367D26B98255075507CCBE313DD2A80 /* GPBDictionary.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDictionary.h; path = objectivec/GPBDictionary.h; sourceTree = ""; }; 33DE8518BF642766B1CB000C6F06FAE0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 34124ADE309AF6601C988CEF79258B04 /* Wrappers.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Wrappers.pbobjc.h; path = objectivec/google/protobuf/Wrappers.pbobjc.h; sourceTree = ""; }; 3426E7B9996557B3C28A8EAE9D13B334 /* Protobuf-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Protobuf-dummy.m"; sourceTree = ""; }; 3445849ED1BC9E3E91DC1C7B79B240B2 /* GPBUnknownField.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUnknownField.m; path = objectivec/GPBUnknownField.m; sourceTree = ""; }; 34923E8B7E5B2514F5F29B7B9E625EB9 /* SwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-umbrella.h"; sourceTree = ""; }; 3508F0681A4023F6622C8AC9FADD27D7 /* GoogleToolboxForMac-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GoogleToolboxForMac-dummy.m"; sourceTree = ""; }; 3532359B8B52B16BD9C7C687A1CD07AA /* GPBArray.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBArray.h; path = objectivec/GPBArray.h; sourceTree = ""; }; 3723EAA3E2CED82A6F296E9D449B512F /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; 376EFE700189AC33EF1EA0ED4A96D0DD /* GTMLogger.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMLogger.h; path = Foundation/GTMLogger.h; sourceTree = ""; }; 37D686F38E816CC415B2E75E0C413C0C /* ImageProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProcessor.swift; path = Sources/ImageProcessor.swift; sourceTree = ""; }; 37DD052CABC84C78C1B2B7ABA9C8C576 /* GPBArray_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBArray_PackagePrivate.h; path = objectivec/GPBArray_PackagePrivate.h; sourceTree = ""; }; 388E90C7B8E020B09466C3A20CCF3D1F /* GPBUnknownFieldSet.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUnknownFieldSet.m; path = objectivec/GPBUnknownFieldSet.m; sourceTree = ""; }; 3BDA01C3BF4935E4D1CF57B5BE874C37 /* Api.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Api.pbobjc.h; path = objectivec/google/protobuf/Api.pbobjc.h; sourceTree = ""; }; 3C428BEE819C0B2E1253E729F5F60893 /* Indicator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Indicator.swift; path = Sources/Indicator.swift; sourceTree = ""; }; 3F555682E5B64EC452CE24A7274FBE7C /* Struct.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Struct.pbobjc.m; path = objectivec/google/protobuf/Struct.pbobjc.m; sourceTree = ""; }; 42CE5044006B1899F209D024ACAA6ACD /* GPBCodedOutputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBCodedOutputStream.m; path = objectivec/GPBCodedOutputStream.m; sourceTree = ""; }; 46A9AFC3851E2FA39D73B26A57C8CA75 /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Kingfisher.swift"; path = "Sources/UIButton+Kingfisher.swift"; sourceTree = ""; }; 4AFE1C87768801F990AB7E6B1E81A04B /* GPBExtensionInternals.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBExtensionInternals.h; path = objectivec/GPBExtensionInternals.h; sourceTree = ""; }; 4B043E1D8A0434AE5EFE708444D795C7 /* GPBDictionary_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDictionary_PackagePrivate.h; path = objectivec/GPBDictionary_PackagePrivate.h; sourceTree = ""; }; 4EB6B376AFE2D2EFF28B2C5E0A90F8BE /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 4F88FD47527B6B1FD98BD48BF2C8C24F /* Kingfisher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Kingfisher.h; path = Sources/Kingfisher.h; sourceTree = ""; }; 5077695BC40022D436E6DF8AF145B561 /* Kingfisher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-prefix.pch"; sourceTree = ""; }; 5399A2C50A8469480F11298D2F271438 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftyJSON.framework; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 550EE5625D6BE69D1DAC99BD07DABB93 /* Kingfisher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kingfisher-dummy.m"; sourceTree = ""; }; 5525C5C27CD4068ACCDEBFFA6C97F3C0 /* GPBCodedInputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBCodedInputStream.m; path = objectivec/GPBCodedInputStream.m; sourceTree = ""; }; 573E083632F044348A22102F38B679D5 /* AlamofireSwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AlamofireSwiftyJSON.framework; path = AlamofireSwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5A12BB87FFB15F38B8157D22062AEFA8 /* GPBWellKnownTypes.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBWellKnownTypes.m; path = objectivec/GPBWellKnownTypes.m; sourceTree = ""; }; 5BCC748DC6D93D9EE46A21F6DFACA423 /* FirebaseAnalytics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseAnalytics.framework; path = Frameworks/FirebaseAnalytics.framework; sourceTree = ""; }; 5D2A1351E4207F3AB5385D4FF20E2C53 /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Sources/ImageDownloader.swift; sourceTree = ""; }; 5EAEDA0F58B0FF6DA1EEFFC7408BC333 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 5ECBEAA9F73830BAF6D19EC2581E3315 /* Kingfisher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Kingfisher.modulemap; sourceTree = ""; }; 5F35D386A8371B862446ADC3DDC9D6FF /* ImagePrefetcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/ImagePrefetcher.swift; sourceTree = ""; }; 61399E0E4922FA39AFB05E4DB44409A6 /* Type.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Type.pbobjc.h; path = objectivec/google/protobuf/Type.pbobjc.h; sourceTree = ""; }; 6287849BDEE4BA309FB7331612394E21 /* GPBProtocolBuffers.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBProtocolBuffers.h; path = objectivec/GPBProtocolBuffers.h; sourceTree = ""; }; 62BABF9DE94CE98833CF5DCCB812A522 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 654C0E3C5B26EAFAC0CFAC7AB58A157E /* FirebaseCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseCore.framework; path = Frameworks/FirebaseCore.framework; sourceTree = ""; }; 65E9DC7A7149403C5FB3CD7F43EB9CD3 /* Empty.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Empty.pbobjc.h; path = objectivec/google/protobuf/Empty.pbobjc.h; sourceTree = ""; }; 66F9A8399FF65AB025EFB7A4E00B9C8B /* Firebase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Firebase.h; path = Core/Sources/Firebase.h; sourceTree = ""; }; 6744651C19700C0D4344482E8E1CB6EF /* Any.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Any.pbobjc.m; path = objectivec/google/protobuf/Any.pbobjc.m; sourceTree = ""; }; 69FFF772582D154D8B1411854ECCB7F6 /* Pods-ezshopUser-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-ezshopUser-umbrella.h"; sourceTree = ""; }; 6A9449DA0F0D0C2028D7A4203E962185 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; 6B6E55E81F578FA94A49A421048724BE /* SourceContext.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SourceContext.pbobjc.m; path = objectivec/google/protobuf/SourceContext.pbobjc.m; sourceTree = ""; }; 6C662288D30F692E3ECC87280EAC8B74 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = Alamofire.modulemap; sourceTree = ""; }; 6C71F9CBF999BBC827CCA1BAEC26C753 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; 6C844058A839BBD30AEBB9F89E6F5DC8 /* AnimatedImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedImageView.swift; path = Sources/AnimatedImageView.swift; sourceTree = ""; }; 6C8BC28DEB1A8D9445493937CFD90696 /* GPBExtensionInternals.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionInternals.m; path = objectivec/GPBExtensionInternals.m; sourceTree = ""; }; 6E1422A205CCC6C2A68F3BCDC65A2681 /* GPBUtilities_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUtilities_PackagePrivate.h; path = objectivec/GPBUtilities_PackagePrivate.h; sourceTree = ""; }; 723F27C34C82F86747773C750671AA54 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 75FCB10083216ED1E69476F1104850A7 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; 764CCF71C04B9D56B0A589A8B94697C1 /* GPBDescriptor_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBDescriptor_PackagePrivate.h; path = objectivec/GPBDescriptor_PackagePrivate.h; sourceTree = ""; }; 7810A863313DCB62275204D0DD8057D3 /* Kingfisher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-umbrella.h"; sourceTree = ""; }; 79DC24E34C263CABF2FF777529E1DE58 /* SwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftyJSON-prefix.pch"; sourceTree = ""; }; 7C1D5CEFAB850ADB985585A6B3B87E37 /* Protobuf.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Protobuf.xcconfig; sourceTree = ""; }; 7DC9C4A44B9F0F833EB3E08ACB7476BD /* Any.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Any.pbobjc.h; path = objectivec/google/protobuf/Any.pbobjc.h; sourceTree = ""; }; 7E918145C65843E6CAF5984FA7B3CF41 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; 7F0A1946B8BBA4BD4D6512EA900BF123 /* Pods-ezshopUser-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-ezshopUser-acknowledgements.markdown"; sourceTree = ""; }; 7F537DC4231346EB9D6358636348BDAD /* GPBUnknownField_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownField_PackagePrivate.h; path = objectivec/GPBUnknownField_PackagePrivate.h; sourceTree = ""; }; 7FDA8F60E56D6CD0C29874DD73DC7E6E /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Sources/ImageCache.swift; sourceTree = ""; }; 8196F690597E27125ABCD8269935E3ED /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; 82B26668D8AAE3B145611B17DBA167E8 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; 8365C78E503339DDD330269D7EE945FB /* GPBWireFormat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBWireFormat.h; path = objectivec/GPBWireFormat.h; sourceTree = ""; }; 85CAAE47903B984CCEF10C64FED57E29 /* GPBUnknownFieldSet_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownFieldSet_PackagePrivate.h; path = objectivec/GPBUnknownFieldSet_PackagePrivate.h; sourceTree = ""; }; 8C7870986BB014C3DF72DB43101609BE /* AlamofireSwiftyJSON-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireSwiftyJSON-umbrella.h"; sourceTree = ""; }; 8D793932C0881AB718CB4A7EBD697FCA /* Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kingfisher.swift; path = Sources/Kingfisher.swift; sourceTree = ""; }; 8F939A9917A756519BB11774E9D7234E /* GPBUnknownField.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUnknownField.h; path = objectivec/GPBUnknownField.h; sourceTree = ""; }; 90A1C8BDCA9E4C18B340062204EA9C4C /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; 9214AC4B970DD95C124DAA0F299B7737 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 93AB09BF686888B9E929884B383F4ED0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 9620871F28E45DEC6C7576CBC95950DD /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 97C3723D6E7B60CC996C1E6C77420298 /* GPBCodedInputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedInputStream.h; path = objectivec/GPBCodedInputStream.h; sourceTree = ""; }; 98A1EFB7523BA19CC4A787D090C18C42 /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; 9B1C5A0E579735089019A48A48148837 /* Pods-ezshopUser-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-ezshopUser-resources.sh"; sourceTree = ""; }; 9B3EFA614851F8D2D39514F535FF6DF2 /* SourceContext.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SourceContext.pbobjc.h; path = objectivec/google/protobuf/SourceContext.pbobjc.h; sourceTree = ""; }; 9C3429D5F9C6935BC41ED6357D9EBAB2 /* GPBArray.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBArray.m; path = objectivec/GPBArray.m; sourceTree = ""; }; 9F64C5558790995FF9AE88D3346A38C9 /* FirebaseInstanceID.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseInstanceID.framework; path = Frameworks/FirebaseInstanceID.framework; sourceTree = ""; }; A4B7875FC0C760153172E16D121FFD01 /* GoogleToolboxForMac.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = GoogleToolboxForMac.modulemap; sourceTree = ""; }; A7CB0B1DB7D26F408CAC488ABDACDD36 /* Empty.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Empty.pbobjc.m; path = objectivec/google/protobuf/Empty.pbobjc.m; sourceTree = ""; }; A7EEA39742AFD80094F02DA1C58BCCB0 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; A862187FB05C586D038914229E373876 /* Kingfisher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kingfisher.framework; path = Kingfisher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A8703C9BDADFF8EFA1268F98992CFFFB /* FieldMask.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FieldMask.pbobjc.m; path = objectivec/google/protobuf/FieldMask.pbobjc.m; sourceTree = ""; }; AA0E980AC9FF4578482D67C373AD6A2C /* GPBRootObject.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRootObject.h; path = objectivec/GPBRootObject.h; sourceTree = ""; }; AA4F38320587D354C68987BEB930518F /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; AA5A7CC657402D18E3CA3CE9F983D5B2 /* ImageTransition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageTransition.swift; path = Sources/ImageTransition.swift; sourceTree = ""; }; AB8B4236B1B9D5F60E68971568825241 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; AB8F4A25DE195A40D43899139AC28E11 /* GPBCodedOutputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedOutputStream.h; path = objectivec/GPBCodedOutputStream.h; sourceTree = ""; }; AC1BF5F2D25F2F3A30CE62E356EADDA7 /* ThreadHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ThreadHelper.swift; path = Sources/ThreadHelper.swift; sourceTree = ""; }; AD1FD04F39E4B8D6F3C507A7D400971A /* GPBMessage.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBMessage.h; path = objectivec/GPBMessage.h; sourceTree = ""; }; AD9086AC3D8C1804078A700A89ADB6DB /* GoogleToolboxForMac-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleToolboxForMac-umbrella.h"; sourceTree = ""; }; B01E408E931A162D54711F2D8C64C5C8 /* GPBCodedInputStream_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedInputStream_PackagePrivate.h; path = objectivec/GPBCodedInputStream_PackagePrivate.h; sourceTree = ""; }; B3DCE1AFAC5A620684FCBD064A8DEF43 /* GPBProtocolBuffers_RuntimeSupport.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBProtocolBuffers_RuntimeSupport.h; path = objectivec/GPBProtocolBuffers_RuntimeSupport.h; sourceTree = ""; }; B5D691F7C0CC32DE14055D8A2B0D93EA /* Wrappers.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Wrappers.pbobjc.m; path = objectivec/google/protobuf/Wrappers.pbobjc.m; sourceTree = ""; }; BBB98BC9D1AD1772FA8C1A2E6B5CC788 /* Protobuf-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Protobuf-prefix.pch"; sourceTree = ""; }; BCBBB5C49100843EA7A2F4051A6A8868 /* GPBWellKnownTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBWellKnownTypes.h; path = objectivec/GPBWellKnownTypes.h; sourceTree = ""; }; C1637B52DA9F9822EF99E453372174D2 /* Api.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Api.pbobjc.m; path = objectivec/google/protobuf/Api.pbobjc.m; sourceTree = ""; }; C2D8C224B02C7AE77A00C5DF9AF1D02E /* GTMLogger.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMLogger.m; path = Foundation/GTMLogger.m; sourceTree = ""; }; CC50FD950B40E66F948C91F67B79F052 /* KingfisherManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherManager.swift; path = Sources/KingfisherManager.swift; sourceTree = ""; }; CD113341C96346B25BDB79A7D73C6AF9 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; CE8F49ABF4D9A6F33B02DF6899B3145D /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Image.swift; sourceTree = ""; }; CFA7355B23837E64869AE671870DA2AC /* FirebaseMessaging.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseMessaging.framework; path = Frameworks/FirebaseMessaging.framework; sourceTree = ""; }; D20F91D5BAFBD5486CACD60D66BB8494 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; D233AE44039C91F17E38C0A7CC0264DC /* GPBRootObject.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBRootObject.m; path = objectivec/GPBRootObject.m; sourceTree = ""; }; D3E2BFE6F7A38038FC55E382413559FF /* SwiftyJSON.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = SwiftyJSON.modulemap; sourceTree = ""; }; D498A80C334BDFFFC5968FD64ECBABB1 /* GPBCodedOutputStream_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBCodedOutputStream_PackagePrivate.h; path = objectivec/GPBCodedOutputStream_PackagePrivate.h; sourceTree = ""; }; D4AFECCCD1BB9E1D39EE664F889B27EE /* GPBRuntimeTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRuntimeTypes.h; path = objectivec/GPBRuntimeTypes.h; sourceTree = ""; }; D79D6024F9ABEBE0B74CC08913EBBEB7 /* AlamofireSwiftyJSON.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AlamofireSwiftyJSON.xcconfig; sourceTree = ""; }; D7F04EC09A08EF0FB13AF7E9B3D05B28 /* AlamofireSwiftyJSON-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AlamofireSwiftyJSON-prefix.pch"; sourceTree = ""; }; D83C9D62E6C76E35925E276E2F9E8EA2 /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; D85DF1FABEC77A0DAFAA7036D75166D0 /* GPBExtensionRegistry.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBExtensionRegistry.m; path = objectivec/GPBExtensionRegistry.m; sourceTree = ""; }; D87B3C76A56E9DD3F45B0ABB0BA03D03 /* Struct.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Struct.pbobjc.h; path = objectivec/google/protobuf/Struct.pbobjc.h; sourceTree = ""; }; D8F525FFBF0F3C8F35A2A24072AE3F1E /* GPBDictionary.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBDictionary.m; path = objectivec/GPBDictionary.m; sourceTree = ""; }; DA775BA2775D27D8A1EBB7D78DB02E6F /* String+MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+MD5.swift"; path = "Sources/String+MD5.swift"; sourceTree = ""; }; DEE47E9A755AF7F5BC23047B06BB7803 /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; DF2598F6B11375B50341ED3423586795 /* Duration.pbobjc.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Duration.pbobjc.h; path = objectivec/google/protobuf/Duration.pbobjc.h; sourceTree = ""; }; E0DFF23FA7BE9E6B2895EB02D9BECE5B /* GPBMessage_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBMessage_PackagePrivate.h; path = objectivec/GPBMessage_PackagePrivate.h; sourceTree = ""; }; E11E039C349D10336D58A595E92E82BD /* GPBUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBUtilities.h; path = objectivec/GPBUtilities.h; sourceTree = ""; }; E57E89B2D9C9E36F1AC9B97B01573EDF /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; E58F047CCD125933FEEA820C88B43CDF /* AlamofireSwiftyJSON-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AlamofireSwiftyJSON-dummy.m"; sourceTree = ""; }; E5AE67002B81E12762E4FD8531EBD904 /* Duration.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Duration.pbobjc.m; path = objectivec/google/protobuf/Duration.pbobjc.m; sourceTree = ""; }; E7CAF143AAC69661B4131A41BFE378D8 /* GoogleToolboxForMac.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GoogleToolboxForMac.xcconfig; sourceTree = ""; }; E8D57DC48A636A589C8E82329849BF14 /* Protobuf-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Protobuf-umbrella.h"; sourceTree = ""; }; E9315BB455F8D4C316FFC5ED322BAA48 /* GTMDefines.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = GTMDefines.h; sourceTree = ""; }; EB8E9341FBA1A36B81A706F7CB73BC2D /* Pods-ezshopUser-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-ezshopUser-dummy.m"; sourceTree = ""; }; EC37DCFDC0C97496BC8D398BFC62FB6B /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Filter.swift; sourceTree = ""; }; F0A9AA103C42618131066BBF82532F48 /* RequestModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestModifier.swift; path = Sources/RequestModifier.swift; sourceTree = ""; }; F0E8C736B3E668F9A737147D133C0BE9 /* GPBUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GPBUtilities.m; path = objectivec/GPBUtilities.m; sourceTree = ""; }; F24296F49D19BE50D11888CFA850E9EF /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F633F2162DFB17DBA6CAE4A7BC8106F5 /* GPBRootObject_PackagePrivate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBRootObject_PackagePrivate.h; path = objectivec/GPBRootObject_PackagePrivate.h; sourceTree = ""; }; F6A3BA44E6E8AF5A57F1D49F1C70D12D /* Protobuf.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Protobuf.framework; path = Protobuf.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F76D1E452CE5C40A8BF8BFC488754336 /* SwiftyJSON.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftyJSON.swift; path = Source/SwiftyJSON.swift; sourceTree = ""; }; F7FB132539A7FA180E8AEA864C4C281D /* GPBBootstrap.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GPBBootstrap.h; path = objectivec/GPBBootstrap.h; sourceTree = ""; }; F932C0158F5001C19F5782F8294A1990 /* GoogleToolboxForMac-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GoogleToolboxForMac-prefix.pch"; sourceTree = ""; }; F937A2E4B31957AD2175578718F135F7 /* Type.pbobjc.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = Type.pbobjc.m; path = objectivec/google/protobuf/Type.pbobjc.m; sourceTree = ""; }; F95792901223019B294F94192BB0A545 /* Resource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resource.swift; path = Sources/Resource.swift; sourceTree = ""; }; FD8F6DC1115CB144FF92AB6EAAF28F71 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; FEE0EC74C691AC5FE81E21053351EF33 /* SwiftyJSON.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SwiftyJSON.framework; sourceTree = BUILT_PRODUCTS_DIR; }; FFD5F74AF249D2DD8A551156CC19FA6E /* Pods_ezshopUser.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_ezshopUser.framework; path = "Pods-ezshopUser.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 229003D8AA2FC24D450F02A58E1EA5D2 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 87C5C03722DEBE6F410B3C5B6460FE3C /* Alamofire.framework in Frameworks */, F0DA3F38ECCA723EF832E2F746C7CFF0 /* Foundation.framework in Frameworks */, 6DC7F9312F5A2D7036531D58527AC26F /* SwiftyJSON.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 8DD06B625DFB302A853551293B0AB0B4 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 87D4CADFC296262AF19DBE6F6D0188B4 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 99195E4207764744AEC07ECCBCD550EB /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( A04BFC558D69E7DBB68023C80A9CFE4E /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; B0C55565E8D6390E0F647FD9E9BBE386 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 224F0B7749932D29C10252DE7AA897FF /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; C5FBD50589CE2C516975A62886A56E07 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 378409D4B120DB191348A8B0C9B61F88 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; C6E6051A4B0615B7833BD8C24136F64B /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 323DA451C68C598E0292CD89A30C064B /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; ED03E5917B811BACFE75189AE0C2A469 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 92136C6584624998D5005F46C70A628B /* CFNetwork.framework in Frameworks */, 9C99E45B90BD95712D9878994BFC8B88 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 19C1A044B7FB2ECA76817BD62BC9854F /* Support Files */ = { isa = PBXGroup; children = ( 9620871F28E45DEC6C7576CBC95950DD /* Info.plist */, D3E2BFE6F7A38038FC55E382413559FF /* SwiftyJSON.modulemap */, 0A4E005A4CD207B854332863444D36C9 /* SwiftyJSON.xcconfig */, 0AC90461C675619A8EDBA7D47F06131C /* SwiftyJSON-dummy.m */, 79DC24E34C263CABF2FF777529E1DE58 /* SwiftyJSON-prefix.pch */, 34923E8B7E5B2514F5F29B7B9E625EB9 /* SwiftyJSON-umbrella.h */, ); name = "Support Files"; path = "../Target Support Files/SwiftyJSON"; sourceTree = ""; }; 23D14ACD17D376D97752C60EE7CEBA54 /* Support Files */ = { isa = PBXGroup; children = ( 33DE8518BF642766B1CB000C6F06FAE0 /* Info.plist */, 5ECBEAA9F73830BAF6D19EC2581E3315 /* Kingfisher.modulemap */, 11CB7EB8D22A301400C0565A686824D7 /* Kingfisher.xcconfig */, 550EE5625D6BE69D1DAC99BD07DABB93 /* Kingfisher-dummy.m */, 5077695BC40022D436E6DF8AF145B561 /* Kingfisher-prefix.pch */, 7810A863313DCB62275204D0DD8057D3 /* Kingfisher-umbrella.h */, ); name = "Support Files"; path = "../Target Support Files/Kingfisher"; sourceTree = ""; }; 2D77C9ECA1F229B98B54BC4CB76A4346 /* Frameworks */ = { isa = PBXGroup; children = ( CFA7355B23837E64869AE671870DA2AC /* FirebaseMessaging.framework */, ); name = Frameworks; sourceTree = ""; }; 350E12F6D88A18D012BC213A82F78CEB /* Frameworks */ = { isa = PBXGroup; children = ( 654C0E3C5B26EAFAC0CFAC7AB58A157E /* FirebaseCore.framework */, ); name = Frameworks; sourceTree = ""; }; 3FD46E3A2501853B6A4CF71ECFB019E7 /* SwiftyJSON */ = { isa = PBXGroup; children = ( F76D1E452CE5C40A8BF8BFC488754336 /* SwiftyJSON.swift */, 19C1A044B7FB2ECA76817BD62BC9854F /* Support Files */, ); name = SwiftyJSON; path = SwiftyJSON; sourceTree = ""; }; 43BDFA65DB9390A8545A27466F4F849D /* iOS */ = { isa = PBXGroup; children = ( 90A1C8BDCA9E4C18B340062204EA9C4C /* CFNetwork.framework */, 11FF01D530FEB574D2273D26ECB68202 /* Foundation.framework */, ); name = iOS; sourceTree = ""; }; 4C6DB2B31394B2EE81A2D4091E39252C /* Frameworks */ = { isa = PBXGroup; children = ( F24296F49D19BE50D11888CFA850E9EF /* Alamofire.framework */, FEE0EC74C691AC5FE81E21053351EF33 /* SwiftyJSON.framework */, 43BDFA65DB9390A8545A27466F4F849D /* iOS */, ); name = Frameworks; sourceTree = ""; }; 5A22883C7BF42FFCA0F1EC4747BB2BD8 /* Support Files */ = { isa = PBXGroup; children = ( 93AB09BF686888B9E929884B383F4ED0 /* Info.plist */, 2AA988D13EC45E80138C7B60A34FDF47 /* Protobuf.modulemap */, 7C1D5CEFAB850ADB985585A6B3B87E37 /* Protobuf.xcconfig */, 3426E7B9996557B3C28A8EAE9D13B334 /* Protobuf-dummy.m */, BBB98BC9D1AD1772FA8C1A2E6B5CC788 /* Protobuf-prefix.pch */, E8D57DC48A636A589C8E82329849BF14 /* Protobuf-umbrella.h */, ); name = "Support Files"; path = "../Target Support Files/Protobuf"; sourceTree = ""; }; 5E2F44668A566A9194F297B6C52317F5 /* Support Files */ = { isa = PBXGroup; children = ( A4B7875FC0C760153172E16D121FFD01 /* GoogleToolboxForMac.modulemap */, E7CAF143AAC69661B4131A41BFE378D8 /* GoogleToolboxForMac.xcconfig */, 3508F0681A4023F6622C8AC9FADD27D7 /* GoogleToolboxForMac-dummy.m */, F932C0158F5001C19F5782F8294A1990 /* GoogleToolboxForMac-prefix.pch */, AD9086AC3D8C1804078A700A89ADB6DB /* GoogleToolboxForMac-umbrella.h */, 5EAEDA0F58B0FF6DA1EEFFC7408BC333 /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/GoogleToolboxForMac"; sourceTree = ""; }; 601A21DAA3246880967E1D647D86123D /* Logger */ = { isa = PBXGroup; children = ( 376EFE700189AC33EF1EA0ED4A96D0DD /* GTMLogger.h */, C2D8C224B02C7AE77A00C5DF9AF1D02E /* GTMLogger.m */, ); name = Logger; sourceTree = ""; }; 602DD0727BA743D7757549397D855188 /* FirebaseAnalytics */ = { isa = PBXGroup; children = ( BF085BBBCBF1A056D151824724FA0C29 /* Frameworks */, ); name = FirebaseAnalytics; path = FirebaseAnalytics; sourceTree = ""; }; 62D7E97AD3640F1CE4E35CD062C37558 /* Frameworks */ = { isa = PBXGroup; children = ( 1498AE1B7EF1B0ECE1719D09807F7B38 /* FirebaseDatabase.framework */, ); name = Frameworks; sourceTree = ""; }; 6B5F4DC53D9A6CA07B8DF26721808B04 /* Protobuf */ = { isa = PBXGroup; children = ( 7DC9C4A44B9F0F833EB3E08ACB7476BD /* Any.pbobjc.h */, 6744651C19700C0D4344482E8E1CB6EF /* Any.pbobjc.m */, 3BDA01C3BF4935E4D1CF57B5BE874C37 /* Api.pbobjc.h */, C1637B52DA9F9822EF99E453372174D2 /* Api.pbobjc.m */, DF2598F6B11375B50341ED3423586795 /* Duration.pbobjc.h */, E5AE67002B81E12762E4FD8531EBD904 /* Duration.pbobjc.m */, 65E9DC7A7149403C5FB3CD7F43EB9CD3 /* Empty.pbobjc.h */, A7CB0B1DB7D26F408CAC488ABDACDD36 /* Empty.pbobjc.m */, 1C3275E775A0E51BA71C6F504A75EAC5 /* FieldMask.pbobjc.h */, A8703C9BDADFF8EFA1268F98992CFFFB /* FieldMask.pbobjc.m */, 3532359B8B52B16BD9C7C687A1CD07AA /* GPBArray.h */, 9C3429D5F9C6935BC41ED6357D9EBAB2 /* GPBArray.m */, 37DD052CABC84C78C1B2B7ABA9C8C576 /* GPBArray_PackagePrivate.h */, F7FB132539A7FA180E8AEA864C4C281D /* GPBBootstrap.h */, 97C3723D6E7B60CC996C1E6C77420298 /* GPBCodedInputStream.h */, 5525C5C27CD4068ACCDEBFFA6C97F3C0 /* GPBCodedInputStream.m */, B01E408E931A162D54711F2D8C64C5C8 /* GPBCodedInputStream_PackagePrivate.h */, AB8F4A25DE195A40D43899139AC28E11 /* GPBCodedOutputStream.h */, 42CE5044006B1899F209D024ACAA6ACD /* GPBCodedOutputStream.m */, D498A80C334BDFFFC5968FD64ECBABB1 /* GPBCodedOutputStream_PackagePrivate.h */, 2472056CDCC04B218F68A938DA0F3AE6 /* GPBDescriptor.h */, 10F1B5479F8FA587D557FC49797800EC /* GPBDescriptor.m */, 764CCF71C04B9D56B0A589A8B94697C1 /* GPBDescriptor_PackagePrivate.h */, 3367D26B98255075507CCBE313DD2A80 /* GPBDictionary.h */, D8F525FFBF0F3C8F35A2A24072AE3F1E /* GPBDictionary.m */, 4B043E1D8A0434AE5EFE708444D795C7 /* GPBDictionary_PackagePrivate.h */, 4AFE1C87768801F990AB7E6B1E81A04B /* GPBExtensionInternals.h */, 6C8BC28DEB1A8D9445493937CFD90696 /* GPBExtensionInternals.m */, 03ACF216004FC21F8E55867AD5ED3386 /* GPBExtensionRegistry.h */, D85DF1FABEC77A0DAFAA7036D75166D0 /* GPBExtensionRegistry.m */, AD1FD04F39E4B8D6F3C507A7D400971A /* GPBMessage.h */, 0A8045B466C02A11EC535FEA5D499969 /* GPBMessage.m */, E0DFF23FA7BE9E6B2895EB02D9BECE5B /* GPBMessage_PackagePrivate.h */, 6287849BDEE4BA309FB7331612394E21 /* GPBProtocolBuffers.h */, B3DCE1AFAC5A620684FCBD064A8DEF43 /* GPBProtocolBuffers_RuntimeSupport.h */, AA0E980AC9FF4578482D67C373AD6A2C /* GPBRootObject.h */, D233AE44039C91F17E38C0A7CC0264DC /* GPBRootObject.m */, F633F2162DFB17DBA6CAE4A7BC8106F5 /* GPBRootObject_PackagePrivate.h */, D4AFECCCD1BB9E1D39EE664F889B27EE /* GPBRuntimeTypes.h */, 8F939A9917A756519BB11774E9D7234E /* GPBUnknownField.h */, 3445849ED1BC9E3E91DC1C7B79B240B2 /* GPBUnknownField.m */, 7F537DC4231346EB9D6358636348BDAD /* GPBUnknownField_PackagePrivate.h */, 2399407BB6B32E11C2AB3C8E2ED57107 /* GPBUnknownFieldSet.h */, 388E90C7B8E020B09466C3A20CCF3D1F /* GPBUnknownFieldSet.m */, 85CAAE47903B984CCEF10C64FED57E29 /* GPBUnknownFieldSet_PackagePrivate.h */, E11E039C349D10336D58A595E92E82BD /* GPBUtilities.h */, F0E8C736B3E668F9A737147D133C0BE9 /* GPBUtilities.m */, 6E1422A205CCC6C2A68F3BCDC65A2681 /* GPBUtilities_PackagePrivate.h */, BCBBB5C49100843EA7A2F4051A6A8868 /* GPBWellKnownTypes.h */, 5A12BB87FFB15F38B8157D22062AEFA8 /* GPBWellKnownTypes.m */, 8365C78E503339DDD330269D7EE945FB /* GPBWireFormat.h */, 2228AAD69DCAB7D0957FBC4384855A87 /* GPBWireFormat.m */, 9B3EFA614851F8D2D39514F535FF6DF2 /* SourceContext.pbobjc.h */, 6B6E55E81F578FA94A49A421048724BE /* SourceContext.pbobjc.m */, D87B3C76A56E9DD3F45B0ABB0BA03D03 /* Struct.pbobjc.h */, 3F555682E5B64EC452CE24A7274FBE7C /* Struct.pbobjc.m */, 2F8623CD7F77917BCB2E2474401E2D56 /* Timestamp.pbobjc.h */, 12F79A2491EC1052229C66AF62DCBB41 /* Timestamp.pbobjc.m */, 61399E0E4922FA39AFB05E4DB44409A6 /* Type.pbobjc.h */, F937A2E4B31957AD2175578718F135F7 /* Type.pbobjc.m */, 34124ADE309AF6601C988CEF79258B04 /* Wrappers.pbobjc.h */, B5D691F7C0CC32DE14055D8A2B0D93EA /* Wrappers.pbobjc.m */, 5A22883C7BF42FFCA0F1EC4747BB2BD8 /* Support Files */, ); name = Protobuf; path = Protobuf; sourceTree = ""; }; 6D9E964E2948DA2829702671A408142E /* Alamofire */ = { isa = PBXGroup; children = ( 82B26668D8AAE3B145611B17DBA167E8 /* AFError.swift */, 75FCB10083216ED1E69476F1104850A7 /* Alamofire.swift */, 6C71F9CBF999BBC827CCA1BAEC26C753 /* DispatchQueue+Alamofire.swift */, D83C9D62E6C76E35925E276E2F9E8EA2 /* MultipartFormData.swift */, E57E89B2D9C9E36F1AC9B97B01573EDF /* NetworkReachabilityManager.swift */, 6A9449DA0F0D0C2028D7A4203E962185 /* Notifications.swift */, 0A12C1915E74E1191B53186485D1AA73 /* ParameterEncoding.swift */, 0017EE26E403D8D5F57C9A12A52407C8 /* Request.swift */, AA4F38320587D354C68987BEB930518F /* Response.swift */, 3723EAA3E2CED82A6F296E9D449B512F /* ResponseSerialization.swift */, CD113341C96346B25BDB79A7D73C6AF9 /* Result.swift */, 06A7ED339F0AD550AF7D3E627E95C93F /* ServerTrustPolicy.swift */, 7E918145C65843E6CAF5984FA7B3CF41 /* SessionDelegate.swift */, 9214AC4B970DD95C124DAA0F299B7737 /* SessionManager.swift */, AB8B4236B1B9D5F60E68971568825241 /* TaskDelegate.swift */, FD8F6DC1115CB144FF92AB6EAAF28F71 /* Timeline.swift */, 8196F690597E27125ABCD8269935E3ED /* Validation.swift */, DEF83772C346FEDD6317506638402A9D /* Support Files */, ); name = Alamofire; path = Alamofire; sourceTree = ""; }; 7A012CF20D07820BA32477D144FC7BB4 /* Kingfisher */ = { isa = PBXGroup; children = ( 6C844058A839BBD30AEBB9F89E6F5DC8 /* AnimatedImageView.swift */, 98A1EFB7523BA19CC4A787D090C18C42 /* Box.swift */, 0F70907D59C28A561718AB74E9869015 /* CacheSerializer.swift */, EC37DCFDC0C97496BC8D398BFC62FB6B /* Filter.swift */, CE8F49ABF4D9A6F33B02DF6899B3145D /* Image.swift */, 7FDA8F60E56D6CD0C29874DD73DC7E6E /* ImageCache.swift */, 5D2A1351E4207F3AB5385D4FF20E2C53 /* ImageDownloader.swift */, 5F35D386A8371B862446ADC3DDC9D6FF /* ImagePrefetcher.swift */, 37D686F38E816CC415B2E75E0C413C0C /* ImageProcessor.swift */, AA5A7CC657402D18E3CA3CE9F983D5B2 /* ImageTransition.swift */, 015E884095ABEA9EED1A37D11863CF3C /* ImageView+Kingfisher.swift */, 3C428BEE819C0B2E1253E729F5F60893 /* Indicator.swift */, 4F88FD47527B6B1FD98BD48BF2C8C24F /* Kingfisher.h */, 8D793932C0881AB718CB4A7EBD697FCA /* Kingfisher.swift */, CC50FD950B40E66F948C91F67B79F052 /* KingfisherManager.swift */, 21402C2B37A0133143EA232F3C53B300 /* KingfisherOptionsInfo.swift */, F0A9AA103C42618131066BBF82532F48 /* RequestModifier.swift */, F95792901223019B294F94192BB0A545 /* Resource.swift */, DA775BA2775D27D8A1EBB7D78DB02E6F /* String+MD5.swift */, AC1BF5F2D25F2F3A30CE62E356EADDA7 /* ThreadHelper.swift */, 46A9AFC3851E2FA39D73B26A57C8CA75 /* UIButton+Kingfisher.swift */, 23D14ACD17D376D97752C60EE7CEBA54 /* Support Files */, ); name = Kingfisher; path = Kingfisher; sourceTree = ""; }; 7DB346D0F39D3F0E887471402A8071AB = { isa = PBXGroup; children = ( 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, 4C6DB2B31394B2EE81A2D4091E39252C /* Frameworks */, CDB5EE7ADB9A1F7C11761DCFDD40CEEE /* Pods */, C61696E039436A632519F049FF807CD3 /* Products */, DF125D80911D6A8703418D9B496E0189 /* Targets Support Files */, ); sourceTree = ""; }; 886210286B9F04CCF5370952C7D303A1 /* Core */ = { isa = PBXGroup; children = ( 66F9A8399FF65AB025EFB7A4E00B9C8B /* Firebase.h */, ); name = Core; sourceTree = ""; }; 97217E666F1363DF5F26670FE3242B9A /* NSData+zlib */ = { isa = PBXGroup; children = ( 1370A8CD06F55CD39311C1D55A9AB0EC /* GTMNSData+zlib.h */, 1A485F7C17155623DD79D981309762F1 /* GTMNSData+zlib.m */, ); name = "NSData+zlib"; sourceTree = ""; }; A756CA037AD9ECD973FDD3812893B587 /* Defines */ = { isa = PBXGroup; children = ( E9315BB455F8D4C316FFC5ED322BAA48 /* GTMDefines.h */, ); name = Defines; sourceTree = ""; }; ABB43032D948590F73701E941EE178AF /* Firebase */ = { isa = PBXGroup; children = ( 886210286B9F04CCF5370952C7D303A1 /* Core */, ); name = Firebase; path = Firebase; sourceTree = ""; }; B5B839A11E7A4F237C61CA1B051F631C /* AlamofireSwiftyJSON */ = { isa = PBXGroup; children = ( 023357B17131C50242F505F95416C2E0 /* AlamofireSwiftyJSON.swift */, C531ED75E230F79282EB087AEF972971 /* Support Files */, ); name = AlamofireSwiftyJSON; path = AlamofireSwiftyJSON; sourceTree = ""; }; BF085BBBCBF1A056D151824724FA0C29 /* Frameworks */ = { isa = PBXGroup; children = ( 5BCC748DC6D93D9EE46A21F6DFACA423 /* FirebaseAnalytics.framework */, ); name = Frameworks; sourceTree = ""; }; C531ED75E230F79282EB087AEF972971 /* Support Files */ = { isa = PBXGroup; children = ( 21616BB6570ECD53F1AEE82C6375E3DD /* AlamofireSwiftyJSON.modulemap */, D79D6024F9ABEBE0B74CC08913EBBEB7 /* AlamofireSwiftyJSON.xcconfig */, E58F047CCD125933FEEA820C88B43CDF /* AlamofireSwiftyJSON-dummy.m */, D7F04EC09A08EF0FB13AF7E9B3D05B28 /* AlamofireSwiftyJSON-prefix.pch */, 8C7870986BB014C3DF72DB43101609BE /* AlamofireSwiftyJSON-umbrella.h */, 121DCC5ABFA4534BA03C49AD806C4788 /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/AlamofireSwiftyJSON"; sourceTree = ""; }; C57C7854CD7AA1B407402A6810812888 /* FirebaseMessaging */ = { isa = PBXGroup; children = ( 2D77C9ECA1F229B98B54BC4CB76A4346 /* Frameworks */, ); name = FirebaseMessaging; path = FirebaseMessaging; sourceTree = ""; }; C61696E039436A632519F049FF807CD3 /* Products */ = { isa = PBXGroup; children = ( 62BABF9DE94CE98833CF5DCCB812A522 /* Alamofire.framework */, 573E083632F044348A22102F38B679D5 /* AlamofireSwiftyJSON.framework */, 08022507F0AC050C0927D291E2695207 /* GoogleToolboxForMac.framework */, A862187FB05C586D038914229E373876 /* Kingfisher.framework */, FFD5F74AF249D2DD8A551156CC19FA6E /* Pods_ezshopUser.framework */, F6A3BA44E6E8AF5A57F1D49F1C70D12D /* Protobuf.framework */, 5399A2C50A8469480F11298D2F271438 /* SwiftyJSON.framework */, ); name = Products; sourceTree = ""; }; CDB5EE7ADB9A1F7C11761DCFDD40CEEE /* Pods */ = { isa = PBXGroup; children = ( 6D9E964E2948DA2829702671A408142E /* Alamofire */, B5B839A11E7A4F237C61CA1B051F631C /* AlamofireSwiftyJSON */, ABB43032D948590F73701E941EE178AF /* Firebase */, 602DD0727BA743D7757549397D855188 /* FirebaseAnalytics */, F6AEF6ABA1ABB47FFF91CF00895D713D /* FirebaseCore */, DC71C35EAC95E1AAFCA4071935FA04F4 /* FirebaseDatabase */, EE9D357D7F38E274913EF9DC175E12CE /* FirebaseInstanceID */, C57C7854CD7AA1B407402A6810812888 /* FirebaseMessaging */, F0C0A12358C012C04F25379151B595FB /* GoogleToolboxForMac */, 7A012CF20D07820BA32477D144FC7BB4 /* Kingfisher */, 6B5F4DC53D9A6CA07B8DF26721808B04 /* Protobuf */, 3FD46E3A2501853B6A4CF71ECFB019E7 /* SwiftyJSON */, ); name = Pods; sourceTree = ""; }; DB18C85BCCB63816C80845BB9B877BA7 /* Pods-ezshopUser */ = { isa = PBXGroup; children = ( 723F27C34C82F86747773C750671AA54 /* Info.plist */, 0D76ADD39984876AEAE8D5CE4946F7D2 /* Pods-ezshopUser.modulemap */, 7F0A1946B8BBA4BD4D6512EA900BF123 /* Pods-ezshopUser-acknowledgements.markdown */, 2B48F4313F780926BFD002DD0BF0D583 /* Pods-ezshopUser-acknowledgements.plist */, EB8E9341FBA1A36B81A706F7CB73BC2D /* Pods-ezshopUser-dummy.m */, 07D2BB4F514782F4380125C7F3B348A5 /* Pods-ezshopUser-frameworks.sh */, 9B1C5A0E579735089019A48A48148837 /* Pods-ezshopUser-resources.sh */, 69FFF772582D154D8B1411854ECCB7F6 /* Pods-ezshopUser-umbrella.h */, 06C543665332C42D6BC9E2381EEBA966 /* Pods-ezshopUser.debug.xcconfig */, 12EE78E0A5094E8A289D185AC82C0CAA /* Pods-ezshopUser.release.xcconfig */, ); name = "Pods-ezshopUser"; path = "Target Support Files/Pods-ezshopUser"; sourceTree = ""; }; DC71C35EAC95E1AAFCA4071935FA04F4 /* FirebaseDatabase */ = { isa = PBXGroup; children = ( 62D7E97AD3640F1CE4E35CD062C37558 /* Frameworks */, ); name = FirebaseDatabase; path = FirebaseDatabase; sourceTree = ""; }; DEF83772C346FEDD6317506638402A9D /* Support Files */ = { isa = PBXGroup; children = ( 6C662288D30F692E3ECC87280EAC8B74 /* Alamofire.modulemap */, 00B18B258C83F13D7E9A6BC2C470D918 /* Alamofire.xcconfig */, DEE47E9A755AF7F5BC23047B06BB7803 /* Alamofire-dummy.m */, A7EEA39742AFD80094F02DA1C58BCCB0 /* Alamofire-prefix.pch */, D20F91D5BAFBD5486CACD60D66BB8494 /* Alamofire-umbrella.h */, 4EB6B376AFE2D2EFF28B2C5E0A90F8BE /* Info.plist */, ); name = "Support Files"; path = "../Target Support Files/Alamofire"; sourceTree = ""; }; DF125D80911D6A8703418D9B496E0189 /* Targets Support Files */ = { isa = PBXGroup; children = ( DB18C85BCCB63816C80845BB9B877BA7 /* Pods-ezshopUser */, ); name = "Targets Support Files"; sourceTree = ""; }; DF61F980FD8E405A3015A8237E7D1415 /* Frameworks */ = { isa = PBXGroup; children = ( 9F64C5558790995FF9AE88D3346A38C9 /* FirebaseInstanceID.framework */, ); name = Frameworks; sourceTree = ""; }; EE9D357D7F38E274913EF9DC175E12CE /* FirebaseInstanceID */ = { isa = PBXGroup; children = ( DF61F980FD8E405A3015A8237E7D1415 /* Frameworks */, ); name = FirebaseInstanceID; path = FirebaseInstanceID; sourceTree = ""; }; F0C0A12358C012C04F25379151B595FB /* GoogleToolboxForMac */ = { isa = PBXGroup; children = ( A756CA037AD9ECD973FDD3812893B587 /* Defines */, 601A21DAA3246880967E1D647D86123D /* Logger */, 97217E666F1363DF5F26670FE3242B9A /* NSData+zlib */, 5E2F44668A566A9194F297B6C52317F5 /* Support Files */, ); name = GoogleToolboxForMac; path = GoogleToolboxForMac; sourceTree = ""; }; F6AEF6ABA1ABB47FFF91CF00895D713D /* FirebaseCore */ = { isa = PBXGroup; children = ( 350E12F6D88A18D012BC213A82F78CEB /* Frameworks */, ); name = FirebaseCore; path = FirebaseCore; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 0F94B6BFE5A6242FBBB0BE3D27F7CEE9 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( A8F35D1EBAEF99D38F02A0B8CA5D8FBE /* Kingfisher-umbrella.h in Headers */, 179523942E7D1E3EB210EF05E2C7AE79 /* Kingfisher.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 1D0E68F4E1B68000D38C8EE5DD2B7CAC /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 7FE7F76FB02A5027A6597578BD7D7D0F /* Any.pbobjc.h in Headers */, 6EA2232FA2BA69E7A974C24997CD5CEF /* Api.pbobjc.h in Headers */, 9576DCFA6C5D93AA57F5D855A8AEE496 /* Duration.pbobjc.h in Headers */, 3FC2DEED5FBD8B67ECB0CD4EC1D38954 /* Empty.pbobjc.h in Headers */, 27BB7A8E478121DC29F5CE34A71E4DC3 /* FieldMask.pbobjc.h in Headers */, C4D1E650D8529AFB35BCBD8C281294DF /* GPBArray.h in Headers */, F1679BFE4FF39E1909E87E5345515E3C /* GPBArray_PackagePrivate.h in Headers */, 5CDAF5ECEE4EFE5F52E8825C007671EA /* GPBBootstrap.h in Headers */, 2B2882EDBFFB475408DD1C3F732C3003 /* GPBCodedInputStream.h in Headers */, D08A54A24BBD582599244BB16024D7E3 /* GPBCodedInputStream_PackagePrivate.h in Headers */, 6EA5E49A3A0877A57949394E30CC8565 /* GPBCodedOutputStream.h in Headers */, FC368C6D8E82D17BB8CB7956BB67B875 /* GPBCodedOutputStream_PackagePrivate.h in Headers */, D50931201EE99B301301F42393DF189B /* GPBDescriptor.h in Headers */, E37A508E9EDE338F47C8AD7F2DABB1AB /* GPBDescriptor_PackagePrivate.h in Headers */, AC10566128ACA11212EA7DB956620226 /* GPBDictionary.h in Headers */, 52B675FC8950B51FC33300A1ECD5F275 /* GPBDictionary_PackagePrivate.h in Headers */, C8B9BC8AF83613F0AB1269209150B15C /* GPBExtensionInternals.h in Headers */, 95398F0CC3450C855C578A06F298DF8D /* GPBExtensionRegistry.h in Headers */, 4A8B2322D0DF6C4A2AB5EADED4281BC2 /* GPBMessage.h in Headers */, 3410282527236BAE6C77E760206A2860 /* GPBMessage_PackagePrivate.h in Headers */, 8526A013821844B0CD77FFF8C7EA7B34 /* GPBProtocolBuffers.h in Headers */, 5F577A91C5A251FB08C01DB9FF8FFED4 /* GPBProtocolBuffers_RuntimeSupport.h in Headers */, E2B615E1D93DCD721BAB1ACC50BA144E /* GPBRootObject.h in Headers */, 554E50D6FB68B117CBFD447233C60EBE /* GPBRootObject_PackagePrivate.h in Headers */, 23B0DBDBE851016D8C15546F4DC260E2 /* GPBRuntimeTypes.h in Headers */, DEAA3A9A9710B0567CA98E618C137608 /* GPBUnknownField.h in Headers */, DF6D5769A321A040E12EE3C75C2C55D1 /* GPBUnknownField_PackagePrivate.h in Headers */, 7685F73DC6AF03B4A47DDE9B5FC5AFCD /* GPBUnknownFieldSet.h in Headers */, D80AB0EBA39A6EE0DF7CFAC7974698CA /* GPBUnknownFieldSet_PackagePrivate.h in Headers */, FCBA7A5E42E0FAC55B37FA0B5B2F51C6 /* GPBUtilities.h in Headers */, 5553EC47014ED2AE8BB342FF926C272F /* GPBUtilities_PackagePrivate.h in Headers */, 75D5A69C61A68922B148CA71F0172E19 /* GPBWellKnownTypes.h in Headers */, A4228F2845CE06BD24D5A863D6E45181 /* GPBWireFormat.h in Headers */, 5338F8282895A05C3A35A3AA1D243716 /* Protobuf-umbrella.h in Headers */, 0B68193A407CAF9775F65787B3357266 /* SourceContext.pbobjc.h in Headers */, 6D707BB31820B5F79A0B4AE74FE786FF /* Struct.pbobjc.h in Headers */, F0D9C922408F7EDE7FEA43079A43C867 /* Timestamp.pbobjc.h in Headers */, 00E8E6EA851CA7C56F18EF3FB88995C8 /* Type.pbobjc.h in Headers */, A7A7128944AD30A4C975CC707CAABA9E /* Wrappers.pbobjc.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 3D3CACB7864BED7F83E4ADEDE0D6EE4D /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 5068EA401BAAC807CB5699005DEF8E03 /* SwiftyJSON-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; A65C674BC8B355E13D74FD423DC8F657 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( ED66F8BD1D43065D931F2C8890806447 /* GoogleToolboxForMac-umbrella.h in Headers */, 3E3B4CF239527A39CD308EBA9676FD8F /* GTMDefines.h in Headers */, 0FF8F27F896850DB2973C4E26EC1F7EE /* GTMLogger.h in Headers */, 755F55A7D577254B73EA7FEABA8E98E0 /* GTMNSData+zlib.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 1B9EDEDC964E6B08F78920B4F4B9DB84 /* Alamofire-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; D5C9442E4D341BC38656D3EF6CE7F323 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 77C5A81B67F4C3A2890826E534AF53DD /* AlamofireSwiftyJSON-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; F9EDA3C43758FBF100F600A3B1EEC9BB /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 6170BF4DE14D79BF6D97BF558911DEB3 /* Pods-ezshopUser-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 21811172B39AFCC0543A13D0C8851A3C /* Protobuf */ = { isa = PBXNativeTarget; buildConfigurationList = C560E4453E42788B2664E00A784A2BFE /* Build configuration list for PBXNativeTarget "Protobuf" */; buildPhases = ( 6F032761E9BCA2384A77AE02E27FFBE4 /* Sources */, C6E6051A4B0615B7833BD8C24136F64B /* Frameworks */, 1D0E68F4E1B68000D38C8EE5DD2B7CAC /* Headers */, ); buildRules = ( ); dependencies = ( ); name = Protobuf; productName = Protobuf; productReference = F6A3BA44E6E8AF5A57F1D49F1C70D12D /* Protobuf.framework */; productType = "com.apple.product-type.framework"; }; 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */ = { isa = PBXNativeTarget; buildConfigurationList = DCCE50C77ACBD367E99B830BA1F92670 /* Build configuration list for PBXNativeTarget "AlamofireSwiftyJSON" */; buildPhases = ( FE667750AC3EE5E6C357274D08062245 /* Sources */, 229003D8AA2FC24D450F02A58E1EA5D2 /* Frameworks */, D5C9442E4D341BC38656D3EF6CE7F323 /* Headers */, ); buildRules = ( ); dependencies = ( F8E3977BAA922212CA0F1481E19D85F5 /* PBXTargetDependency */, FFC9EF8F219B1A13E2061AAE04196C7D /* PBXTargetDependency */, ); name = AlamofireSwiftyJSON; productName = AlamofireSwiftyJSON; productReference = 573E083632F044348A22102F38B679D5 /* AlamofireSwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; 882C078174A217628FC5C0C7371D70D1 /* Pods-ezshopUser */ = { isa = PBXNativeTarget; buildConfigurationList = 8444F7EBA5ED5B2955D9C23EB26CB488 /* Build configuration list for PBXNativeTarget "Pods-ezshopUser" */; buildPhases = ( 35F66A83A99B371799ACC21C68FC7F72 /* Sources */, B0C55565E8D6390E0F647FD9E9BBE386 /* Frameworks */, F9EDA3C43758FBF100F600A3B1EEC9BB /* Headers */, ); buildRules = ( ); dependencies = ( 498AE7F9589AD37C0FDD22236798F18E /* PBXTargetDependency */, 5B8EA554EECB536FEBA6B85B17E5FD85 /* PBXTargetDependency */, 7B19DD8EEE96A4C71ED33F4EB18B0107 /* PBXTargetDependency */, 08D399BDD78AF9DE34AFD78EC5E71EB5 /* PBXTargetDependency */, 17FE56B70837220D01CFB9BE19618964 /* PBXTargetDependency */, B2BFA31A726D665E51FB274833FC9A19 /* PBXTargetDependency */, ); name = "Pods-ezshopUser"; productName = "Pods-ezshopUser"; productReference = FFD5F74AF249D2DD8A551156CC19FA6E /* Pods_ezshopUser.framework */; productType = "com.apple.product-type.framework"; }; 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */ = { isa = PBXNativeTarget; buildConfigurationList = 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */; buildPhases = ( 32B9974868188C4803318E36329C87FE /* Sources */, 99195E4207764744AEC07ECCBCD550EB /* Frameworks */, B4002B6E97835FDCCAA5963EFE09A3E0 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = Alamofire; productName = Alamofire; productReference = 62BABF9DE94CE98833CF5DCCB812A522 /* Alamofire.framework */; productType = "com.apple.product-type.framework"; }; C4944FEC314D1A66588651D006273ADE /* Kingfisher */ = { isa = PBXNativeTarget; buildConfigurationList = 76E7EFBCEA1340954A03AA68051C2306 /* Build configuration list for PBXNativeTarget "Kingfisher" */; buildPhases = ( EAC7EA95310C5E1E724C632852F7D186 /* Sources */, ED03E5917B811BACFE75189AE0C2A469 /* Frameworks */, 0F94B6BFE5A6242FBBB0BE3D27F7CEE9 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = Kingfisher; productName = Kingfisher; productReference = A862187FB05C586D038914229E373876 /* Kingfisher.framework */; productType = "com.apple.product-type.framework"; }; C5B80060FE8C664DF08841000F41D515 /* GoogleToolboxForMac */ = { isa = PBXNativeTarget; buildConfigurationList = A7DCD5CC93C327FAB5EAF73A7ECA9866 /* Build configuration list for PBXNativeTarget "GoogleToolboxForMac" */; buildPhases = ( EF9AB148BBDF7952FC3CFBFF4694161B /* Sources */, C5FBD50589CE2C516975A62886A56E07 /* Frameworks */, A65C674BC8B355E13D74FD423DC8F657 /* Headers */, ); buildRules = ( ); dependencies = ( ); name = GoogleToolboxForMac; productName = GoogleToolboxForMac; productReference = 08022507F0AC050C0927D291E2695207 /* GoogleToolboxForMac.framework */; productType = "com.apple.product-type.framework"; }; C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */ = { isa = PBXNativeTarget; buildConfigurationList = EB8E706BCD309B61E67B4B6956F61DCA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */; buildPhases = ( 6ADC89DA0DB8AAD7550B08A75014E0BB /* Sources */, 8DD06B625DFB302A853551293B0AB0B4 /* Frameworks */, 3D3CACB7864BED7F83E4ADEDE0D6EE4D /* Headers */, ); buildRules = ( ); dependencies = ( ); name = SwiftyJSON; productName = SwiftyJSON; productReference = 5399A2C50A8469480F11298D2F271438 /* SwiftyJSON.framework */; productType = "com.apple.product-type.framework"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; LastUpgradeCheck = 0700; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, ); mainGroup = 7DB346D0F39D3F0E887471402A8071AB; productRefGroup = C61696E039436A632519F049FF807CD3 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */, 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */, C5B80060FE8C664DF08841000F41D515 /* GoogleToolboxForMac */, C4944FEC314D1A66588651D006273ADE /* Kingfisher */, 882C078174A217628FC5C0C7371D70D1 /* Pods-ezshopUser */, 21811172B39AFCC0543A13D0C8851A3C /* Protobuf */, C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 32B9974868188C4803318E36329C87FE /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 9ED2BB2981896E0A39EFA365503F58CE /* AFError.swift in Sources */, A9EEEA7477981DEEBC72432DE9990A4B /* Alamofire-dummy.m in Sources */, F8B3D3092ED0417E8CDF32033F6122F5 /* Alamofire.swift in Sources */, 61200D01A1855D7920CEF835C8BE00B0 /* DispatchQueue+Alamofire.swift in Sources */, B65FCF589DA398C3EFE0128064E510EC /* MultipartFormData.swift in Sources */, A2A6F71B727312BD45CC7A4AAD7B0AB7 /* NetworkReachabilityManager.swift in Sources */, EFD264FC408EBF3BA2528E70B08DDD94 /* Notifications.swift in Sources */, BE5C67A07E289FE1F9BE27335B159997 /* ParameterEncoding.swift in Sources */, 5387216E723A3C68E851CA15573CDD71 /* Request.swift in Sources */, CB6D60925223897FFA2662667DF83E8A /* Response.swift in Sources */, F6BECD98B97CBFEBE2C96F0E9E72A6C0 /* ResponseSerialization.swift in Sources */, 7D8CC01E8C9EFFF9F4D65406CDE0AB66 /* Result.swift in Sources */, 62F65AD8DC4F0F9610F4B8B4738EC094 /* ServerTrustPolicy.swift in Sources */, 7B5FE28C7EA4122B0598738E54DBEBD8 /* SessionDelegate.swift in Sources */, AE1EF48399533730D0066E04B22CA2D6 /* SessionManager.swift in Sources */, 3626B94094672CB1C9DEA32B9F9502E1 /* TaskDelegate.swift in Sources */, 10EB23E9ECC4B33E16933BB1EA560B6A /* Timeline.swift in Sources */, BBEFE2F9CEB73DC7BD97FFA66A0D9D4F /* Validation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 35F66A83A99B371799ACC21C68FC7F72 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 31F6C6283ABB7B2A7A4840A82B9C5EEA /* Pods-ezshopUser-dummy.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6ADC89DA0DB8AAD7550B08A75014E0BB /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 20FFCB796689940613A141013D758B10 /* SwiftyJSON-dummy.m in Sources */, A5CE453D368326CCFE2ECA3034306EAA /* SwiftyJSON.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6F032761E9BCA2384A77AE02E27FFBE4 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( EA064ADB856A4CF4E6DD67787FF35D36 /* Any.pbobjc.m in Sources */, 26CDCF6645185C520134E1320B9147E6 /* Api.pbobjc.m in Sources */, 17C46464C5B0BA51B9C6DD71636EAB0D /* Duration.pbobjc.m in Sources */, 111F6A0D947700AC302CC02AE240F5A9 /* Empty.pbobjc.m in Sources */, CA7718794BD71A1C5A5E0820F76C3692 /* FieldMask.pbobjc.m in Sources */, 4CC855EE8E2A3D5B8B61865B34F028EA /* GPBArray.m in Sources */, 8FC05594728E7F30D90316E8945B5BFE /* GPBCodedInputStream.m in Sources */, C8165AE5AC7E4B0016A2294FCD3E0AA2 /* GPBCodedOutputStream.m in Sources */, 6404C09FAB58402D628CAD8E433C8FE1 /* GPBDescriptor.m in Sources */, 4EC5C27621EB68BF8E77415F7FC1CF80 /* GPBDictionary.m in Sources */, 3B967DF26BEF9DC06380CF94487CC694 /* GPBExtensionInternals.m in Sources */, A55F6C23ECB45FC1C0D5B8A76908DDA0 /* GPBExtensionRegistry.m in Sources */, 453AFD82272E1ABF8A688622A527C8C1 /* GPBMessage.m in Sources */, D070E49D39268ECBE512026EC5CBF2A6 /* GPBRootObject.m in Sources */, A4BA9026A393266E08D360A2B19D62B7 /* GPBUnknownField.m in Sources */, 75BD15665AE7C10FEC4F64CF9CDA2221 /* GPBUnknownFieldSet.m in Sources */, E4258CB32A838760B5803E7086724F0D /* GPBUtilities.m in Sources */, 2D7702EDC73F54AD4C21555F63212F8E /* GPBWellKnownTypes.m in Sources */, 3A85B73C819D7077CC2A2A37BA95CB87 /* GPBWireFormat.m in Sources */, 95150D776F156226116B93DDBAD3B789 /* Protobuf-dummy.m in Sources */, 79FE946262490B5FF43FEA8A3ECB51D9 /* SourceContext.pbobjc.m in Sources */, 985CD33D98AD4F6311964B831D842612 /* Struct.pbobjc.m in Sources */, 4C6E09361DDBF58B631DD4848A4F17BA /* Timestamp.pbobjc.m in Sources */, AF064D0F53E54165493C9DB282B8B374 /* Type.pbobjc.m in Sources */, C4752D0EFF8A8C803DA71E2445870710 /* Wrappers.pbobjc.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; EAC7EA95310C5E1E724C632852F7D186 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 342AE33215135AD56B73580012DC22AB /* AnimatedImageView.swift in Sources */, 6DA770087D354CDCD3889CDAE7C4C698 /* Box.swift in Sources */, 2E5E570FFC49EF98550401421A243C0F /* CacheSerializer.swift in Sources */, 4089E39F76F86466B8DDD39A1C1ABB6B /* Filter.swift in Sources */, 33A14E817C0FA585D5DA3A55E453299D /* Image.swift in Sources */, F8E957950566622A3E4B61AACE8F0B4A /* ImageCache.swift in Sources */, DC6080C64C269628C3F5107BE87055E2 /* ImageDownloader.swift in Sources */, 3414E1D9CB15149A296E16C45967B021 /* ImagePrefetcher.swift in Sources */, 0E9CC28AC8E34FE8E1C87E933E04BC7A /* ImageProcessor.swift in Sources */, 86B7DA678C8705523C300947117C0706 /* ImageTransition.swift in Sources */, 33395912F2FFA355C4C36B7EDEAA3DA7 /* ImageView+Kingfisher.swift in Sources */, 52A280AB4852FDE92DF09B5E79D5C2AA /* Indicator.swift in Sources */, 6A375593407BC7937234B2B6A0811760 /* Kingfisher-dummy.m in Sources */, C9CC5ED97D29C6C3DE22B78A9AA2AD91 /* Kingfisher.swift in Sources */, 7636F846675C9F4ED96E00C6C19A4890 /* KingfisherManager.swift in Sources */, 378B44CAA91C2106076668FDE72E1E02 /* KingfisherOptionsInfo.swift in Sources */, EA816A580C3858934ED6FE92040C26DD /* RequestModifier.swift in Sources */, 8DA7E6883118CB3C8132B64D3D43AE0B /* Resource.swift in Sources */, 9F826F893E86EB86591B637A1CE4B13A /* String+MD5.swift in Sources */, 6CD63E1564618B6213B98E0ABBC3127C /* ThreadHelper.swift in Sources */, EE89512E8D36E67CDC525DB9D5BBF5A7 /* UIButton+Kingfisher.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; EF9AB148BBDF7952FC3CFBFF4694161B /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 64418457D16D9A2F28F496AC75FC7DBD /* GoogleToolboxForMac-dummy.m in Sources */, AB4F0970071E34D0384341466E0468EF /* GTMLogger.m in Sources */, 9101CEA8562055177732244271008BBB /* GTMNSData+zlib.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; FE667750AC3EE5E6C357274D08062245 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 4E59744DDACFECB37D3531E504228AA1 /* AlamofireSwiftyJSON-dummy.m in Sources */, 59BE44195191D46A245AAB3F8B5BA4A4 /* AlamofireSwiftyJSON.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 08D399BDD78AF9DE34AFD78EC5E71EB5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Kingfisher; target = C4944FEC314D1A66588651D006273ADE /* Kingfisher */; targetProxy = 44499CB1CAC5DD785DF381C693D5AD65 /* PBXContainerItemProxy */; }; 17FE56B70837220D01CFB9BE19618964 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Protobuf; target = 21811172B39AFCC0543A13D0C8851A3C /* Protobuf */; targetProxy = 9E39825F79A07D7716D92B12FE467B44 /* PBXContainerItemProxy */; }; 498AE7F9589AD37C0FDD22236798F18E /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; targetProxy = 50DFA62826566C291F52E77FE2979E38 /* PBXContainerItemProxy */; }; 5B8EA554EECB536FEBA6B85B17E5FD85 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = AlamofireSwiftyJSON; target = 61E5C1379DC63FAC57AF48F891CFB123 /* AlamofireSwiftyJSON */; targetProxy = 2482E32FAEC37CB313F3C622BDC5643E /* PBXContainerItemProxy */; }; 7B19DD8EEE96A4C71ED33F4EB18B0107 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GoogleToolboxForMac; target = C5B80060FE8C664DF08841000F41D515 /* GoogleToolboxForMac */; targetProxy = E5EC3AE45F34BF5E9209817976A01A23 /* PBXContainerItemProxy */; }; B2BFA31A726D665E51FB274833FC9A19 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftyJSON; target = C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */; targetProxy = 91FD6C13D7AFF34721D4FD73C6670538 /* PBXContainerItemProxy */; }; F8E3977BAA922212CA0F1481E19D85F5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Alamofire; target = 88E9EC28B8B46C3631E6B242B50F4442 /* Alamofire */; targetProxy = 9FDAF5C6C834BA59530A0169BB8EB750 /* PBXContainerItemProxy */; }; FFC9EF8F219B1A13E2061AAE04196C7D /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftyJSON; target = C68748E71A3DDB40B0AAF4BC0A8F9030 /* SwiftyJSON */; targetProxy = F6814470266156FFDECCFBF764C454DA /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 00B18B258C83F13D7E9A6BC2C470D918 /* Alamofire.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 0BCA67A8634EBFFCB1B601086C3BB0D5 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 12EE78E0A5094E8A289D185AC82C0CAA /* Pods-ezshopUser.release.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-ezshopUser/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 10.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-ezshopUser/Pods-ezshopUser.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = Pods_ezshopUser; SDKROOT = iphoneos; SKIP_INSTALL = YES; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 2E21F60AC37DC29D54831566835A195A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7C1D5CEFAB850ADB985585A6B3B87E37 /* Protobuf.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Protobuf/Protobuf-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Protobuf/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Protobuf/Protobuf.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = Protobuf; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 300BAE10FF360919FED5D22BBFAC5228 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7C1D5CEFAB850ADB985585A6B3B87E37 /* Protobuf.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Protobuf/Protobuf-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Protobuf/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Protobuf/Protobuf.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = Protobuf; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 380C30050278E488BE23DB926933212E /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 11CB7EB8D22A301400C0565A686824D7 /* Kingfisher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Kingfisher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = Kingfisher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 48B8EF5125D58BA1BEC5AD1252EFF787 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = E7CAF143AAC69661B4131A41BFE378D8 /* GoogleToolboxForMac.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GoogleToolboxForMac/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = GoogleToolboxForMac; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; 673254EEAF0B5BF4596080C749645884 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_RELEASE=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; SYMROOT = "${SRCROOT}/../build"; VALIDATE_PRODUCT = YES; }; name = Release; }; 6E53245BBAAAB71AD4E0EE52CA99FD28 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 11CB7EB8D22A301400C0565A686824D7 /* Kingfisher.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Kingfisher/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = Kingfisher; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 9AE22C4C4D968EC0A589760394449CA0 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 06C543665332C42D6BC9E2381EEBA966 /* Pods-ezshopUser.debug.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; INFOPLIST_FILE = "Target Support Files/Pods-ezshopUser/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 10.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MACH_O_TYPE = staticlib; MODULEMAP_FILE = "Target Support Files/Pods-ezshopUser/Pods-ezshopUser.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = ""; OTHER_LIBTOOLFLAGS = ""; PODS_ROOT = "$(SRCROOT)"; PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = Pods_ezshopUser; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; 9EC0381780FB0030D1C388B0D8C5AF03 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = D79D6024F9ABEBE0B74CC08913EBBEB7 /* AlamofireSwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/AlamofireSwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = AlamofireSwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; A0A2261397295783909F252F7AA52949 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 0A4E005A4CD207B854332863444D36C9 /* SwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; A32151AFE5B658C8AB05481B80BE36FE /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = E7CAF143AAC69661B4131A41BFE378D8 /* GoogleToolboxForMac.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch"; INFOPLIST_FILE = "Target Support Files/GoogleToolboxForMac/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = GoogleToolboxForMac; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; BA3A1AE463BAE81544A37570B2425BE8 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 0A4E005A4CD207B854332863444D36C9 /* SwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/SwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/SwiftyJSON/SwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = NO; PRODUCT_NAME = SwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Release; }; BE557DED54B73B607DDA59D2EEFB306E /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = D79D6024F9ABEBE0B74CC08913EBBEB7 /* AlamofireSwiftyJSON.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch"; INFOPLIST_FILE = "Target Support Files/AlamofireSwiftyJSON/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = AlamofireSwiftyJSON; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; E4F26E6EB105713A6A7E7E2E283AC2DF /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGNING_REQUIRED = NO; COPY_PHASE_STRIP = NO; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "POD_CONFIGURATION_DEBUG=1", "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; ONLY_ACTIVE_ARCH = YES; PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; STRIP_INSTALLED_PRODUCT = NO; SYMROOT = "${SRCROOT}/../build"; }; name = Debug; }; F383079BFBF927813EA3613CFB679FDE /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 00B18B258C83F13D7E9A6BC2C470D918 /* Alamofire.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; CURRENT_PROJECT_VERSION = 1; DEBUG_INFORMATION_FORMAT = dwarf; DEFINES_MODULE = YES; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_NO_COMMON_BLOCKS = YES; GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Alamofire/Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; MTL_ENABLE_DEBUG_INFO = YES; PRODUCT_NAME = Alamofire; SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; }; name = Debug; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { isa = XCConfigurationList; buildConfigurations = ( E4F26E6EB105713A6A7E7E2E283AC2DF /* Debug */, 673254EEAF0B5BF4596080C749645884 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 419E5D95491847CD79841B971A8A3277 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { isa = XCConfigurationList; buildConfigurations = ( F383079BFBF927813EA3613CFB679FDE /* Debug */, 0A29B6F510198AF64EFD762EF6FA97A5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 76E7EFBCEA1340954A03AA68051C2306 /* Build configuration list for PBXNativeTarget "Kingfisher" */ = { isa = XCConfigurationList; buildConfigurations = ( 6E53245BBAAAB71AD4E0EE52CA99FD28 /* Debug */, 380C30050278E488BE23DB926933212E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 8444F7EBA5ED5B2955D9C23EB26CB488 /* Build configuration list for PBXNativeTarget "Pods-ezshopUser" */ = { isa = XCConfigurationList; buildConfigurations = ( 9AE22C4C4D968EC0A589760394449CA0 /* Debug */, 0BCA67A8634EBFFCB1B601086C3BB0D5 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; A7DCD5CC93C327FAB5EAF73A7ECA9866 /* Build configuration list for PBXNativeTarget "GoogleToolboxForMac" */ = { isa = XCConfigurationList; buildConfigurations = ( A32151AFE5B658C8AB05481B80BE36FE /* Debug */, 48B8EF5125D58BA1BEC5AD1252EFF787 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; C560E4453E42788B2664E00A784A2BFE /* Build configuration list for PBXNativeTarget "Protobuf" */ = { isa = XCConfigurationList; buildConfigurations = ( 2E21F60AC37DC29D54831566835A195A /* Debug */, 300BAE10FF360919FED5D22BBFAC5228 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; DCCE50C77ACBD367E99B830BA1F92670 /* Build configuration list for PBXNativeTarget "AlamofireSwiftyJSON" */ = { isa = XCConfigurationList; buildConfigurations = ( BE557DED54B73B607DDA59D2EEFB306E /* Debug */, 9EC0381780FB0030D1C388B0D8C5AF03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; EB8E706BCD309B61E67B4B6956F61DCA /* Build configuration list for PBXNativeTarget "SwiftyJSON" */ = { isa = XCConfigurationList; buildConfigurations = ( A0A2261397295783909F252F7AA52949 /* Debug */, BA3A1AE463BAE81544A37570B2425BE8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; } ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Alamofire.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/AlamofireSwiftyJSON.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/GoogleToolboxForMac.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Kingfisher.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Pods-ezshopUser.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/Protobuf.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/SwiftyJSON.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/Pods/Pods.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/xcschememanagement.plist ================================================ SchemeUserState Alamofire.xcscheme isShown AlamofireSwiftyJSON.xcscheme isShown GoogleToolboxForMac.xcscheme isShown Kingfisher.xcscheme isShown Pods-ezshopUser.xcscheme isShown Protobuf.xcscheme isShown SwiftyJSON.xcscheme isShown SuppressBuildableAutocreation 21811172B39AFCC0543A13D0C8851A3C primary 61E5C1379DC63FAC57AF48F891CFB123 primary 882C078174A217628FC5C0C7371D70D1 primary 88E9EC28B8B46C3631E6B242B50F4442 primary C4944FEC314D1A66588651D006273ADE primary C5B80060FE8C664DF08841000F41D515 primary C68748E71A3DDB40B0AAF4BC0A8F9030 primary ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/LICENSE ================================================ This license applies to all parts of Protocol Buffers except the following: - Atomicops support for generic gcc, located in src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. This file is copyrighted by Red Hat Inc. - Atomicops support for AIX/POWER, located in src/google/protobuf/stubs/atomicops_internals_power.h. This file is copyrighted by Bloomberg Finance LP. Copyright 2014, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Code generated by the Protocol Buffer compiler is owned by the owner of the input file used when generating it. This code is not standalone and requires a support library to be linked with it. This support library is itself covered by the above license. ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/README.md ================================================ Protocol Buffers - Google's data interchange format =================================================== [![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf) [![Build Status](https://grpc-testing.appspot.com/buildStatus/icon?job=protobuf_branch)](https://grpc-testing.appspot.com/job/protobuf_branch) [![Build Status](https://grpc-testing.appspot.com/job/protobuf_branch_32/badge/icon)](https://grpc-testing.appspot.com/job/protobuf_branch_32) [![Build Status](http://ci.bazel.io/buildStatus/icon?job=protobuf)](http://ci.bazel.io/job/protobuf/) Copyright 2008 Google Inc. https://developers.google.com/protocol-buffers/ Overview -------- Protocol Buffers (a.k.a., protobuf) are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data. You can find [protobuf's documentation on the Google Developers site](https://developers.google.com/protocol-buffers/). This README file contains protobuf installation instructions. To install protobuf, you need to install the protocol compiler (used to compile .proto files) and the protobuf runtime for your chosen programming language. Protocol Compiler Installation ------------------------------ The protocol compiler is written in C++. If you are using C++, please follow the [C++ Installation Instructions](src/README.md) to install protoc along with the C++ runtime. For non-C++ users, the simplest way to install the protocol compiler is to download a pre-built binary from our release page: [https://github.com/google/protobuf/releases](https://github.com/google/protobuf/releases) In the downloads section of each release, you can find pre-built binaries in zip packages: protoc-$VERSION-$PLATFORM.zip. It contains the protoc binary as well as a set of standard .proto files distributed along with protobuf. If you are looking for an old version that is not available in the release page, check out the maven repo here: [http://repo1.maven.org/maven2/com/google/protobuf/protoc/](http://repo1.maven.org/maven2/com/google/protobuf/protoc/) These pre-built binaries are only provided for released versions. If you want to use the github master version at HEAD, or you need to modify protobuf code, or you are using C++, it's recommended to build your own protoc binary from source. If you would like to build protoc binary from source, see the [C++ Installation Instructions](src/README.md). Protobuf Runtime Installation ----------------------------- Protobuf supports several different programming languages. For each programming language, you can find instructions in the corresponding source directory about how to install protobuf runtime for that specific language: | Language | Source | |--------------------------------------|-------------------------------------------------------| | C++ (include C++ runtime and protoc) | [src](src) | | Java | [java](java) | | Python | [python](python) | | Objective-C | [objectivec](objectivec) | | C# | [csharp](csharp) | | JavaNano | [javanano](javanano) | | JavaScript | [js](js) | | Ruby | [ruby](ruby) | | Go | [golang/protobuf](https://github.com/golang/protobuf) | | PHP | [php](php) | Usage ----- The complete documentation for Protocol Buffers is available via the web at: https://developers.google.com/protocol-buffers/ ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBArray.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBRuntimeTypes.h" NS_ASSUME_NONNULL_BEGIN //%PDDM-EXPAND DECLARE_ARRAYS() // This block of code is generated, do not edit it directly. #pragma mark - Int32 /** * Class used for repeated fields of int32_t values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32Array : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBInt32Array. **/ + (instancetype)array; /** * Creates and initializes a GPBInt32Array with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBInt32Array with value in it. **/ + (instancetype)arrayWithValue:(int32_t)value; /** * Creates and initializes a GPBInt32Array with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBInt32Array with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBInt32Array *)array; /** * Creates and initializes a GPBInt32Array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBInt32Array with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBInt32Array. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBInt32Array with a copy of the values. **/ - (instancetype)initWithValues:(const int32_t [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBInt32Array with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBInt32Array *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBInt32Array with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (int32_t)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(int32_t)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const int32_t [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBInt32Array *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(int32_t)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - UInt32 /** * Class used for repeated fields of uint32_t values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32Array : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBUInt32Array. **/ + (instancetype)array; /** * Creates and initializes a GPBUInt32Array with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBUInt32Array with value in it. **/ + (instancetype)arrayWithValue:(uint32_t)value; /** * Creates and initializes a GPBUInt32Array with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBUInt32Array with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBUInt32Array *)array; /** * Creates and initializes a GPBUInt32Array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBUInt32Array with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBUInt32Array. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBUInt32Array with a copy of the values. **/ - (instancetype)initWithValues:(const uint32_t [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBUInt32Array with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBUInt32Array *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBUInt32Array with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (uint32_t)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(uint32_t)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const uint32_t [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBUInt32Array *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(uint32_t)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint32_t)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - Int64 /** * Class used for repeated fields of int64_t values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64Array : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBInt64Array. **/ + (instancetype)array; /** * Creates and initializes a GPBInt64Array with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBInt64Array with value in it. **/ + (instancetype)arrayWithValue:(int64_t)value; /** * Creates and initializes a GPBInt64Array with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBInt64Array with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBInt64Array *)array; /** * Creates and initializes a GPBInt64Array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBInt64Array with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBInt64Array. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBInt64Array with a copy of the values. **/ - (instancetype)initWithValues:(const int64_t [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBInt64Array with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBInt64Array *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBInt64Array with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (int64_t)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(int64_t)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const int64_t [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBInt64Array *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(int64_t)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int64_t)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - UInt64 /** * Class used for repeated fields of uint64_t values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64Array : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBUInt64Array. **/ + (instancetype)array; /** * Creates and initializes a GPBUInt64Array with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBUInt64Array with value in it. **/ + (instancetype)arrayWithValue:(uint64_t)value; /** * Creates and initializes a GPBUInt64Array with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBUInt64Array with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBUInt64Array *)array; /** * Creates and initializes a GPBUInt64Array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBUInt64Array with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBUInt64Array. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBUInt64Array with a copy of the values. **/ - (instancetype)initWithValues:(const uint64_t [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBUInt64Array with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBUInt64Array *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBUInt64Array with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (uint64_t)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(uint64_t)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const uint64_t [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBUInt64Array *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(uint64_t)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint64_t)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - Float /** * Class used for repeated fields of float values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBFloatArray : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBFloatArray. **/ + (instancetype)array; /** * Creates and initializes a GPBFloatArray with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBFloatArray with value in it. **/ + (instancetype)arrayWithValue:(float)value; /** * Creates and initializes a GPBFloatArray with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBFloatArray with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBFloatArray *)array; /** * Creates and initializes a GPBFloatArray with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBFloatArray with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBFloatArray. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBFloatArray with a copy of the values. **/ - (instancetype)initWithValues:(const float [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBFloatArray with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBFloatArray *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBFloatArray with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (float)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(float)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const float [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBFloatArray *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(float)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(float)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - Double /** * Class used for repeated fields of double values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBDoubleArray : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBDoubleArray. **/ + (instancetype)array; /** * Creates and initializes a GPBDoubleArray with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBDoubleArray with value in it. **/ + (instancetype)arrayWithValue:(double)value; /** * Creates and initializes a GPBDoubleArray with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBDoubleArray with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBDoubleArray *)array; /** * Creates and initializes a GPBDoubleArray with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBDoubleArray with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBDoubleArray. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBDoubleArray with a copy of the values. **/ - (instancetype)initWithValues:(const double [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBDoubleArray with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBDoubleArray *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBDoubleArray with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (double)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(double)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const double [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBDoubleArray *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(double)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(double)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - Bool /** * Class used for repeated fields of BOOL values. This performs better than * boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolArray : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty GPBBoolArray. **/ + (instancetype)array; /** * Creates and initializes a GPBBoolArray with the single element given. * * @param value The value to be placed in the array. * * @return A newly instanced GPBBoolArray with value in it. **/ + (instancetype)arrayWithValue:(BOOL)value; /** * Creates and initializes a GPBBoolArray with the contents of the given * array. * * @param array Array with the contents to be put into the new array. * * @return A newly instanced GPBBoolArray with the contents of array. **/ + (instancetype)arrayWithValueArray:(GPBBoolArray *)array; /** * Creates and initializes a GPBBoolArray with the given capacity. * * @param count The capacity needed for the array. * * @return A newly instanced GPBBoolArray with a capacity of count. **/ + (instancetype)arrayWithCapacity:(NSUInteger)count; /** * @return A newly initialized and empty GPBBoolArray. **/ - (instancetype)init NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBBoolArray with a copy of the values. **/ - (instancetype)initWithValues:(const BOOL [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBBoolArray with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBBoolArray *)array; /** * Initializes the array with the given capacity. * * @param count The capacity needed for the array. * * @return A newly initialized GPBBoolArray with a capacity of count. **/ - (instancetype)initWithCapacity:(NSUInteger)count; /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (BOOL)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block; /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(BOOL)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const BOOL [])values count:(NSUInteger)count; /** * Adds the values from the given array to this array. * * @param array The array containing the elements to add to this array. **/ - (void)addValuesFromArray:(GPBBoolArray *)array; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(BOOL)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(BOOL)value; /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end #pragma mark - Enum /** * This class is used for repeated fields of int32_t values. This performs * better than boxing into NSNumbers in NSArrays. * * @note This class is not meant to be subclassed. **/ @interface GPBEnumArray : NSObject /** The number of elements contained in the array. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty GPBEnumArray. **/ + (instancetype)array; /** * Creates and initializes a GPBEnumArray with the enum validation function * given. * * @param func The enum validation function for the array. * * @return A newly instanced GPBEnumArray. **/ + (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a GPBEnumArray with the enum validation function * given and the single raw value given. * * @param func The enum validation function for the array. * @param value The raw value to add to this array. * * @return A newly instanced GPBEnumArray. **/ + (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)value; /** * Creates and initializes a GPBEnumArray that adds the elements from the * given array. * * @param array Array containing the values to add to the new array. * * @return A newly instanced GPBEnumArray. **/ + (instancetype)arrayWithValueArray:(GPBEnumArray *)array; /** * Creates and initializes a GPBEnumArray with the given enum validation * function and with the givencapacity. * * @param func The enum validation function for the array. * @param count The capacity needed for the array. * * @return A newly instanced GPBEnumArray with a capacity of count. **/ + (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)count; /** * Initializes the array with the given enum validation function. * * @param func The enum validation function for the array. * * @return A newly initialized GPBEnumArray with a copy of the values. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func NS_DESIGNATED_INITIALIZER; /** * Initializes the array, copying the given values. * * @param func The enum validation function for the array. * @param values An array with the values to put inside this array. * @param count The number of elements to copy into the array. * * @return A newly initialized GPBEnumArray with a copy of the values. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values count:(NSUInteger)count; /** * Initializes the array, copying the given values. * * @param array An array with the values to put inside this array. * * @return A newly initialized GPBEnumArray with a copy of the values. **/ - (instancetype)initWithValueArray:(GPBEnumArray *)array; /** * Initializes the array with the given capacity. * * @param func The enum validation function for the array. * @param count The capacity needed for the array. * * @return A newly initialized GPBEnumArray with a capacity of count. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)count; // These will return kGPBUnrecognizedEnumeratorValue if the value at index is not a // valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value at the given index. * * @param index The index of the value to get. * * @return The value at the given index. **/ - (int32_t)valueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; // These methods bypass the validationFunc to provide access to values that were not // known at the time the binary was compiled. /** * Gets the raw enum value at the given index. * * @param index The index of the raw enum value to get. * * @return The raw enum value at the given index. **/ - (int32_t)rawValueAtIndex:(NSUInteger)index; /** * Enumerates the values on this array with the given block. * * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; /** * Enumerates the values on this array with the given block. * * @param opts Options to control the enumeration. * @param block The block to enumerate with. * **value**: The current value being enumerated. * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Adds a value to this array. * * @param value The value to add to this array. **/ - (void)addValue:(int32_t)value; /** * Adds values to this array. * * @param values The values to add to this array. * @param count The number of elements to add. **/ - (void)addValues:(const int32_t [])values count:(NSUInteger)count; /** * Inserts a value into the given position. * * @param value The value to add to this array. * @param index The index into which to insert the value. **/ - (void)insertValue:(int32_t)value atIndex:(NSUInteger)index; /** * Replaces the value at the given index with the given value. * * @param index The index for which to replace the value. * @param value The value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value; // These methods bypass the validationFunc to provide setting of values that were not // known at the time the binary was compiled. /** * Adds a raw enum value to this array. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param value The raw enum value to add to the array. **/ - (void)addRawValue:(int32_t)value; /** * Adds raw enum values to this array. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param array Array containing the raw enum values to add to this array. **/ - (void)addRawValuesFromArray:(GPBEnumArray *)array; /** * Adds raw enum values to this array. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param values Array containing the raw enum values to add to this array. * @param count The number of raw values to add. **/ - (void)addRawValues:(const int32_t [])values count:(NSUInteger)count; /** * Inserts a raw enum value at the given index. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param value Raw enum value to add. * @param index The index into which to insert the value. **/ - (void)insertRawValue:(int32_t)value atIndex:(NSUInteger)index; /** * Replaces the raw enum value at the given index with the given value. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param index The index for which to replace the value. * @param value The raw enum value to replace with. **/ - (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(int32_t)value; // No validation applies to these methods. /** * Removes the value at the given index. * * @param index The index of the value to remove. **/ - (void)removeValueAtIndex:(NSUInteger)index; /** * Removes all the values from this array. **/ - (void)removeAll; /** * Exchanges the values between the given indexes. * * @param idx1 The index of the first element to exchange. * @param idx2 The index of the second element to exchange. **/ - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2; @end //%PDDM-EXPAND-END DECLARE_ARRAYS() NS_ASSUME_NONNULL_END //%PDDM-DEFINE DECLARE_ARRAYS() //%ARRAY_INTERFACE_SIMPLE(Int32, int32_t) //%ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t) //%ARRAY_INTERFACE_SIMPLE(Int64, int64_t) //%ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t) //%ARRAY_INTERFACE_SIMPLE(Float, float) //%ARRAY_INTERFACE_SIMPLE(Double, double) //%ARRAY_INTERFACE_SIMPLE(Bool, BOOL) //%ARRAY_INTERFACE_ENUM(Enum, int32_t) // // The common case (everything but Enum) // //%PDDM-DEFINE ARRAY_INTERFACE_SIMPLE(NAME, TYPE) //%#pragma mark - NAME //% //%/** //% * Class used for repeated fields of ##TYPE## values. This performs better than //% * boxing into NSNumbers in NSArrays. //% * //% * @note This class is not meant to be subclassed. //% **/ //%@interface GPB##NAME##Array : NSObject //% //%/** The number of elements contained in the array. */ //%@property(nonatomic, readonly) NSUInteger count; //% //%/** //% * @return A newly instanced and empty GPB##NAME##Array. //% **/ //%+ (instancetype)array; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the single element given. //% * //% * @param value The value to be placed in the array. //% * //% * @return A newly instanced GPB##NAME##Array with value in it. //% **/ //%+ (instancetype)arrayWithValue:(TYPE)value; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the contents of the given //% * array. //% * //% * @param array Array with the contents to be put into the new array. //% * //% * @return A newly instanced GPB##NAME##Array with the contents of array. //% **/ //%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the given capacity. //% * //% * @param count The capacity needed for the array. //% * //% * @return A newly instanced GPB##NAME##Array with a capacity of count. //% **/ //%+ (instancetype)arrayWithCapacity:(NSUInteger)count; //% //%/** //% * @return A newly initialized and empty GPB##NAME##Array. //% **/ //%- (instancetype)init NS_DESIGNATED_INITIALIZER; //% //%/** //% * Initializes the array, copying the given values. //% * //% * @param values An array with the values to put inside this array. //% * @param count The number of elements to copy into the array. //% * //% * @return A newly initialized GPB##NAME##Array with a copy of the values. //% **/ //%- (instancetype)initWithValues:(const TYPE [])values //% count:(NSUInteger)count; //% //%/** //% * Initializes the array, copying the given values. //% * //% * @param array An array with the values to put inside this array. //% * //% * @return A newly initialized GPB##NAME##Array with a copy of the values. //% **/ //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; //% //%/** //% * Initializes the array with the given capacity. //% * //% * @param count The capacity needed for the array. //% * //% * @return A newly initialized GPB##NAME##Array with a capacity of count. //% **/ //%- (instancetype)initWithCapacity:(NSUInteger)count; //% //%ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, Basic) //% //%ARRAY_MUTABLE_INTERFACE(NAME, TYPE, Basic) //% //%@end //% // // Macros specific to Enums (to tweak their interface). // //%PDDM-DEFINE ARRAY_INTERFACE_ENUM(NAME, TYPE) //%#pragma mark - NAME //% //%/** //% * This class is used for repeated fields of ##TYPE## values. This performs //% * better than boxing into NSNumbers in NSArrays. //% * //% * @note This class is not meant to be subclassed. //% **/ //%@interface GPB##NAME##Array : NSObject //% //%/** The number of elements contained in the array. */ //%@property(nonatomic, readonly) NSUInteger count; //%/** The validation function to check if the enums are valid. */ //%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; //% //%/** //% * @return A newly instanced and empty GPB##NAME##Array. //% **/ //%+ (instancetype)array; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the enum validation function //% * given. //% * //% * @param func The enum validation function for the array. //% * //% * @return A newly instanced GPB##NAME##Array. //% **/ //%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the enum validation function //% * given and the single raw value given. //% * //% * @param func The enum validation function for the array. //% * @param value The raw value to add to this array. //% * //% * @return A newly instanced GPB##NAME##Array. //% **/ //%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValue:(TYPE)value; //% //%/** //% * Creates and initializes a GPB##NAME##Array that adds the elements from the //% * given array. //% * //% * @param array Array containing the values to add to the new array. //% * //% * @return A newly instanced GPB##NAME##Array. //% **/ //%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array; //% //%/** //% * Creates and initializes a GPB##NAME##Array with the given enum validation //% * function and with the givencapacity. //% * //% * @param func The enum validation function for the array. //% * @param count The capacity needed for the array. //% * //% * @return A newly instanced GPB##NAME##Array with a capacity of count. //% **/ //%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)count; //% //%/** //% * Initializes the array with the given enum validation function. //% * //% * @param func The enum validation function for the array. //% * //% * @return A newly initialized GPB##NAME##Array with a copy of the values. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% NS_DESIGNATED_INITIALIZER; //% //%/** //% * Initializes the array, copying the given values. //% * //% * @param func The enum validation function for the array. //% * @param values An array with the values to put inside this array. //% * @param count The number of elements to copy into the array. //% * //% * @return A newly initialized GPB##NAME##Array with a copy of the values. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValues:(const TYPE [])values //% count:(NSUInteger)count; //% //%/** //% * Initializes the array, copying the given values. //% * //% * @param array An array with the values to put inside this array. //% * //% * @return A newly initialized GPB##NAME##Array with a copy of the values. //% **/ //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array; //% //%/** //% * Initializes the array with the given capacity. //% * //% * @param func The enum validation function for the array. //% * @param count The capacity needed for the array. //% * //% * @return A newly initialized GPB##NAME##Array with a capacity of count. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)count; //% //%// These will return kGPBUnrecognizedEnumeratorValue if the value at index is not a //%// valid enumerator as defined by validationFunc. If the actual value is //%// desired, use "raw" version of the method. //% //%ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, NAME) //% //%// These methods bypass the validationFunc to provide access to values that were not //%// known at the time the binary was compiled. //% //%/** //% * Gets the raw enum value at the given index. //% * //% * @param index The index of the raw enum value to get. //% * //% * @return The raw enum value at the given index. //% **/ //%- (TYPE)rawValueAtIndex:(NSUInteger)index; //% //%/** //% * Enumerates the values on this array with the given block. //% * //% * @param block The block to enumerate with. //% * **value**: The current value being enumerated. //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateRawValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; //% //%/** //% * Enumerates the values on this array with the given block. //% * //% * @param opts Options to control the enumeration. //% * @param block The block to enumerate with. //% * **value**: The current value being enumerated. //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts //% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; //% //%// If value is not a valid enumerator as defined by validationFunc, these //%// methods will assert in debug, and will log in release and assign the value //%// to the default value. Use the rawValue methods below to assign non enumerator //%// values. //% //%ARRAY_MUTABLE_INTERFACE(NAME, TYPE, NAME) //% //%@end //% //%PDDM-DEFINE ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME) //%/** //% * Gets the value at the given index. //% * //% * @param index The index of the value to get. //% * //% * @return The value at the given index. //% **/ //%- (TYPE)valueAtIndex:(NSUInteger)index; //% //%/** //% * Enumerates the values on this array with the given block. //% * //% * @param block The block to enumerate with. //% * **value**: The current value being enumerated. //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; //% //%/** //% * Enumerates the values on this array with the given block. //% * //% * @param opts Options to control the enumeration. //% * @param block The block to enumerate with. //% * **value**: The current value being enumerated. //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts //% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block; //%PDDM-DEFINE ARRAY_MUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME) //%/** //% * Adds a value to this array. //% * //% * @param value The value to add to this array. //% **/ //%- (void)addValue:(TYPE)value; //% //%/** //% * Adds values to this array. //% * //% * @param values The values to add to this array. //% * @param count The number of elements to add. //% **/ //%- (void)addValues:(const TYPE [])values count:(NSUInteger)count; //% //%ARRAY_EXTRA_MUTABLE_METHODS1_##HELPER_NAME(NAME, TYPE) //%/** //% * Inserts a value into the given position. //% * //% * @param value The value to add to this array. //% * @param index The index into which to insert the value. //% **/ //%- (void)insertValue:(TYPE)value atIndex:(NSUInteger)index; //% //%/** //% * Replaces the value at the given index with the given value. //% * //% * @param index The index for which to replace the value. //% * @param value The value to replace with. //% **/ //%- (void)replaceValueAtIndex:(NSUInteger)index withValue:(TYPE)value; //%ARRAY_EXTRA_MUTABLE_METHODS2_##HELPER_NAME(NAME, TYPE) //%/** //% * Removes the value at the given index. //% * //% * @param index The index of the value to remove. //% **/ //%- (void)removeValueAtIndex:(NSUInteger)index; //% //%/** //% * Removes all the values from this array. //% **/ //%- (void)removeAll; //% //%/** //% * Exchanges the values between the given indexes. //% * //% * @param idx1 The index of the first element to exchange. //% * @param idx2 The index of the second element to exchange. //% **/ //%- (void)exchangeValueAtIndex:(NSUInteger)idx1 //% withValueAtIndex:(NSUInteger)idx2; // // These are hooks invoked by the above to do insert as needed. // //%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS1_Basic(NAME, TYPE) //%/** //% * Adds the values from the given array to this array. //% * //% * @param array The array containing the elements to add to this array. //% **/ //%- (void)addValuesFromArray:(GPB##NAME##Array *)array; //% //%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS2_Basic(NAME, TYPE) // Empty //%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS1_Enum(NAME, TYPE) // Empty //%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS2_Enum(NAME, TYPE) //% //%// These methods bypass the validationFunc to provide setting of values that were not //%// known at the time the binary was compiled. //% //%/** //% * Adds a raw enum value to this array. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param value The raw enum value to add to the array. //% **/ //%- (void)addRawValue:(TYPE)value; //% //%/** //% * Adds raw enum values to this array. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param array Array containing the raw enum values to add to this array. //% **/ //%- (void)addRawValuesFromArray:(GPB##NAME##Array *)array; //% //%/** //% * Adds raw enum values to this array. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param values Array containing the raw enum values to add to this array. //% * @param count The number of raw values to add. //% **/ //%- (void)addRawValues:(const TYPE [])values count:(NSUInteger)count; //% //%/** //% * Inserts a raw enum value at the given index. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param value Raw enum value to add. //% * @param index The index into which to insert the value. //% **/ //%- (void)insertRawValue:(TYPE)value atIndex:(NSUInteger)index; //% //%/** //% * Replaces the raw enum value at the given index with the given value. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param index The index for which to replace the value. //% * @param value The raw enum value to replace with. //% **/ //%- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(TYPE)value; //% //%// No validation applies to these methods. //% ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBArray.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBArray_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" // Mutable arrays use an internal buffer that can always hold a multiple of this elements. #define kChunkSize 16 #define CapacityFromCount(x) (((x / kChunkSize) + 1) * kChunkSize) static BOOL ArrayDefault_IsValidValue(int32_t value) { // Anything but the bad value marker is allowed. return (value != kGPBUnrecognizedEnumeratorValue); } //%PDDM-DEFINE VALIDATE_RANGE(INDEX, COUNT) //% if (INDEX >= COUNT) { //% [NSException raise:NSRangeException //% format:@"Index (%lu) beyond bounds (%lu)", //% (unsigned long)INDEX, (unsigned long)COUNT]; //% } //%PDDM-DEFINE MAYBE_GROW_TO_SET_COUNT(NEW_COUNT) //% if (NEW_COUNT > _capacity) { //% [self internalResizeToCapacity:CapacityFromCount(NEW_COUNT)]; //% } //% _count = NEW_COUNT; //%PDDM-DEFINE SET_COUNT_AND_MAYBE_SHRINK(NEW_COUNT) //% _count = NEW_COUNT; //% if ((NEW_COUNT + (2 * kChunkSize)) < _capacity) { //% [self internalResizeToCapacity:CapacityFromCount(NEW_COUNT)]; //% } // // Macros for the common basic cases. // //%PDDM-DEFINE ARRAY_INTERFACE_SIMPLE(NAME, TYPE, FORMAT) //%#pragma mark - NAME //% //%@implementation GPB##NAME##Array { //% @package //% TYPE *_values; //% NSUInteger _count; //% NSUInteger _capacity; //%} //% //%@synthesize count = _count; //% //%+ (instancetype)array { //% return [[[self alloc] init] autorelease]; //%} //% //%+ (instancetype)arrayWithValue:(TYPE)value { //% // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get //% // the type correct. //% return [[(GPB##NAME##Array*)[self alloc] initWithValues:&value count:1] autorelease]; //%} //% //%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array { //% return [[(GPB##NAME##Array*)[self alloc] initWithValueArray:array] autorelease]; //%} //% //%+ (instancetype)arrayWithCapacity:(NSUInteger)count { //% return [[[self alloc] initWithCapacity:count] autorelease]; //%} //% //%- (instancetype)init { //% self = [super init]; //% // No work needed; //% return self; //%} //% //%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array { //% return [self initWithValues:array->_values count:array->_count]; //%} //% //%- (instancetype)initWithValues:(const TYPE [])values count:(NSUInteger)count { //% self = [self init]; //% if (self) { //% if (count && values) { //% _values = reallocf(_values, count * sizeof(TYPE)); //% if (_values != NULL) { //% _capacity = count; //% memcpy(_values, values, count * sizeof(TYPE)); //% _count = count; //% } else { //% [self release]; //% [NSException raise:NSMallocException //% format:@"Failed to allocate %lu bytes", //% (unsigned long)(count * sizeof(TYPE))]; //% } //% } //% } //% return self; //%} //% //%- (instancetype)initWithCapacity:(NSUInteger)count { //% self = [self initWithValues:NULL count:0]; //% if (self && count) { //% [self internalResizeToCapacity:count]; //% } //% return self; //%} //% //%- (instancetype)copyWithZone:(NSZone *)zone { //% return [[GPB##NAME##Array allocWithZone:zone] initWithValues:_values count:_count]; //%} //% //%ARRAY_IMMUTABLE_CORE(NAME, TYPE, , FORMAT) //% //%- (TYPE)valueAtIndex:(NSUInteger)index { //%VALIDATE_RANGE(index, _count) //% return _values[index]; //%} //% //%ARRAY_MUTABLE_CORE(NAME, TYPE, , FORMAT) //%@end //% // // Some core macros used for both the simple types and Enums. // //%PDDM-DEFINE ARRAY_IMMUTABLE_CORE(NAME, TYPE, ACCESSOR_NAME, FORMAT) //%- (void)dealloc { //% NSAssert(!_autocreator, //% @"%@: Autocreator must be cleared before release, autocreator: %@", //% [self class], _autocreator); //% free(_values); //% [super dealloc]; //%} //% //%- (BOOL)isEqual:(id)other { //% if (self == other) { //% return YES; //% } //% if (![other isKindOfClass:[GPB##NAME##Array class]]) { //% return NO; //% } //% GPB##NAME##Array *otherArray = other; //% return (_count == otherArray->_count //% && memcmp(_values, otherArray->_values, (_count * sizeof(TYPE))) == 0); //%} //% //%- (NSUInteger)hash { //% // Follow NSArray's lead, and use the count as the hash. //% return _count; //%} //% //%- (NSString *)description { //% NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; //% for (NSUInteger i = 0, count = _count; i < count; ++i) { //% if (i == 0) { //% [result appendFormat:@"##FORMAT##", _values[i]]; //% } else { //% [result appendFormat:@", ##FORMAT##", _values[i]]; //% } //% } //% [result appendFormat:@" }"]; //% return result; //%} //% //%- (void)enumerate##ACCESSOR_NAME##ValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block { //% [self enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; //%} //% //%- (void)enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)opts //% ACCESSOR_NAME$S usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block { //% // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). //% BOOL stop = NO; //% if ((opts & NSEnumerationReverse) == 0) { //% for (NSUInteger i = 0, count = _count; i < count; ++i) { //% block(_values[i], i, &stop); //% if (stop) break; //% } //% } else if (_count > 0) { //% for (NSUInteger i = _count; i > 0; --i) { //% block(_values[i - 1], (i - 1), &stop); //% if (stop) break; //% } //% } //%} //%PDDM-DEFINE MUTATION_HOOK_None() //%PDDM-DEFINE MUTATION_METHODS(NAME, TYPE, ACCESSOR_NAME, HOOK_1, HOOK_2) //%- (void)add##ACCESSOR_NAME##Value:(TYPE)value { //% [self add##ACCESSOR_NAME##Values:&value count:1]; //%} //% //%- (void)add##ACCESSOR_NAME##Values:(const TYPE [])values count:(NSUInteger)count { //% if (values == NULL || count == 0) return; //%MUTATION_HOOK_##HOOK_1() NSUInteger initialCount = _count; //% NSUInteger newCount = initialCount + count; //%MAYBE_GROW_TO_SET_COUNT(newCount) //% memcpy(&_values[initialCount], values, count * sizeof(TYPE)); //% if (_autocreator) { //% GPBAutocreatedArrayModified(_autocreator, self); //% } //%} //% //%- (void)insert##ACCESSOR_NAME##Value:(TYPE)value atIndex:(NSUInteger)index { //%VALIDATE_RANGE(index, _count + 1) //%MUTATION_HOOK_##HOOK_2() NSUInteger initialCount = _count; //% NSUInteger newCount = initialCount + 1; //%MAYBE_GROW_TO_SET_COUNT(newCount) //% if (index != initialCount) { //% memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(TYPE)); //% } //% _values[index] = value; //% if (_autocreator) { //% GPBAutocreatedArrayModified(_autocreator, self); //% } //%} //% //%- (void)replaceValueAtIndex:(NSUInteger)index with##ACCESSOR_NAME##Value:(TYPE)value { //%VALIDATE_RANGE(index, _count) //%MUTATION_HOOK_##HOOK_2() _values[index] = value; //%} //%PDDM-DEFINE ARRAY_MUTABLE_CORE(NAME, TYPE, ACCESSOR_NAME, FORMAT) //%- (void)internalResizeToCapacity:(NSUInteger)newCapacity { //% _values = reallocf(_values, newCapacity * sizeof(TYPE)); //% if (_values == NULL) { //% _capacity = 0; //% _count = 0; //% [NSException raise:NSMallocException //% format:@"Failed to allocate %lu bytes", //% (unsigned long)(newCapacity * sizeof(TYPE))]; //% } //% _capacity = newCapacity; //%} //% //%MUTATION_METHODS(NAME, TYPE, ACCESSOR_NAME, None, None) //% //%- (void)add##ACCESSOR_NAME##ValuesFromArray:(GPB##NAME##Array *)array { //% [self add##ACCESSOR_NAME##Values:array->_values count:array->_count]; //%} //% //%- (void)removeValueAtIndex:(NSUInteger)index { //%VALIDATE_RANGE(index, _count) //% NSUInteger newCount = _count - 1; //% if (index != newCount) { //% memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(TYPE)); //% } //%SET_COUNT_AND_MAYBE_SHRINK(newCount) //%} //% //%- (void)removeAll { //%SET_COUNT_AND_MAYBE_SHRINK(0) //%} //% //%- (void)exchangeValueAtIndex:(NSUInteger)idx1 //% withValueAtIndex:(NSUInteger)idx2 { //%VALIDATE_RANGE(idx1, _count) //%VALIDATE_RANGE(idx2, _count) //% TYPE temp = _values[idx1]; //% _values[idx1] = _values[idx2]; //% _values[idx2] = temp; //%} //% //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int32, int32_t, %d) // This block of code is generated, do not edit it directly. #pragma mark - Int32 @implementation GPBInt32Array { @package int32_t *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(int32_t)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBInt32Array*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBInt32Array *)array { return [[(GPBInt32Array*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBInt32Array *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const int32_t [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(int32_t)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int32_t)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int32_t))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32Array allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32Array class]]) { return NO; } GPBInt32Array *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(int32_t))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%d", _values[i]]; } else { [result appendFormat:@", %d", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (int32_t)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(int32_t)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(int32_t))]; } _capacity = newCapacity; } - (void)addValue:(int32_t)value { [self addValues:&value count:1]; } - (void)addValues:(const int32_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(int32_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(int32_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBInt32Array *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int32_t)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } int32_t temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t, %u) // This block of code is generated, do not edit it directly. #pragma mark - UInt32 @implementation GPBUInt32Array { @package uint32_t *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(uint32_t)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBUInt32Array*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBUInt32Array *)array { return [[(GPBUInt32Array*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBUInt32Array *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const uint32_t [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(uint32_t)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(uint32_t)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(uint32_t))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32Array allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32Array class]]) { return NO; } GPBUInt32Array *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(uint32_t))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%u", _values[i]]; } else { [result appendFormat:@", %u", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (uint32_t)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(uint32_t)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(uint32_t))]; } _capacity = newCapacity; } - (void)addValue:(uint32_t)value { [self addValues:&value count:1]; } - (void)addValues:(const uint32_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(uint32_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(uint32_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(uint32_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint32_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBUInt32Array *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(uint32_t)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } uint32_t temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int64, int64_t, %lld) // This block of code is generated, do not edit it directly. #pragma mark - Int64 @implementation GPBInt64Array { @package int64_t *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(int64_t)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBInt64Array*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBInt64Array *)array { return [[(GPBInt64Array*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBInt64Array *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const int64_t [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(int64_t)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int64_t)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int64_t))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64Array allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64Array class]]) { return NO; } GPBInt64Array *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(int64_t))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%lld", _values[i]]; } else { [result appendFormat:@", %lld", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (int64_t)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(int64_t)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(int64_t))]; } _capacity = newCapacity; } - (void)addValue:(int64_t)value { [self addValues:&value count:1]; } - (void)addValues:(const int64_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(int64_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(int64_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int64_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int64_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBInt64Array *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int64_t)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } int64_t temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t, %llu) // This block of code is generated, do not edit it directly. #pragma mark - UInt64 @implementation GPBUInt64Array { @package uint64_t *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(uint64_t)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBUInt64Array*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBUInt64Array *)array { return [[(GPBUInt64Array*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBUInt64Array *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const uint64_t [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(uint64_t)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(uint64_t)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(uint64_t))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64Array allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64Array class]]) { return NO; } GPBUInt64Array *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(uint64_t))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%llu", _values[i]]; } else { [result appendFormat:@", %llu", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (uint64_t)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(uint64_t)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(uint64_t))]; } _capacity = newCapacity; } - (void)addValue:(uint64_t)value { [self addValues:&value count:1]; } - (void)addValues:(const uint64_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(uint64_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(uint64_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(uint64_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint64_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBUInt64Array *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(uint64_t)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } uint64_t temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Float, float, %f) // This block of code is generated, do not edit it directly. #pragma mark - Float @implementation GPBFloatArray { @package float *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(float)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBFloatArray*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBFloatArray *)array { return [[(GPBFloatArray*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBFloatArray *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const float [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(float)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(float)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(float))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBFloatArray allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBFloatArray class]]) { return NO; } GPBFloatArray *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(float))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%f", _values[i]]; } else { [result appendFormat:@", %f", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (float)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(float)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(float))]; } _capacity = newCapacity; } - (void)addValue:(float)value { [self addValues:&value count:1]; } - (void)addValues:(const float [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(float)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(float)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(float)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(float)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBFloatArray *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(float)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } float temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Double, double, %lf) // This block of code is generated, do not edit it directly. #pragma mark - Double @implementation GPBDoubleArray { @package double *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(double)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBDoubleArray*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBDoubleArray *)array { return [[(GPBDoubleArray*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBDoubleArray *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const double [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(double)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(double)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(double))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBDoubleArray allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBDoubleArray class]]) { return NO; } GPBDoubleArray *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(double))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%lf", _values[i]]; } else { [result appendFormat:@", %lf", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (double)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(double)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(double))]; } _capacity = newCapacity; } - (void)addValue:(double)value { [self addValues:&value count:1]; } - (void)addValues:(const double [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(double)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(double)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(double)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(double)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBDoubleArray *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(double)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } double temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Bool, BOOL, %d) // This block of code is generated, do not edit it directly. #pragma mark - Bool @implementation GPBBoolArray { @package BOOL *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; + (instancetype)array { return [[[self alloc] init] autorelease]; } + (instancetype)arrayWithValue:(BOOL)value { // Cast is needed so the compiler knows what class we are invoking initWithValues: on to get // the type correct. return [[(GPBBoolArray*)[self alloc] initWithValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBBoolArray *)array { return [[(GPBBoolArray*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithCapacity:(NSUInteger)count { return [[[self alloc] initWithCapacity:count] autorelease]; } - (instancetype)init { self = [super init]; // No work needed; return self; } - (instancetype)initWithValueArray:(GPBBoolArray *)array { return [self initWithValues:array->_values count:array->_count]; } - (instancetype)initWithValues:(const BOOL [])values count:(NSUInteger)count { self = [self init]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(BOOL)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(BOOL)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(BOOL))]; } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)count { self = [self initWithValues:NULL count:0]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolArray allocWithZone:zone] initWithValues:_values count:_count]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolArray class]]) { return NO; } GPBBoolArray *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(BOOL))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%d", _values[i]]; } else { [result appendFormat:@", %d", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } - (BOOL)valueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } return _values[index]; } - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(BOOL)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(BOOL))]; } _capacity = newCapacity; } - (void)addValue:(BOOL)value { [self addValues:&value count:1]; } - (void)addValues:(const BOOL [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(BOOL)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(BOOL)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(BOOL)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(BOOL)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addValuesFromArray:(GPBBoolArray *)array { [self addValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(BOOL)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } BOOL temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } @end //%PDDM-EXPAND-END (7 expansions) #pragma mark - Enum @implementation GPBEnumArray { @package GPBEnumValidationFunc _validationFunc; int32_t *_values; NSUInteger _count; NSUInteger _capacity; } @synthesize count = _count; @synthesize validationFunc = _validationFunc; + (instancetype)array { return [[[self alloc] initWithValidationFunction:NULL] autorelease]; } + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func] autorelease]; } + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)value { return [[[self alloc] initWithValidationFunction:func rawValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBEnumArray *)array { return [[(GPBEnumArray*)[self alloc] initWithValueArray:array] autorelease]; } + (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count { return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL]; } - (instancetype)initWithValueArray:(GPBEnumArray *)array { return [self initWithValidationFunction:array->_validationFunc rawValues:array->_values count:array->_count]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { self = [super init]; if (self) { _validationFunc = (func != NULL ? func : ArrayDefault_IsValidValue); } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])values count:(NSUInteger)count { self = [self initWithValidationFunction:func]; if (self) { if (count && values) { _values = reallocf(_values, count * sizeof(int32_t)); if (_values != NULL) { _capacity = count; memcpy(_values, values, count * sizeof(int32_t)); _count = count; } else { [self release]; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int32_t))]; } } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count { self = [self initWithValidationFunction:func]; if (self && count) { [self internalResizeToCapacity:count]; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBEnumArray allocWithZone:zone] initWithValidationFunction:_validationFunc rawValues:_values count:_count]; } //%PDDM-EXPAND ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) // This block of code is generated, do not edit it directly. - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); free(_values); [super dealloc]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBEnumArray class]]) { return NO; } GPBEnumArray *otherArray = other; return (_count == otherArray->_count && memcmp(_values, otherArray->_values, (_count * sizeof(int32_t))) == 0); } - (NSUInteger)hash { // Follow NSArray's lead, and use the count as the hash. return _count; } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> { ", [self class], self]; for (NSUInteger i = 0, count = _count; i < count; ++i) { if (i == 0) { [result appendFormat:@"%d", _values[i]]; } else { [result appendFormat:@", %d", _values[i]]; } } [result appendFormat:@" }"]; return result; } - (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateRawValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { for (NSUInteger i = 0, count = _count; i < count; ++i) { block(_values[i], i, &stop); if (stop) break; } } else if (_count > 0) { for (NSUInteger i = _count; i > 0; --i) { block(_values[i - 1], (i - 1), &stop); if (stop) break; } } } //%PDDM-EXPAND-END ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) - (int32_t)valueAtIndex:(NSUInteger)index { //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) int32_t result = _values[index]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } return result; } - (int32_t)rawValueAtIndex:(NSUInteger)index { //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) return _values[index]; } - (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; GPBEnumValidationFunc func = _validationFunc; if ((opts & NSEnumerationReverse) == 0) { int32_t *scan = _values; int32_t *end = scan + _count; for (NSUInteger i = 0; scan < end; ++i, ++scan) { int32_t value = *scan; if (!func(value)) { value = kGPBUnrecognizedEnumeratorValue; } block(value, i, &stop); if (stop) break; } } else if (_count > 0) { int32_t *end = _values; int32_t *scan = end + (_count - 1); for (NSUInteger i = (_count - 1); scan >= end; --i, --scan) { int32_t value = *scan; if (!func(value)) { value = kGPBUnrecognizedEnumeratorValue; } block(value, i, &stop); if (stop) break; } } } //%PDDM-EXPAND ARRAY_MUTABLE_CORE(Enum, int32_t, Raw, %d) // This block of code is generated, do not edit it directly. - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(int32_t)); if (_values == NULL) { _capacity = 0; _count = 0; [NSException raise:NSMallocException format:@"Failed to allocate %lu bytes", (unsigned long)(newCapacity * sizeof(int32_t))]; } _capacity = newCapacity; } - (void)addRawValue:(int32_t)value { [self addRawValues:&value count:1]; } - (void)addRawValues:(const int32_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(int32_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertRawValue:(int32_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(int32_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } _values[index] = value; } - (void)addRawValuesFromArray:(GPBEnumArray *)array { [self addRawValues:array->_values count:array->_count]; } - (void)removeValueAtIndex:(NSUInteger)index { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } NSUInteger newCount = _count - 1; if (index != newCount) { memmove(&_values[index], &_values[index + 1], (newCount - index) * sizeof(int32_t)); } _count = newCount; if ((newCount + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } } - (void)removeAll { _count = 0; if ((0 + (2 * kChunkSize)) < _capacity) { [self internalResizeToCapacity:CapacityFromCount(0)]; } } - (void)exchangeValueAtIndex:(NSUInteger)idx1 withValueAtIndex:(NSUInteger)idx2 { if (idx1 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx1, (unsigned long)_count]; } if (idx2 >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)idx2, (unsigned long)_count]; } int32_t temp = _values[idx1]; _values[idx1] = _values[idx2]; _values[idx2] = temp; } //%PDDM-EXPAND MUTATION_METHODS(Enum, int32_t, , EnumValidationList, EnumValidationOne) // This block of code is generated, do not edit it directly. - (void)addValue:(int32_t)value { [self addValues:&value count:1]; } - (void)addValues:(const int32_t [])values count:(NSUInteger)count { if (values == NULL || count == 0) return; GPBEnumValidationFunc func = _validationFunc; for (NSUInteger i = 0; i < count; ++i) { if (!func(values[i])) { [NSException raise:NSInvalidArgumentException format:@"%@: Attempt to set an unknown enum value (%d)", [self class], values[i]]; } } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + count; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; memcpy(&_values[initialCount], values, count * sizeof(int32_t)); if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)insertValue:(int32_t)value atIndex:(NSUInteger)index { if (index >= _count + 1) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count + 1]; } if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"%@: Attempt to set an unknown enum value (%d)", [self class], value]; } NSUInteger initialCount = _count; NSUInteger newCount = initialCount + 1; if (newCount > _capacity) { [self internalResizeToCapacity:CapacityFromCount(newCount)]; } _count = newCount; if (index != initialCount) { memmove(&_values[index + 1], &_values[index], (initialCount - index) * sizeof(int32_t)); } _values[index] = value; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value { if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"%@: Attempt to set an unknown enum value (%d)", [self class], value]; } _values[index] = value; } //%PDDM-EXPAND-END (2 expansions) //%PDDM-DEFINE MUTATION_HOOK_EnumValidationList() //% GPBEnumValidationFunc func = _validationFunc; //% for (NSUInteger i = 0; i < count; ++i) { //% if (!func(values[i])) { //% [NSException raise:NSInvalidArgumentException //% format:@"%@: Attempt to set an unknown enum value (%d)", //% [self class], values[i]]; //% } //% } //% //%PDDM-DEFINE MUTATION_HOOK_EnumValidationOne() //% if (!_validationFunc(value)) { //% [NSException raise:NSInvalidArgumentException //% format:@"%@: Attempt to set an unknown enum value (%d)", //% [self class], value]; //% } //% @end #pragma mark - NSArray Subclass @implementation GPBAutocreatedArray { NSMutableArray *_array; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_array release]; [super dealloc]; } #pragma mark Required NSArray overrides - (NSUInteger)count { return [_array count]; } - (id)objectAtIndex:(NSUInteger)idx { return [_array objectAtIndex:idx]; } #pragma mark Required NSMutableArray overrides // Only need to call GPBAutocreatedArrayModified() when adding things since // we only autocreate empty arrays. - (void)insertObject:(id)anObject atIndex:(NSUInteger)idx { if (_array == nil) { _array = [[NSMutableArray alloc] init]; } [_array insertObject:anObject atIndex:idx]; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)removeObject:(id)anObject { [_array removeObject:anObject]; } - (void)removeObjectAtIndex:(NSUInteger)idx { [_array removeObjectAtIndex:idx]; } - (void)addObject:(id)anObject { if (_array == nil) { _array = [[NSMutableArray alloc] init]; } [_array addObject:anObject]; if (_autocreator) { GPBAutocreatedArrayModified(_autocreator, self); } } - (void)removeLastObject { [_array removeLastObject]; } - (void)replaceObjectAtIndex:(NSUInteger)idx withObject:(id)anObject { [_array replaceObjectAtIndex:idx withObject:anObject]; } #pragma mark Extra things hooked - (id)copyWithZone:(NSZone *)zone { if (_array == nil) { return [[NSMutableArray allocWithZone:zone] init]; } return [_array copyWithZone:zone]; } - (id)mutableCopyWithZone:(NSZone *)zone { if (_array == nil) { return [[NSMutableArray allocWithZone:zone] init]; } return [_array mutableCopyWithZone:zone]; } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len { return [_array countByEnumeratingWithState:state objects:buffer count:len]; } - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { [_array enumerateObjectsUsingBlock:block]; } - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { [_array enumerateObjectsWithOptions:opts usingBlock:block]; } @end #pragma clang diagnostic pop ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBArray_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBArray.h" @class GPBMessage; //%PDDM-DEFINE DECLARE_ARRAY_EXTRAS() //%ARRAY_INTERFACE_EXTRAS(Int32, int32_t) //%ARRAY_INTERFACE_EXTRAS(UInt32, uint32_t) //%ARRAY_INTERFACE_EXTRAS(Int64, int64_t) //%ARRAY_INTERFACE_EXTRAS(UInt64, uint64_t) //%ARRAY_INTERFACE_EXTRAS(Float, float) //%ARRAY_INTERFACE_EXTRAS(Double, double) //%ARRAY_INTERFACE_EXTRAS(Bool, BOOL) //%ARRAY_INTERFACE_EXTRAS(Enum, int32_t) //%PDDM-DEFINE ARRAY_INTERFACE_EXTRAS(NAME, TYPE) //%#pragma mark - NAME //% //%@interface GPB##NAME##Array () { //% @package //% GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; //%} //%@end //% //%PDDM-EXPAND DECLARE_ARRAY_EXTRAS() // This block of code is generated, do not edit it directly. #pragma mark - Int32 @interface GPBInt32Array () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - UInt32 @interface GPBUInt32Array () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Int64 @interface GPBInt64Array () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - UInt64 @interface GPBUInt64Array () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Float @interface GPBFloatArray () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Double @interface GPBDoubleArray () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Bool @interface GPBBoolArray () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Enum @interface GPBEnumArray () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end //%PDDM-EXPAND-END DECLARE_ARRAY_EXTRAS() #pragma mark - NSArray Subclass @interface GPBAutocreatedArray : NSMutableArray { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBBootstrap.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * The Objective C runtime has complete enough info that most protos don’t end * up using this, so leaving it on is no cost or very little cost. If you * happen to see it causing bloat, this is the way to disable it. If you do * need to disable it, try only disabling it for Release builds as having * full TextFormat can be useful for debugging. **/ #ifndef GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS #define GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS 0 #endif // Used in the generated code to give sizes to enums. int32_t was chosen based // on the fact that Protocol Buffers enums are limited to this range. #if !__has_feature(objc_fixed_enum) #error All supported Xcode versions should support objc_fixed_enum. #endif // If the headers are imported into Objective-C++, we can run into an issue // where the defintion of NS_ENUM (really CF_ENUM) changes based on the C++ // standard that is in effect. If it isn't C++11 or higher, the definition // doesn't allow us to forward declare. We work around this one case by // providing a local definition. The default case has to use NS_ENUM for the // magic that is Swift bridging of enums. #if (defined(__cplusplus) && __cplusplus && __cplusplus < 201103L) #define GPB_ENUM(X) enum X : int32_t X; enum X : int32_t #else #define GPB_ENUM(X) NS_ENUM(int32_t, X) #endif /** * GPB_ENUM_FWD_DECLARE is used for forward declaring enums, for example: * * ``` * GPB_ENUM_FWD_DECLARE(Foo_Enum) * * @interface BarClass : NSObject * @property (nonatomic) enum Foo_Enum value; * - (void)bazMethod:(enum Foo_Enum):value; * @end * ``` **/ #define GPB_ENUM_FWD_DECLARE(X) enum X : int32_t /** * Based upon CF_INLINE. Forces inlining in non DEBUG builds. **/ #if !defined(DEBUG) #define GPB_INLINE static __inline__ __attribute__((always_inline)) #else #define GPB_INLINE static __inline__ #endif /** * For use in public headers that might need to deal with ARC. **/ #ifndef GPB_UNSAFE_UNRETAINED #if __has_feature(objc_arc) #define GPB_UNSAFE_UNRETAINED __unsafe_unretained #else #define GPB_UNSAFE_UNRETAINED #endif #endif // If property name starts with init we need to annotate it to get past ARC. // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 // // Meant to be used internally by generated code. #define GPB_METHOD_FAMILY_NONE __attribute__((objc_method_family(none))) // ---------------------------------------------------------------------------- // These version numbers are all internal to the ObjC Protobuf runtime; they // are used to ensure compatibility between the generated sources and the // headers being compiled against and/or the version of sources being run // against. // // They are all #defines so the values are captured into every .o file they // are used in and to allow comparisons in the preprocessor. // Current library runtime version. // - Gets bumped when the runtime makes changes to the interfaces between the // generated code and runtime (things added/removed, etc). #define GOOGLE_PROTOBUF_OBJC_VERSION 30002 // Minimum runtime version supported for compiling/running against. // - Gets changed when support for the older generated code is dropped. #define GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION 30001 // This is a legacy constant now frozen in time for old generated code. If // GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION ever gets moved above 30001 then // this should also change to break code compiled with an old runtime that // can't be supported any more. #define GOOGLE_PROTOBUF_OBJC_GEN_VERSION 30001 ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedInputStream.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import @class GPBMessage; @class GPBExtensionRegistry; NS_ASSUME_NONNULL_BEGIN CF_EXTERN_C_BEGIN /** * @c GPBCodedInputStream exception name. Exceptions raised from * @c GPBCodedInputStream contain an underlying error in the userInfo dictionary * under the GPBCodedInputStreamUnderlyingErrorKey key. **/ extern NSString *const GPBCodedInputStreamException; /** The key under which the underlying NSError from the exception is stored. */ extern NSString *const GPBCodedInputStreamUnderlyingErrorKey; /** NSError domain used for @c GPBCodedInputStream errors. */ extern NSString *const GPBCodedInputStreamErrorDomain; /** * Error code for NSError with @c GPBCodedInputStreamErrorDomain. **/ typedef NS_ENUM(NSInteger, GPBCodedInputStreamErrorCode) { /** The size does not fit in the remaining bytes to be read. */ GPBCodedInputStreamErrorInvalidSize = -100, /** Attempted to read beyond the subsection limit. */ GPBCodedInputStreamErrorSubsectionLimitReached = -101, /** The requested subsection limit is invalid. */ GPBCodedInputStreamErrorInvalidSubsectionLimit = -102, /** Invalid tag read. */ GPBCodedInputStreamErrorInvalidTag = -103, /** Invalid UTF-8 character in a string. */ GPBCodedInputStreamErrorInvalidUTF8 = -104, /** Invalid VarInt read. */ GPBCodedInputStreamErrorInvalidVarInt = -105, /** The maximum recursion depth of messages was exceeded. */ GPBCodedInputStreamErrorRecursionDepthExceeded = -106, }; CF_EXTERN_C_END /** * Reads and decodes protocol message fields. * * The common uses of protocol buffers shouldn't need to use this class. * @c GPBMessage's provide a @c +parseFromData:error: and * @c +parseFromData:extensionRegistry:error: method that will decode a * message for you. * * @note Subclassing of @c GPBCodedInputStream is NOT supported. **/ @interface GPBCodedInputStream : NSObject /** * Creates a new stream wrapping some data. * * @param data The data to wrap inside the stream. * * @return A newly instanced GPBCodedInputStream. **/ + (instancetype)streamWithData:(NSData *)data; /** * Initializes a stream wrapping some data. * * @param data The data to wrap inside the stream. * * @return A newly initialized GPBCodedInputStream. **/ - (instancetype)initWithData:(NSData *)data; /** * Attempts to read a field tag, returning zero if we have reached EOF. * Protocol message parsers use this to read tags, since a protocol message * may legally end wherever a tag occurs, and zero is not a valid tag number. * * @return The field tag, or zero if EOF was reached. **/ - (int32_t)readTag; /** * @return A double read from the stream. **/ - (double)readDouble; /** * @return A float read from the stream. **/ - (float)readFloat; /** * @return A uint64 read from the stream. **/ - (uint64_t)readUInt64; /** * @return A uint32 read from the stream. **/ - (uint32_t)readUInt32; /** * @return An int64 read from the stream. **/ - (int64_t)readInt64; /** * @return An int32 read from the stream. **/ - (int32_t)readInt32; /** * @return A fixed64 read from the stream. **/ - (uint64_t)readFixed64; /** * @return A fixed32 read from the stream. **/ - (uint32_t)readFixed32; /** * @return An enum read from the stream. **/ - (int32_t)readEnum; /** * @return A sfixed32 read from the stream. **/ - (int32_t)readSFixed32; /** * @return A fixed64 read from the stream. **/ - (int64_t)readSFixed64; /** * @return A sint32 read from the stream. **/ - (int32_t)readSInt32; /** * @return A sint64 read from the stream. **/ - (int64_t)readSInt64; /** * @return A boolean read from the stream. **/ - (BOOL)readBool; /** * @return A string read from the stream. **/ - (NSString *)readString; /** * @return Data read from the stream. **/ - (NSData *)readBytes; /** * Read an embedded message field value from the stream. * * @param message The message to set fields on as they are read. * @param extensionRegistry An optional extension registry to use to lookup * extensions for message. **/ - (void)readMessage:(GPBMessage *)message extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; /** * Reads and discards a single field, given its tag value. * * @param tag The tag number of the field to skip. * * @return NO if the tag is an endgroup tag (in which case nothing is skipped), * YES in all other cases. **/ - (BOOL)skipField:(int32_t)tag; /** * Reads and discards an entire message. This will read either until EOF or * until an endgroup tag, whichever comes first. **/ - (void)skipMessage; /** * Check to see if the logical end of the stream has been reached. * * @note This can return NO when there is no more data, but the current parsing * expected more data. * * @return YES if the logical end of the stream has been reached, NO otherwise. **/ - (BOOL)isAtEnd; /** * @return The offset into the stream. **/ - (size_t)position; /** * Moves the limit to the given byte offset starting at the current location. * * @exception GPBCodedInputStreamException If the requested bytes exceeed the * current limit. * * @param byteLimit The number of bytes to move the limit, offset to the current * location. * * @return The limit offset before moving the new limit. */ - (size_t)pushLimit:(size_t)byteLimit; /** * Moves the limit back to the offset as it was before calling pushLimit:. * * @param oldLimit The number of bytes to move the current limit. Usually this * is the value returned by the pushLimit: method. */ - (void)popLimit:(size_t)oldLimit; /** * Verifies that the last call to -readTag returned the given tag value. This * is used to verify that a nested group ended with the correct end tag. * * @exception NSParseErrorException If the value does not match the last tag. * * @param expected The tag that was expected. **/ - (void)checkLastTagWas:(int32_t)expected; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedInputStream.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBDictionary_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" #import "GPBUnknownFieldSet_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" #import "GPBWireFormat.h" NSString *const GPBCodedInputStreamException = GPBNSStringifySymbol(GPBCodedInputStreamException); NSString *const GPBCodedInputStreamUnderlyingErrorKey = GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey); NSString *const GPBCodedInputStreamErrorDomain = GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain); static const NSUInteger kDefaultRecursionLimit = 64; static void RaiseException(NSInteger code, NSString *reason) { NSDictionary *errorInfo = nil; if ([reason length]) { errorInfo = @{ GPBErrorReasonKey: reason }; } NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain code:code userInfo:errorInfo]; NSDictionary *exceptionInfo = @{ GPBCodedInputStreamUnderlyingErrorKey: error }; [[[NSException alloc] initWithName:GPBCodedInputStreamException reason:reason userInfo:exceptionInfo] raise]; } static void CheckSize(GPBCodedInputStreamState *state, size_t size) { size_t newSize = state->bufferPos + size; if (newSize > state->bufferSize) { RaiseException(GPBCodedInputStreamErrorInvalidSize, nil); } if (newSize > state->currentLimit) { // Fast forward to end of currentLimit; state->bufferPos = state->currentLimit; RaiseException(GPBCodedInputStreamErrorSubsectionLimitReached, nil); } } static int8_t ReadRawByte(GPBCodedInputStreamState *state) { CheckSize(state, sizeof(int8_t)); return ((int8_t *)state->bytes)[state->bufferPos++]; } static int32_t ReadRawLittleEndian32(GPBCodedInputStreamState *state) { CheckSize(state, sizeof(int32_t)); int32_t value = OSReadLittleInt32(state->bytes, state->bufferPos); state->bufferPos += sizeof(int32_t); return value; } static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) { CheckSize(state, sizeof(int64_t)); int64_t value = OSReadLittleInt64(state->bytes, state->bufferPos); state->bufferPos += sizeof(int64_t); return value; } static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) { int8_t tmp = ReadRawByte(state); if (tmp >= 0) { return tmp; } int32_t result = tmp & 0x7f; if ((tmp = ReadRawByte(state)) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = ReadRawByte(state)) >= 0) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = ReadRawByte(state)) >= 0) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = ReadRawByte(state)) << 28; if (tmp < 0) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (ReadRawByte(state) >= 0) { return result; } } RaiseException(GPBCodedInputStreamErrorInvalidVarInt, @"Invalid VarInt32"); } } } } return result; } static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) { int32_t shift = 0; int64_t result = 0; while (shift < 64) { int8_t b = ReadRawByte(state); result |= (int64_t)(b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } shift += 7; } RaiseException(GPBCodedInputStreamErrorInvalidVarInt, @"Invalid VarInt64"); return 0; } static void SkipRawData(GPBCodedInputStreamState *state, size_t size) { CheckSize(state, size); state->bufferPos += size; } double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state) { int64_t value = ReadRawLittleEndian64(state); return GPBConvertInt64ToDouble(value); } float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state) { int32_t value = ReadRawLittleEndian32(state); return GPBConvertInt32ToFloat(value); } uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state) { uint64_t value = ReadRawVarint64(state); return value; } uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state) { uint32_t value = ReadRawVarint32(state); return value; } int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state) { int64_t value = ReadRawVarint64(state); return value; } int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state) { int32_t value = ReadRawVarint32(state); return value; } uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state) { uint64_t value = ReadRawLittleEndian64(state); return value; } uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state) { uint32_t value = ReadRawLittleEndian32(state); return value; } int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state) { int32_t value = ReadRawVarint32(state); return value; } int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state) { int32_t value = ReadRawLittleEndian32(state); return value; } int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state) { int64_t value = ReadRawLittleEndian64(state); return value; } int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state) { int32_t value = GPBDecodeZigZag32(ReadRawVarint32(state)); return value; } int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state) { int64_t value = GPBDecodeZigZag64(ReadRawVarint64(state)); return value; } BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state) { return ReadRawVarint32(state) != 0; } int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) { if (GPBCodedInputStreamIsAtEnd(state)) { state->lastTag = 0; return 0; } state->lastTag = ReadRawVarint32(state); if (state->lastTag == 0) { // If we actually read zero, that's not a valid tag. RaiseException(GPBCodedInputStreamErrorInvalidTag, @"A zero tag on the wire is invalid."); } // Tags have to include a valid wireformat, check that also. if (!GPBWireFormatIsValidTag(state->lastTag)) { RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Invalid wireformat in tag."); } return state->lastTag; } NSString *GPBCodedInputStreamReadRetainedString( GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); NSString *result; if (size == 0) { result = @""; } else { CheckSize(state, size); result = [[NSString alloc] initWithBytes:&state->bytes[state->bufferPos] length:size encoding:NSUTF8StringEncoding]; state->bufferPos += size; if (!result) { #ifdef DEBUG // https://developers.google.com/protocol-buffers/docs/proto#scalar NSLog(@"UTF-8 failure, is some field type 'string' when it should be " @"'bytes'?"); #endif RaiseException(GPBCodedInputStreamErrorInvalidUTF8, nil); } } return result; } NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); if (size < 0) return nil; CheckSize(state, size); NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos length:size]; state->bufferPos += size; return result; } NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); if (size < 0) return nil; CheckSize(state, size); // Cast is safe because freeWhenDone is NO. NSData *result = [[NSData alloc] initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos) length:size freeWhenDone:NO]; state->bufferPos += size; return result; } size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t byteLimit) { byteLimit += state->bufferPos; size_t oldLimit = state->currentLimit; if (byteLimit > oldLimit) { RaiseException(GPBCodedInputStreamErrorInvalidSubsectionLimit, nil); } state->currentLimit = byteLimit; return oldLimit; } void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, size_t oldLimit) { state->currentLimit = oldLimit; } size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) { return state->currentLimit - state->bufferPos; } BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) { return (state->bufferPos == state->bufferSize) || (state->bufferPos == state->currentLimit); } void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t value) { if (state->lastTag != value) { RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read"); } } @implementation GPBCodedInputStream + (instancetype)streamWithData:(NSData *)data { return [[[self alloc] initWithData:data] autorelease]; } - (instancetype)initWithData:(NSData *)data { if ((self = [super init])) { #ifdef DEBUG NSCAssert([self class] == [GPBCodedInputStream class], @"Subclassing of GPBCodedInputStream is not allowed."); #endif buffer_ = [data retain]; state_.bytes = (const uint8_t *)[data bytes]; state_.bufferSize = [data length]; state_.currentLimit = state_.bufferSize; } return self; } - (void)dealloc { [buffer_ release]; [super dealloc]; } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (int32_t)readTag { return GPBCodedInputStreamReadTag(&state_); } - (void)checkLastTagWas:(int32_t)value { GPBCodedInputStreamCheckLastTagWas(&state_, value); } - (BOOL)skipField:(int32_t)tag { NSAssert(GPBWireFormatIsValidTag(tag), @"Invalid tag"); switch (GPBWireFormatGetTagWireType(tag)) { case GPBWireFormatVarint: GPBCodedInputStreamReadInt32(&state_); return YES; case GPBWireFormatFixed64: SkipRawData(&state_, sizeof(int64_t)); return YES; case GPBWireFormatLengthDelimited: SkipRawData(&state_, ReadRawVarint32(&state_)); return YES; case GPBWireFormatStartGroup: [self skipMessage]; GPBCodedInputStreamCheckLastTagWas( &state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), GPBWireFormatEndGroup)); return YES; case GPBWireFormatEndGroup: return NO; case GPBWireFormatFixed32: SkipRawData(&state_, sizeof(int32_t)); return YES; } } - (void)skipMessage { while (YES) { int32_t tag = GPBCodedInputStreamReadTag(&state_); if (tag == 0 || ![self skipField:tag]) { return; } } } - (BOOL)isAtEnd { return GPBCodedInputStreamIsAtEnd(&state_); } - (size_t)position { return state_.bufferPos; } - (size_t)pushLimit:(size_t)byteLimit { return GPBCodedInputStreamPushLimit(&state_, byteLimit); } - (void)popLimit:(size_t)oldLimit { GPBCodedInputStreamPopLimit(&state_, oldLimit); } - (double)readDouble { return GPBCodedInputStreamReadDouble(&state_); } - (float)readFloat { return GPBCodedInputStreamReadFloat(&state_); } - (uint64_t)readUInt64 { return GPBCodedInputStreamReadUInt64(&state_); } - (int64_t)readInt64 { return GPBCodedInputStreamReadInt64(&state_); } - (int32_t)readInt32 { return GPBCodedInputStreamReadInt32(&state_); } - (uint64_t)readFixed64 { return GPBCodedInputStreamReadFixed64(&state_); } - (uint32_t)readFixed32 { return GPBCodedInputStreamReadFixed32(&state_); } - (BOOL)readBool { return GPBCodedInputStreamReadBool(&state_); } - (NSString *)readString { return [GPBCodedInputStreamReadRetainedString(&state_) autorelease]; } - (void)readGroup:(int32_t)fieldNumber message:(GPBMessage *)message extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { if (state_.recursionDepth >= kDefaultRecursionLimit) { RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil); } ++state_.recursionDepth; [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; GPBCodedInputStreamCheckLastTagWas( &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); --state_.recursionDepth; } - (void)readUnknownGroup:(int32_t)fieldNumber message:(GPBUnknownFieldSet *)message { if (state_.recursionDepth >= kDefaultRecursionLimit) { RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil); } ++state_.recursionDepth; [message mergeFromCodedInputStream:self]; GPBCodedInputStreamCheckLastTagWas( &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); --state_.recursionDepth; } - (void)readMessage:(GPBMessage *)message extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { int32_t length = ReadRawVarint32(&state_); if (state_.recursionDepth >= kDefaultRecursionLimit) { RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil); } size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); ++state_.recursionDepth; [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; GPBCodedInputStreamCheckLastTagWas(&state_, 0); --state_.recursionDepth; GPBCodedInputStreamPopLimit(&state_, oldLimit); } - (void)readMapEntry:(id)mapDictionary extensionRegistry:(GPBExtensionRegistry *)extensionRegistry field:(GPBFieldDescriptor *)field parentMessage:(GPBMessage *)parentMessage { int32_t length = ReadRawVarint32(&state_); if (state_.recursionDepth >= kDefaultRecursionLimit) { RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil); } size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); ++state_.recursionDepth; GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, parentMessage); GPBCodedInputStreamCheckLastTagWas(&state_, 0); --state_.recursionDepth; GPBCodedInputStreamPopLimit(&state_, oldLimit); } - (NSData *)readBytes { return [GPBCodedInputStreamReadRetainedBytes(&state_) autorelease]; } - (uint32_t)readUInt32 { return GPBCodedInputStreamReadUInt32(&state_); } - (int32_t)readEnum { return GPBCodedInputStreamReadEnum(&state_); } - (int32_t)readSFixed32 { return GPBCodedInputStreamReadSFixed32(&state_); } - (int64_t)readSFixed64 { return GPBCodedInputStreamReadSFixed64(&state_); } - (int32_t)readSInt32 { return GPBCodedInputStreamReadSInt32(&state_); } - (int64_t)readSInt64 { return GPBCodedInputStreamReadSInt64(&state_); } #pragma clang diagnostic pop @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedInputStream_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This header is private to the ProtobolBuffers library and must NOT be // included by any sources outside this library. The contents of this file are // subject to change at any time without notice. #import "GPBCodedInputStream.h" #import @class GPBUnknownFieldSet; @class GPBFieldDescriptor; typedef struct GPBCodedInputStreamState { const uint8_t *bytes; size_t bufferSize; size_t bufferPos; // For parsing subsections of an input stream you can put a hard limit on // how much should be read. Normally the limit is the end of the stream, // but you can adjust it to anywhere, and if you hit it you will be at the // end of the stream, until you adjust the limit. size_t currentLimit; int32_t lastTag; NSUInteger recursionDepth; } GPBCodedInputStreamState; @interface GPBCodedInputStream () { @package struct GPBCodedInputStreamState state_; NSData *buffer_; } // Group support is deprecated, so we hide this interface from users, but // support for older data. - (void)readGroup:(int32_t)fieldNumber message:(GPBMessage *)message extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; // Reads a group field value from the stream and merges it into the given // UnknownFieldSet. - (void)readUnknownGroup:(int32_t)fieldNumber message:(GPBUnknownFieldSet *)message; // Reads a map entry. - (void)readMapEntry:(id)mapDictionary extensionRegistry:(GPBExtensionRegistry *)extensionRegistry field:(GPBFieldDescriptor *)field parentMessage:(GPBMessage *)parentMessage; @end CF_EXTERN_C_BEGIN int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state); double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state); float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state); uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state); uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state); int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state); int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state); uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state); uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state); int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state); int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state); int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state); int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state); int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state); BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state); NSString *GPBCodedInputStreamReadRetainedString(GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t byteLimit); void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, size_t oldLimit); size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state); BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state); void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t value); CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedOutputStream.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBRuntimeTypes.h" #import "GPBWireFormat.h" @class GPBBoolArray; @class GPBDoubleArray; @class GPBEnumArray; @class GPBFloatArray; @class GPBMessage; @class GPBInt32Array; @class GPBInt64Array; @class GPBUInt32Array; @class GPBUInt64Array; @class GPBUnknownFieldSet; NS_ASSUME_NONNULL_BEGIN /** * Writes out protocol message fields. * * The common uses of protocol buffers shouldn't need to use this class. * GPBMessage's provide a -data method that will serialize the message for you. * * @note Subclassing of GPBCodedOutputStream is NOT supported. **/ @interface GPBCodedOutputStream : NSObject /** * Creates a stream to fill in the given data. Data must be sized to fit or * an error will be raised when out of space. * * @param data The data where the stream will be written to. * * @return A newly instanced GPBCodedOutputStream. **/ + (instancetype)streamWithData:(NSMutableData *)data; /** * Creates a stream to write into the given NSOutputStream. * * @param output The output stream where the stream will be written to. * * @return A newly instanced GPBCodedOutputStream. **/ + (instancetype)streamWithOutputStream:(NSOutputStream *)output; /** * Initializes a stream to fill in the given data. Data must be sized to fit * or an error will be raised when out of space. * * @param data The data where the stream will be written to. * * @return A newly initialized GPBCodedOutputStream. **/ - (instancetype)initWithData:(NSMutableData *)data; /** * Initializes a stream to write into the given @c NSOutputStream. * * @param output The output stream where the stream will be written to. * * @return A newly initialized GPBCodedOutputStream. **/ - (instancetype)initWithOutputStream:(NSOutputStream *)output; /** * Flush any buffered data out. **/ - (void)flush; /** * Write the raw byte out. * * @param value The value to write out. **/ - (void)writeRawByte:(uint8_t)value; /** * Write the tag for the given field number and wire format. * * @param fieldNumber The field number. * @param format The wire format the data for the field will be in. **/ - (void)writeTag:(uint32_t)fieldNumber format:(GPBWireFormat)format; /** * Write a 32bit value out in little endian format. * * @param value The value to write out. **/ - (void)writeRawLittleEndian32:(int32_t)value; /** * Write a 64bit value out in little endian format. * * @param value The value to write out. **/ - (void)writeRawLittleEndian64:(int64_t)value; /** * Write a 32bit value out in varint format. * * @param value The value to write out. **/ - (void)writeRawVarint32:(int32_t)value; /** * Write a 64bit value out in varint format. * * @param value The value to write out. **/ - (void)writeRawVarint64:(int64_t)value; /** * Write a size_t out as a 32bit varint value. * * @note This will truncate 64 bit values to 32. * * @param value The value to write out. **/ - (void)writeRawVarintSizeTAs32:(size_t)value; /** * Writes the contents of an NSData out. * * @param data The data to write out. **/ - (void)writeRawData:(NSData *)data; /** * Writes out the given data. * * @param data The data blob to write out. * @param offset The offset into the blob to start writing out. * @param length The number of bytes from the blob to write out. **/ - (void)writeRawPtr:(const void *)data offset:(size_t)offset length:(size_t)length; //%PDDM-EXPAND _WRITE_DECLS() // This block of code is generated, do not edit it directly. /** * Write a double for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeDouble:(int32_t)fieldNumber value:(double)value; /** * Write a packed array of double for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeDoubleArray:(int32_t)fieldNumber values:(GPBDoubleArray *)values tag:(uint32_t)tag; /** * Write a double without any tag. * * @param value The value to write out. **/ - (void)writeDoubleNoTag:(double)value; /** * Write a float for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeFloat:(int32_t)fieldNumber value:(float)value; /** * Write a packed array of float for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeFloatArray:(int32_t)fieldNumber values:(GPBFloatArray *)values tag:(uint32_t)tag; /** * Write a float without any tag. * * @param value The value to write out. **/ - (void)writeFloatNoTag:(float)value; /** * Write a uint64_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeUInt64:(int32_t)fieldNumber value:(uint64_t)value; /** * Write a packed array of uint64_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeUInt64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values tag:(uint32_t)tag; /** * Write a uint64_t without any tag. * * @param value The value to write out. **/ - (void)writeUInt64NoTag:(uint64_t)value; /** * Write a int64_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeInt64:(int32_t)fieldNumber value:(int64_t)value; /** * Write a packed array of int64_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag; /** * Write a int64_t without any tag. * * @param value The value to write out. **/ - (void)writeInt64NoTag:(int64_t)value; /** * Write a int32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeInt32:(int32_t)fieldNumber value:(int32_t)value; /** * Write a packed array of int32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag; /** * Write a int32_t without any tag. * * @param value The value to write out. **/ - (void)writeInt32NoTag:(int32_t)value; /** * Write a uint32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeUInt32:(int32_t)fieldNumber value:(uint32_t)value; /** * Write a packed array of uint32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeUInt32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values tag:(uint32_t)tag; /** * Write a uint32_t without any tag. * * @param value The value to write out. **/ - (void)writeUInt32NoTag:(uint32_t)value; /** * Write a uint64_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeFixed64:(int32_t)fieldNumber value:(uint64_t)value; /** * Write a packed array of uint64_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeFixed64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values tag:(uint32_t)tag; /** * Write a uint64_t without any tag. * * @param value The value to write out. **/ - (void)writeFixed64NoTag:(uint64_t)value; /** * Write a uint32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeFixed32:(int32_t)fieldNumber value:(uint32_t)value; /** * Write a packed array of uint32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeFixed32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values tag:(uint32_t)tag; /** * Write a uint32_t without any tag. * * @param value The value to write out. **/ - (void)writeFixed32NoTag:(uint32_t)value; /** * Write a int32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeSInt32:(int32_t)fieldNumber value:(int32_t)value; /** * Write a packed array of int32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeSInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag; /** * Write a int32_t without any tag. * * @param value The value to write out. **/ - (void)writeSInt32NoTag:(int32_t)value; /** * Write a int64_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeSInt64:(int32_t)fieldNumber value:(int64_t)value; /** * Write a packed array of int64_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeSInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag; /** * Write a int64_t without any tag. * * @param value The value to write out. **/ - (void)writeSInt64NoTag:(int64_t)value; /** * Write a int64_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeSFixed64:(int32_t)fieldNumber value:(int64_t)value; /** * Write a packed array of int64_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeSFixed64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag; /** * Write a int64_t without any tag. * * @param value The value to write out. **/ - (void)writeSFixed64NoTag:(int64_t)value; /** * Write a int32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeSFixed32:(int32_t)fieldNumber value:(int32_t)value; /** * Write a packed array of int32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeSFixed32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag; /** * Write a int32_t without any tag. * * @param value The value to write out. **/ - (void)writeSFixed32NoTag:(int32_t)value; /** * Write a BOOL for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeBool:(int32_t)fieldNumber value:(BOOL)value; /** * Write a packed array of BOOL for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeBoolArray:(int32_t)fieldNumber values:(GPBBoolArray *)values tag:(uint32_t)tag; /** * Write a BOOL without any tag. * * @param value The value to write out. **/ - (void)writeBoolNoTag:(BOOL)value; /** * Write a int32_t for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeEnum:(int32_t)fieldNumber value:(int32_t)value; /** * Write a packed array of int32_t for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. * @param tag The tag assigned to the values. **/ - (void)writeEnumArray:(int32_t)fieldNumber values:(GPBEnumArray *)values tag:(uint32_t)tag; /** * Write a int32_t without any tag. * * @param value The value to write out. **/ - (void)writeEnumNoTag:(int32_t)value; /** * Write a NSString for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeString:(int32_t)fieldNumber value:(NSString *)value; /** * Write an array of NSString for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. **/ - (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values; /** * Write a NSString without any tag. * * @param value The value to write out. **/ - (void)writeStringNoTag:(NSString *)value; /** * Write a GPBMessage for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeMessage:(int32_t)fieldNumber value:(GPBMessage *)value; /** * Write an array of GPBMessage for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. **/ - (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values; /** * Write a GPBMessage without any tag. * * @param value The value to write out. **/ - (void)writeMessageNoTag:(GPBMessage *)value; /** * Write a NSData for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeBytes:(int32_t)fieldNumber value:(NSData *)value; /** * Write an array of NSData for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. **/ - (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values; /** * Write a NSData without any tag. * * @param value The value to write out. **/ - (void)writeBytesNoTag:(NSData *)value; /** * Write a GPBMessage for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeGroup:(int32_t)fieldNumber value:(GPBMessage *)value; /** * Write an array of GPBMessage for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. **/ - (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values; /** * Write a GPBMessage without any tag (but does write the endGroup tag). * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeGroupNoTag:(int32_t)fieldNumber value:(GPBMessage *)value; /** * Write a GPBUnknownFieldSet for the given field number. * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeUnknownGroup:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value; /** * Write an array of GPBUnknownFieldSet for the given field number. * * @param fieldNumber The field number assigned to the values. * @param values The values to write out. **/ - (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values; /** * Write a GPBUnknownFieldSet without any tag (but does write the endGroup tag). * * @param fieldNumber The field number assigned to the value. * @param value The value to write out. **/ - (void)writeUnknownGroupNoTag:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value; //%PDDM-EXPAND-END _WRITE_DECLS() /** Write a MessageSet extension field to the stream. For historical reasons, the wire format differs from normal fields. @param fieldNumber The extension field number to write out. @param value The message from where to get the extension. */ - (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value; /** Write an unparsed MessageSet extension field to the stream. For historical reasons, the wire format differs from normal fields. @param fieldNumber The extension field number to write out. @param value The raw message from where to get the extension. */ - (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value; @end NS_ASSUME_NONNULL_END // Write methods for types that can be in packed arrays. //%PDDM-DEFINE _WRITE_PACKABLE_DECLS(NAME, ARRAY_TYPE, TYPE) //%/** //% * Write a TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the value. //% * @param value The value to write out. //% **/ //%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE)value; //%/** //% * Write a packed array of TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the values. //% * @param values The values to write out. //% * @param tag The tag assigned to the values. //% **/ //%- (void)write##NAME##Array:(int32_t)fieldNumber //% NAME$S values:(GPB##ARRAY_TYPE##Array *)values //% NAME$S tag:(uint32_t)tag; //%/** //% * Write a TYPE without any tag. //% * //% * @param value The value to write out. //% **/ //%- (void)write##NAME##NoTag:(TYPE)value; //% // Write methods for types that aren't in packed arrays. //%PDDM-DEFINE _WRITE_UNPACKABLE_DECLS(NAME, TYPE) //%/** //% * Write a TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the value. //% * @param value The value to write out. //% **/ //%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE *)value; //%/** //% * Write an array of TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the values. //% * @param values The values to write out. //% **/ //%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values; //%/** //% * Write a TYPE without any tag. //% * //% * @param value The value to write out. //% **/ //%- (void)write##NAME##NoTag:(TYPE *)value; //% // Special write methods for Groups. //%PDDM-DEFINE _WRITE_GROUP_DECLS(NAME, TYPE) //%/** //% * Write a TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the value. //% * @param value The value to write out. //% **/ //%- (void)write##NAME:(int32_t)fieldNumber //% NAME$S value:(TYPE *)value; //%/** //% * Write an array of TYPE for the given field number. //% * //% * @param fieldNumber The field number assigned to the values. //% * @param values The values to write out. //% **/ //%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values; //%/** //% * Write a TYPE without any tag (but does write the endGroup tag). //% * //% * @param fieldNumber The field number assigned to the value. //% * @param value The value to write out. //% **/ //%- (void)write##NAME##NoTag:(int32_t)fieldNumber //% NAME$S value:(TYPE *)value; //% // One macro to hide it all up above. //%PDDM-DEFINE _WRITE_DECLS() //%_WRITE_PACKABLE_DECLS(Double, Double, double) //%_WRITE_PACKABLE_DECLS(Float, Float, float) //%_WRITE_PACKABLE_DECLS(UInt64, UInt64, uint64_t) //%_WRITE_PACKABLE_DECLS(Int64, Int64, int64_t) //%_WRITE_PACKABLE_DECLS(Int32, Int32, int32_t) //%_WRITE_PACKABLE_DECLS(UInt32, UInt32, uint32_t) //%_WRITE_PACKABLE_DECLS(Fixed64, UInt64, uint64_t) //%_WRITE_PACKABLE_DECLS(Fixed32, UInt32, uint32_t) //%_WRITE_PACKABLE_DECLS(SInt32, Int32, int32_t) //%_WRITE_PACKABLE_DECLS(SInt64, Int64, int64_t) //%_WRITE_PACKABLE_DECLS(SFixed64, Int64, int64_t) //%_WRITE_PACKABLE_DECLS(SFixed32, Int32, int32_t) //%_WRITE_PACKABLE_DECLS(Bool, Bool, BOOL) //%_WRITE_PACKABLE_DECLS(Enum, Enum, int32_t) //%_WRITE_UNPACKABLE_DECLS(String, NSString) //%_WRITE_UNPACKABLE_DECLS(Message, GPBMessage) //%_WRITE_UNPACKABLE_DECLS(Bytes, NSData) //%_WRITE_GROUP_DECLS(Group, GPBMessage) //%_WRITE_GROUP_DECLS(UnknownGroup, GPBUnknownFieldSet) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedOutputStream.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBCodedOutputStream_PackagePrivate.h" #import #import "GPBArray.h" #import "GPBUnknownFieldSet_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" // Structure for containing state of a GPBCodedInputStream. Brought out into // a struct so that we can inline several common functions instead of dealing // with overhead of ObjC dispatch. typedef struct GPBOutputBufferState { uint8_t *bytes; size_t size; size_t position; NSOutputStream *output; } GPBOutputBufferState; @implementation GPBCodedOutputStream { GPBOutputBufferState state_; NSMutableData *buffer_; } static const int32_t LITTLE_ENDIAN_32_SIZE = sizeof(uint32_t); static const int32_t LITTLE_ENDIAN_64_SIZE = sizeof(uint64_t); // Internal helper that writes the current buffer to the output. The // buffer position is reset to its initial value when this returns. static void GPBRefreshBuffer(GPBOutputBufferState *state) { if (state->output == nil) { // We're writing to a single buffer. [NSException raise:@"OutOfSpace" format:@""]; } if (state->position != 0) { NSInteger written = [state->output write:state->bytes maxLength:state->position]; if (written != (NSInteger)state->position) { [NSException raise:@"WriteFailed" format:@""]; } state->position = 0; } } static void GPBWriteRawByte(GPBOutputBufferState *state, uint8_t value) { if (state->position == state->size) { GPBRefreshBuffer(state); } state->bytes[state->position++] = value; } static void GPBWriteRawVarint32(GPBOutputBufferState *state, int32_t value) { while (YES) { if ((value & ~0x7F) == 0) { uint8_t val = (uint8_t)value; GPBWriteRawByte(state, val); return; } else { GPBWriteRawByte(state, (value & 0x7F) | 0x80); value = GPBLogicalRightShift32(value, 7); } } } static void GPBWriteRawVarint64(GPBOutputBufferState *state, int64_t value) { while (YES) { if ((value & ~0x7FL) == 0) { uint8_t val = (uint8_t)value; GPBWriteRawByte(state, val); return; } else { GPBWriteRawByte(state, ((int32_t)value & 0x7F) | 0x80); value = GPBLogicalRightShift64(value, 7); } } } static void GPBWriteInt32NoTag(GPBOutputBufferState *state, int32_t value) { if (value >= 0) { GPBWriteRawVarint32(state, value); } else { // Must sign-extend GPBWriteRawVarint64(state, value); } } static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, uint32_t value) { GPBWriteTagWithFormat(state, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint32(state, value); } static void GPBWriteTagWithFormat(GPBOutputBufferState *state, uint32_t fieldNumber, GPBWireFormat format) { GPBWriteRawVarint32(state, GPBWireFormatMakeTag(fieldNumber, format)); } static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, int32_t value) { GPBWriteRawByte(state, (value)&0xFF); GPBWriteRawByte(state, (value >> 8) & 0xFF); GPBWriteRawByte(state, (value >> 16) & 0xFF); GPBWriteRawByte(state, (value >> 24) & 0xFF); } static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, int64_t value) { GPBWriteRawByte(state, (int32_t)(value)&0xFF); GPBWriteRawByte(state, (int32_t)(value >> 8) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 16) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 24) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 32) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 40) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 48) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 56) & 0xFF); } - (void)dealloc { [self flush]; [state_.output close]; [state_.output release]; [buffer_ release]; [super dealloc]; } - (instancetype)initWithOutputStream:(NSOutputStream *)output { NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; return [self initWithOutputStream:output data:data]; } - (instancetype)initWithData:(NSMutableData *)data { return [self initWithOutputStream:nil data:data]; } // This initializer isn't exposed, but it is the designated initializer. // Setting OutputStream and NSData is to control the buffering behavior/size // of the work, but that is more obvious via the bufferSize: version. - (instancetype)initWithOutputStream:(NSOutputStream *)output data:(NSMutableData *)data { if ((self = [super init])) { buffer_ = [data retain]; [output open]; state_.bytes = [data mutableBytes]; state_.size = [data length]; state_.output = [output retain]; } return self; } + (instancetype)streamWithOutputStream:(NSOutputStream *)output { NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; return [[[self alloc] initWithOutputStream:output data:data] autorelease]; } + (instancetype)streamWithData:(NSMutableData *)data { return [[[self alloc] initWithData:data] autorelease]; } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (void)writeDoubleNoTag:(double)value { GPBWriteRawLittleEndian64(&state_, GPBConvertDoubleToInt64(value)); } - (void)writeDouble:(int32_t)fieldNumber value:(double)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); GPBWriteRawLittleEndian64(&state_, GPBConvertDoubleToInt64(value)); } - (void)writeFloatNoTag:(float)value { GPBWriteRawLittleEndian32(&state_, GPBConvertFloatToInt32(value)); } - (void)writeFloat:(int32_t)fieldNumber value:(float)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); GPBWriteRawLittleEndian32(&state_, GPBConvertFloatToInt32(value)); } - (void)writeUInt64NoTag:(uint64_t)value { GPBWriteRawVarint64(&state_, value); } - (void)writeUInt64:(int32_t)fieldNumber value:(uint64_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint64(&state_, value); } - (void)writeInt64NoTag:(int64_t)value { GPBWriteRawVarint64(&state_, value); } - (void)writeInt64:(int32_t)fieldNumber value:(int64_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint64(&state_, value); } - (void)writeInt32NoTag:(int32_t)value { GPBWriteInt32NoTag(&state_, value); } - (void)writeInt32:(int32_t)fieldNumber value:(int32_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteInt32NoTag(&state_, value); } - (void)writeFixed64NoTag:(uint64_t)value { GPBWriteRawLittleEndian64(&state_, value); } - (void)writeFixed64:(int32_t)fieldNumber value:(uint64_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); GPBWriteRawLittleEndian64(&state_, value); } - (void)writeFixed32NoTag:(uint32_t)value { GPBWriteRawLittleEndian32(&state_, value); } - (void)writeFixed32:(int32_t)fieldNumber value:(uint32_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); GPBWriteRawLittleEndian32(&state_, value); } - (void)writeBoolNoTag:(BOOL)value { GPBWriteRawByte(&state_, (value ? 1 : 0)); } - (void)writeBool:(int32_t)fieldNumber value:(BOOL)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawByte(&state_, (value ? 1 : 0)); } - (void)writeStringNoTag:(const NSString *)value { size_t length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; GPBWriteRawVarint32(&state_, (int32_t)length); if (length == 0) { return; } const char *quickString = CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8); // Fast path: Most strings are short, if the buffer already has space, // add to it directly. NSUInteger bufferBytesLeft = state_.size - state_.position; if (bufferBytesLeft >= length) { NSUInteger usedBufferLength = 0; BOOL result; if (quickString != NULL) { memcpy(state_.bytes + state_.position, quickString, length); usedBufferLength = length; result = YES; } else { result = [value getBytes:state_.bytes + state_.position maxLength:bufferBytesLeft usedLength:&usedBufferLength encoding:NSUTF8StringEncoding options:(NSStringEncodingConversionOptions)0 range:NSMakeRange(0, [value length]) remainingRange:NULL]; } if (result) { NSAssert2((usedBufferLength == length), @"Our UTF8 calc was wrong? %tu vs %zd", usedBufferLength, length); state_.position += usedBufferLength; return; } } else if (quickString != NULL) { [self writeRawPtr:quickString offset:0 length:length]; } else { // Slow path: just get it as data and write it out. NSData *utf8Data = [value dataUsingEncoding:NSUTF8StringEncoding]; NSAssert2(([utf8Data length] == length), @"Strings UTF8 length was wrong? %tu vs %zd", [utf8Data length], length); [self writeRawData:utf8Data]; } } - (void)writeString:(int32_t)fieldNumber value:(NSString *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); [self writeStringNoTag:value]; } - (void)writeGroupNoTag:(int32_t)fieldNumber value:(GPBMessage *)value { [value writeToCodedOutputStream:self]; GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); } - (void)writeGroup:(int32_t)fieldNumber value:(GPBMessage *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); [self writeGroupNoTag:fieldNumber value:value]; } - (void)writeUnknownGroupNoTag:(int32_t)fieldNumber value:(const GPBUnknownFieldSet *)value { [value writeToCodedOutputStream:self]; GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); } - (void)writeUnknownGroup:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); [self writeUnknownGroupNoTag:fieldNumber value:value]; } - (void)writeMessageNoTag:(GPBMessage *)value { GPBWriteRawVarint32(&state_, (int32_t)[value serializedSize]); [value writeToCodedOutputStream:self]; } - (void)writeMessage:(int32_t)fieldNumber value:(GPBMessage *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); [self writeMessageNoTag:value]; } - (void)writeBytesNoTag:(NSData *)value { GPBWriteRawVarint32(&state_, (int32_t)[value length]); [self writeRawData:value]; } - (void)writeBytes:(int32_t)fieldNumber value:(NSData *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatLengthDelimited); [self writeBytesNoTag:value]; } - (void)writeUInt32NoTag:(uint32_t)value { GPBWriteRawVarint32(&state_, value); } - (void)writeUInt32:(int32_t)fieldNumber value:(uint32_t)value { GPBWriteUInt32(&state_, fieldNumber, value); } - (void)writeEnumNoTag:(int32_t)value { GPBWriteRawVarint32(&state_, value); } - (void)writeEnum:(int32_t)fieldNumber value:(int32_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint32(&state_, value); } - (void)writeSFixed32NoTag:(int32_t)value { GPBWriteRawLittleEndian32(&state_, value); } - (void)writeSFixed32:(int32_t)fieldNumber value:(int32_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed32); GPBWriteRawLittleEndian32(&state_, value); } - (void)writeSFixed64NoTag:(int64_t)value { GPBWriteRawLittleEndian64(&state_, value); } - (void)writeSFixed64:(int32_t)fieldNumber value:(int64_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatFixed64); GPBWriteRawLittleEndian64(&state_, value); } - (void)writeSInt32NoTag:(int32_t)value { GPBWriteRawVarint32(&state_, GPBEncodeZigZag32(value)); } - (void)writeSInt32:(int32_t)fieldNumber value:(int32_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint32(&state_, GPBEncodeZigZag32(value)); } - (void)writeSInt64NoTag:(int64_t)value { GPBWriteRawVarint64(&state_, GPBEncodeZigZag64(value)); } - (void)writeSInt64:(int32_t)fieldNumber value:(int64_t)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint64(&state_, GPBEncodeZigZag64(value)); } //%PDDM-DEFINE WRITE_PACKABLE_DEFNS(NAME, ARRAY_TYPE, TYPE, ACCESSOR_NAME) //%- (void)write##NAME##Array:(int32_t)fieldNumber //% NAME$S values:(GPB##ARRAY_TYPE##Array *)values //% NAME$S tag:(uint32_t)tag { //% if (tag != 0) { //% if (values.count == 0) return; //% __block size_t dataSize = 0; //% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { //%#pragma unused(idx, stop) //% dataSize += GPBCompute##NAME##SizeNoTag(value); //% }]; //% GPBWriteRawVarint32(&state_, tag); //% GPBWriteRawVarint32(&state_, (int32_t)dataSize); //% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { //%#pragma unused(idx, stop) //% [self write##NAME##NoTag:value]; //% }]; //% } else { //% [values enumerate##ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { //%#pragma unused(idx, stop) //% [self write##NAME:fieldNumber value:value]; //% }]; //% } //%} //% //%PDDM-DEFINE WRITE_UNPACKABLE_DEFNS(NAME, TYPE) //%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray *)values { //% for (TYPE *value in values) { //% [self write##NAME:fieldNumber value:value]; //% } //%} //% //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Double, Double, double, ) // This block of code is generated, do not edit it directly. - (void)writeDoubleArray:(int32_t)fieldNumber values:(GPBDoubleArray *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeDoubleSizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeDoubleNoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(double value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeDouble:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Float, Float, float, ) // This block of code is generated, do not edit it directly. - (void)writeFloatArray:(int32_t)fieldNumber values:(GPBFloatArray *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeFloatSizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFloatNoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(float value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFloat:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt64, UInt64, uint64_t, ) // This block of code is generated, do not edit it directly. - (void)writeUInt64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeUInt64SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeUInt64NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeUInt64:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. - (void)writeInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeInt64SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeInt64NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeInt64:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. - (void)writeInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeInt32SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeInt32NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeInt32:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt32, UInt32, uint32_t, ) // This block of code is generated, do not edit it directly. - (void)writeUInt32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeUInt32SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeUInt32NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeUInt32:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed64, UInt64, uint64_t, ) // This block of code is generated, do not edit it directly. - (void)writeFixed64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeFixed64SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFixed64NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFixed64:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed32, UInt32, uint32_t, ) // This block of code is generated, do not edit it directly. - (void)writeFixed32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeFixed32SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFixed32NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeFixed32:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. - (void)writeSInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeSInt32SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSInt32NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSInt32:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. - (void)writeSInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeSInt64SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSInt64NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSInt64:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. - (void)writeSFixed64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeSFixed64SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSFixed64NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSFixed64:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. - (void)writeSFixed32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeSFixed32SizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSFixed32NoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeSFixed32:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Bool, Bool, BOOL, ) // This block of code is generated, do not edit it directly. - (void)writeBoolArray:(int32_t)fieldNumber values:(GPBBoolArray *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeBoolSizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeBoolNoTag:value]; }]; } else { [values enumerateValuesWithBlock:^(BOOL value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeBool:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Enum, Enum, int32_t, Raw) // This block of code is generated, do not edit it directly. - (void)writeEnumArray:(int32_t)fieldNumber values:(GPBEnumArray *)values tag:(uint32_t)tag { if (tag != 0) { if (values.count == 0) return; __block size_t dataSize = 0; [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) dataSize += GPBComputeEnumSizeNoTag(value); }]; GPBWriteRawVarint32(&state_, tag); GPBWriteRawVarint32(&state_, (int32_t)dataSize); [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeEnumNoTag:value]; }]; } else { [values enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [self writeEnum:fieldNumber value:value]; }]; } } //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(String, NSString) // This block of code is generated, do not edit it directly. - (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values { for (NSString *value in values) { [self writeString:fieldNumber value:value]; } } //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Message, GPBMessage) // This block of code is generated, do not edit it directly. - (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBMessage *value in values) { [self writeMessage:fieldNumber value:value]; } } //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Bytes, NSData) // This block of code is generated, do not edit it directly. - (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values { for (NSData *value in values) { [self writeBytes:fieldNumber value:value]; } } //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Group, GPBMessage) // This block of code is generated, do not edit it directly. - (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBMessage *value in values) { [self writeGroup:fieldNumber value:value]; } } //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(UnknownGroup, GPBUnknownFieldSet) // This block of code is generated, do not edit it directly. - (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBUnknownFieldSet *value in values) { [self writeUnknownGroup:fieldNumber value:value]; } } //%PDDM-EXPAND-END (19 expansions) - (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value { GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); [self writeMessage:GPBWireFormatMessageSetMessage value:value]; GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup); } - (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value { GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); [self writeBytes:GPBWireFormatMessageSetMessage value:value]; GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup); } - (void)flush { if (state_.output != nil) { GPBRefreshBuffer(&state_); } } - (void)writeRawByte:(uint8_t)value { GPBWriteRawByte(&state_, value); } - (void)writeRawData:(const NSData *)data { [self writeRawPtr:[data bytes] offset:0 length:[data length]]; } - (void)writeRawPtr:(const void *)value offset:(size_t)offset length:(size_t)length { if (value == nil || length == 0) { return; } NSUInteger bufferLength = state_.size; NSUInteger bufferBytesLeft = bufferLength - state_.position; if (bufferBytesLeft >= length) { // We have room in the current buffer. memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, length); state_.position += length; } else { // Write extends past current buffer. Fill the rest of this buffer and // flush. size_t bytesWritten = bufferBytesLeft; memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, bytesWritten); offset += bytesWritten; length -= bytesWritten; state_.position = bufferLength; GPBRefreshBuffer(&state_); bufferLength = state_.size; // Now deal with the rest. // Since we have an output stream, this is our buffer // and buffer offset == 0 if (length <= bufferLength) { // Fits in new buffer. memcpy(state_.bytes, ((uint8_t *)value) + offset, length); state_.position = length; } else { // Write is very big. Let's do it all at once. [state_.output write:((uint8_t *)value) + offset maxLength:length]; } } } - (void)writeTag:(uint32_t)fieldNumber format:(GPBWireFormat)format { GPBWriteTagWithFormat(&state_, fieldNumber, format); } - (void)writeRawVarint32:(int32_t)value { GPBWriteRawVarint32(&state_, value); } - (void)writeRawVarintSizeTAs32:(size_t)value { // Note the truncation. GPBWriteRawVarint32(&state_, (int32_t)value); } - (void)writeRawVarint64:(int64_t)value { GPBWriteRawVarint64(&state_, value); } - (void)writeRawLittleEndian32:(int32_t)value { GPBWriteRawLittleEndian32(&state_, value); } - (void)writeRawLittleEndian64:(int64_t)value { GPBWriteRawLittleEndian64(&state_, value); } #pragma clang diagnostic pop @end size_t GPBComputeDoubleSizeNoTag(Float64 value) { #pragma unused(value) return LITTLE_ENDIAN_64_SIZE; } size_t GPBComputeFloatSizeNoTag(Float32 value) { #pragma unused(value) return LITTLE_ENDIAN_32_SIZE; } size_t GPBComputeUInt64SizeNoTag(uint64_t value) { return GPBComputeRawVarint64Size(value); } size_t GPBComputeInt64SizeNoTag(int64_t value) { return GPBComputeRawVarint64Size(value); } size_t GPBComputeInt32SizeNoTag(int32_t value) { if (value >= 0) { return GPBComputeRawVarint32Size(value); } else { // Must sign-extend. return 10; } } size_t GPBComputeSizeTSizeAsInt32NoTag(size_t value) { return GPBComputeInt32SizeNoTag((int32_t)value); } size_t GPBComputeFixed64SizeNoTag(uint64_t value) { #pragma unused(value) return LITTLE_ENDIAN_64_SIZE; } size_t GPBComputeFixed32SizeNoTag(uint32_t value) { #pragma unused(value) return LITTLE_ENDIAN_32_SIZE; } size_t GPBComputeBoolSizeNoTag(BOOL value) { #pragma unused(value) return 1; } size_t GPBComputeStringSizeNoTag(NSString *value) { NSUInteger length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; return GPBComputeRawVarint32SizeForInteger(length) + length; } size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { return [value serializedSize]; } size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { return value.serializedSize; } size_t GPBComputeMessageSizeNoTag(GPBMessage *value) { size_t size = [value serializedSize]; return GPBComputeRawVarint32SizeForInteger(size) + size; } size_t GPBComputeBytesSizeNoTag(NSData *value) { NSUInteger valueLength = [value length]; return GPBComputeRawVarint32SizeForInteger(valueLength) + valueLength; } size_t GPBComputeUInt32SizeNoTag(int32_t value) { return GPBComputeRawVarint32Size(value); } size_t GPBComputeEnumSizeNoTag(int32_t value) { return GPBComputeRawVarint32Size(value); } size_t GPBComputeSFixed32SizeNoTag(int32_t value) { #pragma unused(value) return LITTLE_ENDIAN_32_SIZE; } size_t GPBComputeSFixed64SizeNoTag(int64_t value) { #pragma unused(value) return LITTLE_ENDIAN_64_SIZE; } size_t GPBComputeSInt32SizeNoTag(int32_t value) { return GPBComputeRawVarint32Size(GPBEncodeZigZag32(value)); } size_t GPBComputeSInt64SizeNoTag(int64_t value) { return GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); } size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) { return GPBComputeTagSize(fieldNumber) + GPBComputeDoubleSizeNoTag(value); } size_t GPBComputeFloatSize(int32_t fieldNumber, float value) { return GPBComputeTagSize(fieldNumber) + GPBComputeFloatSizeNoTag(value); } size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeUInt64SizeNoTag(value); } size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeInt64SizeNoTag(value); } size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeInt32SizeNoTag(value); } size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeFixed64SizeNoTag(value); } size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeFixed32SizeNoTag(value); } size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) { return GPBComputeTagSize(fieldNumber) + GPBComputeBoolSizeNoTag(value); } size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) { return GPBComputeTagSize(fieldNumber) + GPBComputeStringSizeNoTag(value); } size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) { return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeGroupSizeNoTag(value); } size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, GPBUnknownFieldSet *value) { return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeUnknownGroupSizeNoTag(value); } size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) { return GPBComputeTagSize(fieldNumber) + GPBComputeMessageSizeNoTag(value); } size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) { return GPBComputeTagSize(fieldNumber) + GPBComputeBytesSizeNoTag(value); } size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeUInt32SizeNoTag(value); } size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeEnumSizeNoTag(value); } size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeSFixed32SizeNoTag(value); } size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeSFixed64SizeNoTag(value); } size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeSInt32SizeNoTag(value); } size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) { return GPBComputeTagSize(fieldNumber) + GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); } size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) { return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeMessageSize(GPBWireFormatMessageSetMessage, value); } size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) { return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeBytesSize(GPBWireFormatMessageSetMessage, value); } size_t GPBComputeTagSize(int32_t fieldNumber) { return GPBComputeRawVarint32Size( GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint)); } size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) { size_t result = GPBComputeTagSize(field_number); if (dataType == GPBDataTypeGroup) { // Groups have both a start and an end tag. return result * 2; } else { return result; } } size_t GPBComputeRawVarint32Size(int32_t value) { // value is treated as unsigned, so it won't be sign-extended if negative. if ((value & (0xffffffff << 7)) == 0) return 1; if ((value & (0xffffffff << 14)) == 0) return 2; if ((value & (0xffffffff << 21)) == 0) return 3; if ((value & (0xffffffff << 28)) == 0) return 4; return 5; } size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) { // Note the truncation. return GPBComputeRawVarint32Size((int32_t)value); } size_t GPBComputeRawVarint64Size(int64_t value) { if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; return 10; } ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBCodedOutputStream_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2016 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBCodedOutputStream.h" NS_ASSUME_NONNULL_BEGIN CF_EXTERN_C_BEGIN size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) __attribute__((const)); size_t GPBComputeFloatSize(int32_t fieldNumber, float value) __attribute__((const)); size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) __attribute__((const)); size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) __attribute__((const)); size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) __attribute__((const)); size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) __attribute__((const)); size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) __attribute__((const)); size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) __attribute__((const)); size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, GPBUnknownFieldSet *value) __attribute__((const)); size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) __attribute__((const)); size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) __attribute__((const)); size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) __attribute__((const)); size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); size_t GPBComputeTagSize(int32_t fieldNumber) __attribute__((const)); size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) __attribute__((const)); size_t GPBComputeDoubleSizeNoTag(double value) __attribute__((const)); size_t GPBComputeFloatSizeNoTag(float value) __attribute__((const)); size_t GPBComputeUInt64SizeNoTag(uint64_t value) __attribute__((const)); size_t GPBComputeInt64SizeNoTag(int64_t value) __attribute__((const)); size_t GPBComputeInt32SizeNoTag(int32_t value) __attribute__((const)); size_t GPBComputeFixed64SizeNoTag(uint64_t value) __attribute__((const)); size_t GPBComputeFixed32SizeNoTag(uint32_t value) __attribute__((const)); size_t GPBComputeBoolSizeNoTag(BOOL value) __attribute__((const)); size_t GPBComputeStringSizeNoTag(NSString *value) __attribute__((const)); size_t GPBComputeGroupSizeNoTag(GPBMessage *value) __attribute__((const)); size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) __attribute__((const)); size_t GPBComputeMessageSizeNoTag(GPBMessage *value) __attribute__((const)); size_t GPBComputeBytesSizeNoTag(NSData *value) __attribute__((const)); size_t GPBComputeUInt32SizeNoTag(int32_t value) __attribute__((const)); size_t GPBComputeEnumSizeNoTag(int32_t value) __attribute__((const)); size_t GPBComputeSFixed32SizeNoTag(int32_t value) __attribute__((const)); size_t GPBComputeSFixed64SizeNoTag(int64_t value) __attribute__((const)); size_t GPBComputeSInt32SizeNoTag(int32_t value) __attribute__((const)); size_t GPBComputeSInt64SizeNoTag(int64_t value) __attribute__((const)); // Note that this will calculate the size of 64 bit values truncated to 32. size_t GPBComputeSizeTSizeAsInt32NoTag(size_t value) __attribute__((const)); size_t GPBComputeRawVarint32Size(int32_t value) __attribute__((const)); size_t GPBComputeRawVarint64Size(int64_t value) __attribute__((const)); // Note that this will calculate the size of 64 bit values truncated to 32. size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) __attribute__((const)); // Compute the number of bytes that would be needed to encode a // MessageSet extension to the stream. For historical reasons, // the wire format differs from normal fields. size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) __attribute__((const)); // Compute the number of bytes that would be needed to encode an // unparsed MessageSet extension field to the stream. For // historical reasons, the wire format differs from normal fields. size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) __attribute__((const)); size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) __attribute__((const)); CF_EXTERN_C_END NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDescriptor.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBRuntimeTypes.h" @class GPBEnumDescriptor; @class GPBFieldDescriptor; @class GPBFileDescriptor; @class GPBOneofDescriptor; NS_ASSUME_NONNULL_BEGIN /** Syntax used in the proto file. */ typedef NS_ENUM(uint8_t, GPBFileSyntax) { /** Unknown syntax. */ GPBFileSyntaxUnknown = 0, /** Proto2 syntax. */ GPBFileSyntaxProto2 = 2, /** Proto3 syntax. */ GPBFileSyntaxProto3 = 3, }; /** Type of proto field. */ typedef NS_ENUM(uint8_t, GPBFieldType) { /** Optional/required field. Only valid for proto2 fields. */ GPBFieldTypeSingle, /** Repeated field. */ GPBFieldTypeRepeated, /** Map field. */ GPBFieldTypeMap, }; /** * Describes a proto message. **/ @interface GPBDescriptor : NSObject /** Name of the message. */ @property(nonatomic, readonly, copy) NSString *name; /** Fields declared in the message. */ @property(nonatomic, readonly, strong, nullable) NSArray *fields; /** Oneofs declared in the message. */ @property(nonatomic, readonly, strong, nullable) NSArray *oneofs; /** Extension range declared for the message. */ @property(nonatomic, readonly, nullable) const GPBExtensionRange *extensionRanges; /** Number of extension ranges declared for the message. */ @property(nonatomic, readonly) uint32_t extensionRangesCount; /** Descriptor for the file where the message was defined. */ @property(nonatomic, readonly, assign) GPBFileDescriptor *file; /** Whether the message is in wire format or not. */ @property(nonatomic, readonly, getter=isWireFormat) BOOL wireFormat; /** The class of this message. */ @property(nonatomic, readonly) Class messageClass; /** Containing message descriptor if this message is nested, or nil otherwise. */ @property(readonly, nullable) GPBDescriptor *containingType; /** * Fully qualified name for this message (package.message). Can be nil if the * value is unable to be computed. */ @property(readonly, nullable) NSString *fullName; /** * Gets the field for the given number. * * @param fieldNumber The number for the field to get. * * @return The field descriptor for the given number, or nil if not found. **/ - (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber; /** * Gets the field for the given name. * * @param name The name for the field to get. * * @return The field descriptor for the given name, or nil if not found. **/ - (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name; /** * Gets the oneof for the given name. * * @param name The name for the oneof to get. * * @return The oneof descriptor for the given name, or nil if not found. **/ - (nullable GPBOneofDescriptor *)oneofWithName:(NSString *)name; @end /** * Describes a proto file. **/ @interface GPBFileDescriptor : NSObject /** The package declared in the proto file. */ @property(nonatomic, readonly, copy) NSString *package; /** The objc prefix declared in the proto file. */ @property(nonatomic, readonly, copy, nullable) NSString *objcPrefix; /** The syntax of the proto file. */ @property(nonatomic, readonly) GPBFileSyntax syntax; @end /** * Describes a oneof field. **/ @interface GPBOneofDescriptor : NSObject /** Name of the oneof field. */ @property(nonatomic, readonly) NSString *name; /** Fields declared in the oneof. */ @property(nonatomic, readonly) NSArray *fields; /** * Gets the field for the given number. * * @param fieldNumber The number for the field to get. * * @return The field descriptor for the given number, or nil if not found. **/ - (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber; /** * Gets the field for the given name. * * @param name The name for the field to get. * * @return The field descriptor for the given name, or nil if not found. **/ - (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name; @end /** * Describes a proto field. **/ @interface GPBFieldDescriptor : NSObject /** Name of the field. */ @property(nonatomic, readonly, copy) NSString *name; /** Number associated with the field. */ @property(nonatomic, readonly) uint32_t number; /** Data type contained in the field. */ @property(nonatomic, readonly) GPBDataType dataType; /** Whether it has a default value or not. */ @property(nonatomic, readonly) BOOL hasDefaultValue; /** Default value for the field. */ @property(nonatomic, readonly) GPBGenericValue defaultValue; /** Whether this field is required. Only valid for proto2 fields. */ @property(nonatomic, readonly, getter=isRequired) BOOL required; /** Whether this field is optional. */ @property(nonatomic, readonly, getter=isOptional) BOOL optional; /** Type of field (single, repeated, map). */ @property(nonatomic, readonly) GPBFieldType fieldType; /** Type of the key if the field is a map. The value's type is -fieldType. */ @property(nonatomic, readonly) GPBDataType mapKeyDataType; /** Whether the field is packable. */ @property(nonatomic, readonly, getter=isPackable) BOOL packable; /** The containing oneof if this field is part of one, nil otherwise. */ @property(nonatomic, readonly, assign, nullable) GPBOneofDescriptor *containingOneof; /** Class of the message if the field is of message type. */ @property(nonatomic, readonly, assign, nullable) Class msgClass; /** Descriptor for the enum if this field is an enum. */ @property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor; /** * Checks whether the given enum raw value is a valid enum value. * * @param value The raw enum value to check. * * @return YES if value is a valid enum raw value. **/ - (BOOL)isValidEnumValue:(int32_t)value; /** @return Name for the text format, or nil if not known. */ - (nullable NSString *)textFormatName; @end /** * Describes a proto enum. **/ @interface GPBEnumDescriptor : NSObject /** Name of the enum. */ @property(nonatomic, readonly, copy) NSString *name; /** Function that validates that raw values are valid enum values. */ @property(nonatomic, readonly) GPBEnumValidationFunc enumVerifier; /** * Returns the enum value name for the given raw enum. * * @param number The raw enum value. * * @return The name of the enum value passed, or nil if not valid. **/ - (nullable NSString *)enumNameForValue:(int32_t)number; /** * Gets the enum raw value for the given enum name. * * @param outValue A pointer where the value will be set. * @param name The enum name for which to get the raw value. * * @return YES if a value was copied into the pointer, NO otherwise. **/ - (BOOL)getValue:(nullable int32_t *)outValue forEnumName:(NSString *)name; /** * Returns the text format for the given raw enum value. * * @param number The raw enum value. * * @return The text format name for the raw enum value, or nil if not valid. **/ - (nullable NSString *)textFormatNameForValue:(int32_t)number; /** * Gets the enum raw value for the given text format name. * * @param outValue A pointer where the value will be set. * @param textFormatName The text format name for which to get the raw value. * * @return YES if a value was copied into the pointer, NO otherwise. **/ - (BOOL)getValue:(nullable int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName; @end /** * Describes a proto extension. **/ @interface GPBExtensionDescriptor : NSObject /** Field number under which the extension is stored. */ @property(nonatomic, readonly) uint32_t fieldNumber; /** The containing message class, i.e. the class extended by this extension. */ @property(nonatomic, readonly) Class containingMessageClass; /** Data type contained in the extension. */ @property(nonatomic, readonly) GPBDataType dataType; /** Whether the extension is repeated. */ @property(nonatomic, readonly, getter=isRepeated) BOOL repeated; /** Whether the extension is packable. */ @property(nonatomic, readonly, getter=isPackable) BOOL packable; /** The class of the message if the extension is of message type. */ @property(nonatomic, readonly, assign) Class msgClass; /** The singleton name for the extension. */ @property(nonatomic, readonly) NSString *singletonName; /** The enum descriptor if the extension is of enum type. */ @property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor; /** The default value for the extension. */ @property(nonatomic, readonly, nullable) id defaultValue; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDescriptor.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBDescriptor_PackagePrivate.h" #import #import "GPBUtilities_PackagePrivate.h" #import "GPBWireFormat.h" #import "GPBMessage_PackagePrivate.h" // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" // The addresses of these variables are used as keys for objc_getAssociatedObject. static const char kTextFormatExtraValueKey = 0; static const char kParentClassNameValueKey = 0; static const char kClassNameSuffixKey = 0; // Utility function to generate selectors on the fly. static SEL SelFromStrings(const char *prefix, const char *middle, const char *suffix, BOOL takesArg) { if (prefix == NULL && suffix == NULL && !takesArg) { return sel_getUid(middle); } const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0; const size_t middleLen = strlen(middle); const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0; size_t totalLen = prefixLen + middleLen + suffixLen + 1; // include space for null on end. if (takesArg) { totalLen += 1; } char buffer[totalLen]; if (prefix != NULL) { memcpy(buffer, prefix, prefixLen); memcpy(buffer + prefixLen, middle, middleLen); buffer[prefixLen] = (char)toupper(buffer[prefixLen]); } else { memcpy(buffer, middle, middleLen); } if (suffix != NULL) { memcpy(buffer + prefixLen + middleLen, suffix, suffixLen); } if (takesArg) { buffer[totalLen - 2] = ':'; } // Always null terminate it. buffer[totalLen - 1] = 0; SEL result = sel_getUid(buffer); return result; } static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) __attribute__((ns_returns_retained)); static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) { NSMutableArray *result = [[NSMutableArray alloc] init]; for (GPBFieldDescriptor *fieldDesc in allMessageFields) { if (fieldDesc->description_->hasIndex == hasIndex) { [result addObject:fieldDesc]; } } return result; } @implementation GPBDescriptor { Class messageClass_; GPBFileDescriptor *file_; BOOL wireFormat_; } @synthesize messageClass = messageClass_; @synthesize fields = fields_; @synthesize oneofs = oneofs_; @synthesize extensionRanges = extensionRanges_; @synthesize extensionRangesCount = extensionRangesCount_; @synthesize file = file_; @synthesize wireFormat = wireFormat_; + (instancetype) allocDescriptorForClass:(Class)messageClass rootClass:(Class)rootClass file:(GPBFileDescriptor *)file fields:(void *)fieldDescriptions fieldCount:(uint32_t)fieldCount storageSize:(uint32_t)storageSize flags:(GPBDescriptorInitializationFlags)flags { // The rootClass is no longer used, but it is passed in to ensure it // was started up during initialization also. (void)rootClass; NSMutableArray *fields = nil; GPBFileSyntax syntax = file.syntax; BOOL fieldsIncludeDefault = (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0; void *desc; for (uint32_t i = 0; i < fieldCount; ++i) { if (fields == nil) { fields = [[NSMutableArray alloc] initWithCapacity:fieldCount]; } // Need correctly typed pointer for array indexing below to work. if (fieldsIncludeDefault) { GPBMessageFieldDescriptionWithDefault *fieldDescWithDefault = fieldDescriptions; desc = &(fieldDescWithDefault[i]); } else { GPBMessageFieldDescription *fieldDesc = fieldDescriptions; desc = &(fieldDesc[i]); } GPBFieldDescriptor *fieldDescriptor = [[GPBFieldDescriptor alloc] initWithFieldDescription:desc includesDefault:fieldsIncludeDefault syntax:syntax]; [fields addObject:fieldDescriptor]; [fieldDescriptor release]; } BOOL wireFormat = (flags & GPBDescriptorInitializationFlag_WireFormat) != 0; GPBDescriptor *descriptor = [[self alloc] initWithClass:messageClass file:file fields:fields storageSize:storageSize wireFormat:wireFormat]; [fields release]; return descriptor; } - (instancetype)initWithClass:(Class)messageClass file:(GPBFileDescriptor *)file fields:(NSArray *)fields storageSize:(uint32_t)storageSize wireFormat:(BOOL)wireFormat { if ((self = [super init])) { messageClass_ = messageClass; file_ = file; fields_ = [fields retain]; storageSize_ = storageSize; wireFormat_ = wireFormat; } return self; } - (void)dealloc { [fields_ release]; [oneofs_ release]; [super dealloc]; } - (void)setupOneofs:(const char **)oneofNames count:(uint32_t)count firstHasIndex:(int32_t)firstHasIndex { NSCAssert(firstHasIndex < 0, @"Should always be <0"); NSMutableArray *oneofs = [[NSMutableArray alloc] initWithCapacity:count]; for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) { const char *name = oneofNames[i]; NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_); NSCAssert(fieldsForOneof.count > 0, @"No fields for this oneof? (%s:%d)", name, hasIndex); GPBOneofDescriptor *oneofDescriptor = [[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof]; [oneofs addObject:oneofDescriptor]; [oneofDescriptor release]; [fieldsForOneof release]; } oneofs_ = oneofs; } - (void)setupExtraTextInfo:(const char *)extraTextFormatInfo { // Extra info is a compile time option, so skip the work if not needed. if (extraTextFormatInfo) { NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo]; for (GPBFieldDescriptor *fieldDescriptor in fields_) { if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) { objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, extraInfoValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } } } - (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count { extensionRanges_ = ranges; extensionRangesCount_ = count; } - (void)setupContainingMessageClassName:(const char *)msgClassName { // Note: Only fetch the class here, can't send messages to it because // that could cause cycles back to this class within +initialize if // two messages have each other in fields (i.e. - they build a graph). NSAssert(objc_getClass(msgClassName), @"Class %s not defined", msgClassName); NSValue *parentNameValue = [NSValue valueWithPointer:msgClassName]; objc_setAssociatedObject(self, &kParentClassNameValueKey, parentNameValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (void)setupMessageClassNameSuffix:(NSString *)suffix { if (suffix.length) { objc_setAssociatedObject(self, &kClassNameSuffixKey, suffix, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } - (NSString *)name { return NSStringFromClass(messageClass_); } - (GPBDescriptor *)containingType { NSValue *parentNameValue = objc_getAssociatedObject(self, &kParentClassNameValueKey); if (!parentNameValue) { return nil; } const char *parentName = [parentNameValue pointerValue]; Class parentClass = objc_getClass(parentName); NSAssert(parentClass, @"Class %s not defined", parentName); return [parentClass descriptor]; } - (NSString *)fullName { NSString *className = NSStringFromClass(self.messageClass); GPBFileDescriptor *file = self.file; NSString *objcPrefix = file.objcPrefix; if (objcPrefix && ![className hasPrefix:objcPrefix]) { NSAssert(0, @"Class didn't have correct prefix? (%@ - %@)", className, objcPrefix); return nil; } GPBDescriptor *parent = self.containingType; NSString *name = nil; if (parent) { NSString *parentClassName = NSStringFromClass(parent.messageClass); // The generator will add _Class to avoid reserved words, drop it. NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey); if (suffix) { if (![parentClassName hasSuffix:suffix]) { NSAssert(0, @"ParentMessage class didn't have correct suffix? (%@ - %@)", className, suffix); return nil; } parentClassName = [parentClassName substringToIndex:(parentClassName.length - suffix.length)]; } NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"]; if (![className hasPrefix:parentPrefix]) { NSAssert(0, @"Class didn't have the correct parent name prefix? (%@ - %@)", parentPrefix, className); return nil; } name = [className substringFromIndex:parentPrefix.length]; } else { name = [className substringFromIndex:objcPrefix.length]; } // The generator will add _Class to avoid reserved words, drop it. NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey); if (suffix) { if (![name hasSuffix:suffix]) { NSAssert(0, @"Message class didn't have correct suffix? (%@ - %@)", name, suffix); return nil; } name = [name substringToIndex:(name.length - suffix.length)]; } NSString *prefix = (parent != nil ? parent.fullName : file.package); NSString *result; if (prefix.length > 0) { result = [NSString stringWithFormat:@"%@.%@", prefix, name]; } else { result = name; } return result; } - (id)copyWithZone:(NSZone *)zone { #pragma unused(zone) return [self retain]; } - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { for (GPBFieldDescriptor *descriptor in fields_) { if (GPBFieldNumber(descriptor) == fieldNumber) { return descriptor; } } return nil; } - (GPBFieldDescriptor *)fieldWithName:(NSString *)name { for (GPBFieldDescriptor *descriptor in fields_) { if ([descriptor.name isEqual:name]) { return descriptor; } } return nil; } - (GPBOneofDescriptor *)oneofWithName:(NSString *)name { for (GPBOneofDescriptor *descriptor in oneofs_) { if ([descriptor.name isEqual:name]) { return descriptor; } } return nil; } @end @implementation GPBFileDescriptor { NSString *package_; NSString *objcPrefix_; GPBFileSyntax syntax_; } @synthesize package = package_; @synthesize objcPrefix = objcPrefix_; @synthesize syntax = syntax_; - (instancetype)initWithPackage:(NSString *)package objcPrefix:(NSString *)objcPrefix syntax:(GPBFileSyntax)syntax { self = [super init]; if (self) { package_ = [package copy]; objcPrefix_ = [objcPrefix copy]; syntax_ = syntax; } return self; } - (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax { self = [super init]; if (self) { package_ = [package copy]; syntax_ = syntax; } return self; } - (void)dealloc { [package_ release]; [objcPrefix_ release]; [super dealloc]; } @end @implementation GPBOneofDescriptor @synthesize fields = fields_; - (instancetype)initWithName:(const char *)name fields:(NSArray *)fields { self = [super init]; if (self) { name_ = name; fields_ = [fields retain]; for (GPBFieldDescriptor *fieldDesc in fields) { fieldDesc->containingOneof_ = self; } caseSel_ = SelFromStrings(NULL, name, "OneOfCase", NO); } return self; } - (void)dealloc { [fields_ release]; [super dealloc]; } - (NSString *)name { return @(name_); } - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { for (GPBFieldDescriptor *descriptor in fields_) { if (GPBFieldNumber(descriptor) == fieldNumber) { return descriptor; } } return nil; } - (GPBFieldDescriptor *)fieldWithName:(NSString *)name { for (GPBFieldDescriptor *descriptor in fields_) { if ([descriptor.name isEqual:name]) { return descriptor; } } return nil; } @end uint32_t GPBFieldTag(GPBFieldDescriptor *self) { GPBMessageFieldDescription *description = self->description_; GPBWireFormat format; if ((description->flags & GPBFieldMapKeyMask) != 0) { // Maps are repeated messages on the wire. format = GPBWireFormatForType(GPBDataTypeMessage, NO); } else { format = GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) != 0)); } return GPBWireFormatMakeTag(description->number, format); } uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { GPBMessageFieldDescription *description = self->description_; NSCAssert((description->flags & GPBFieldRepeated) != 0, @"Only valid on repeated fields"); GPBWireFormat format = GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) == 0)); return GPBWireFormatMakeTag(description->number, format); } @implementation GPBFieldDescriptor { GPBGenericValue defaultValue_; // Message ivars Class msgClass_; // Enum ivars. // If protos are generated with GenerateEnumDescriptors on then it will // be a enumDescriptor, otherwise it will be a enumVerifier. union { GPBEnumDescriptor *enumDescriptor_; GPBEnumValidationFunc enumVerifier_; } enumHandling_; } @synthesize msgClass = msgClass_; @synthesize containingOneof = containingOneof_; - (instancetype)init { // Throw an exception if people attempt to not use the designated initializer. self = [super init]; if (self != nil) { [self doesNotRecognizeSelector:_cmd]; self = nil; } return self; } - (instancetype)initWithFieldDescription:(void *)description includesDefault:(BOOL)includesDefault syntax:(GPBFileSyntax)syntax { if ((self = [super init])) { GPBMessageFieldDescription *coreDesc; if (includesDefault) { coreDesc = &(((GPBMessageFieldDescriptionWithDefault *)description)->core); } else { coreDesc = description; } description_ = coreDesc; getSel_ = sel_getUid(coreDesc->name); setSel_ = SelFromStrings("set", coreDesc->name, NULL, YES); GPBDataType dataType = coreDesc->dataType; BOOL isMessage = GPBDataTypeIsMessage(dataType); BOOL isMapOrArray = GPBFieldIsMapOrArray(self); if (isMapOrArray) { // map<>/repeated fields get a *Count property (inplace of a has*) to // support checking if there are any entries without triggering // autocreation. hasOrCountSel_ = SelFromStrings(NULL, coreDesc->name, "_Count", NO); } else { // If there is a positive hasIndex, then: // - All fields types for proto2 messages get has* selectors. // - Only message fields for proto3 messages get has* selectors. // Note: the positive check is to handle oneOfs, we can't check // containingOneof_ because it isn't set until after initialization. if ((coreDesc->hasIndex >= 0) && (coreDesc->hasIndex != GPBNoHasBit) && ((syntax != GPBFileSyntaxProto3) || isMessage)) { hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO); setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES); } } // Extra type specific data. if (isMessage) { const char *className = coreDesc->dataTypeSpecific.className; // Note: Only fetch the class here, can't send messages to it because // that could cause cycles back to this class within +initialize if // two messages have each other in fields (i.e. - they build a graph). msgClass_ = objc_getClass(className); NSAssert(msgClass_, @"Class %s not defined", className); } else if (dataType == GPBDataTypeEnum) { if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) { enumHandling_.enumDescriptor_ = coreDesc->dataTypeSpecific.enumDescFunc(); } else { enumHandling_.enumVerifier_ = coreDesc->dataTypeSpecific.enumVerifier; } } // Non map<>/repeated fields can have defaults in proto2 syntax. if (!isMapOrArray && includesDefault) { defaultValue_ = ((GPBMessageFieldDescriptionWithDefault *)description)->defaultValue; if (dataType == GPBDataTypeBytes) { // Data stored as a length prefixed (network byte order) c-string in // descriptor structure. const uint8_t *bytes = (const uint8_t *)defaultValue_.valueData; if (bytes) { uint32_t length = *((uint32_t *)bytes); length = ntohl(length); bytes += sizeof(length); defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length]; } } } } return self; } - (void)dealloc { if (description_->dataType == GPBDataTypeBytes && !(description_->flags & GPBFieldRepeated)) { [defaultValue_.valueData release]; } [super dealloc]; } - (GPBDataType)dataType { return description_->dataType; } - (BOOL)hasDefaultValue { return (description_->flags & GPBFieldHasDefaultValue) != 0; } - (uint32_t)number { return description_->number; } - (NSString *)name { return @(description_->name); } - (BOOL)isRequired { return (description_->flags & GPBFieldRequired) != 0; } - (BOOL)isOptional { return (description_->flags & GPBFieldOptional) != 0; } - (GPBFieldType)fieldType { GPBFieldFlags flags = description_->flags; if ((flags & GPBFieldRepeated) != 0) { return GPBFieldTypeRepeated; } else if ((flags & GPBFieldMapKeyMask) != 0) { return GPBFieldTypeMap; } else { return GPBFieldTypeSingle; } } - (GPBDataType)mapKeyDataType { switch (description_->flags & GPBFieldMapKeyMask) { case GPBFieldMapKeyInt32: return GPBDataTypeInt32; case GPBFieldMapKeyInt64: return GPBDataTypeInt64; case GPBFieldMapKeyUInt32: return GPBDataTypeUInt32; case GPBFieldMapKeyUInt64: return GPBDataTypeUInt64; case GPBFieldMapKeySInt32: return GPBDataTypeSInt32; case GPBFieldMapKeySInt64: return GPBDataTypeSInt64; case GPBFieldMapKeyFixed32: return GPBDataTypeFixed32; case GPBFieldMapKeyFixed64: return GPBDataTypeFixed64; case GPBFieldMapKeySFixed32: return GPBDataTypeSFixed32; case GPBFieldMapKeySFixed64: return GPBDataTypeSFixed64; case GPBFieldMapKeyBool: return GPBDataTypeBool; case GPBFieldMapKeyString: return GPBDataTypeString; default: NSAssert(0, @"Not a map type"); return GPBDataTypeInt32; // For lack of anything better. } } - (BOOL)isPackable { return (description_->flags & GPBFieldPacked) != 0; } - (BOOL)isValidEnumValue:(int32_t)value { NSAssert(description_->dataType == GPBDataTypeEnum, @"Field Must be of type GPBDataTypeEnum"); if (description_->flags & GPBFieldHasEnumDescriptor) { return enumHandling_.enumDescriptor_.enumVerifier(value); } else { return enumHandling_.enumVerifier_(value); } } - (GPBEnumDescriptor *)enumDescriptor { if (description_->flags & GPBFieldHasEnumDescriptor) { return enumHandling_.enumDescriptor_; } else { return nil; } } - (GPBGenericValue)defaultValue { // Depends on the fact that defaultValue_ is initialized either to "0/nil" or // to an actual defaultValue in our initializer. GPBGenericValue value = defaultValue_; if (!(description_->flags & GPBFieldRepeated)) { // We special handle data and strings. If they are nil, we replace them // with empty string/empty data. GPBDataType type = description_->dataType; if (type == GPBDataTypeBytes && value.valueData == nil) { value.valueData = GPBEmptyNSData(); } else if (type == GPBDataTypeString && value.valueString == nil) { value.valueString = @""; } } return value; } - (NSString *)textFormatName { if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) { NSValue *extraInfoValue = objc_getAssociatedObject(self, &kTextFormatExtraValueKey); // Support can be left out at generation time. if (!extraInfoValue) { return nil; } const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue]; return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), self.name); } // The logic here has to match SetCommonFieldVariables() from // objectivec_field.cc in the proto compiler. NSString *name = self.name; NSUInteger len = [name length]; // Remove the "_p" added to reserved names. if ([name hasSuffix:@"_p"]) { name = [name substringToIndex:(len - 2)]; len = [name length]; } // Remove "Array" from the end for repeated fields. if (((description_->flags & GPBFieldRepeated) != 0) && [name hasSuffix:@"Array"]) { name = [name substringToIndex:(len - 5)]; len = [name length]; } // Groups vs. other fields. if (description_->dataType == GPBDataTypeGroup) { // Just capitalize the first letter. unichar firstChar = [name characterAtIndex:0]; if (firstChar >= 'a' && firstChar <= 'z') { NSString *firstCharString = [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')]; NSString *result = [name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:firstCharString]; return result; } return name; } else { // Undo the CamelCase. NSMutableString *result = [NSMutableString stringWithCapacity:len]; for (uint32_t i = 0; i < len; i++) { unichar c = [name characterAtIndex:i]; if (c >= 'A' && c <= 'Z') { if (i > 0) { [result appendFormat:@"_%C", (unichar)(c - 'A' + 'a')]; } else { [result appendFormat:@"%C", c]; } } else { [result appendFormat:@"%C", c]; } } return result; } } @end @implementation GPBEnumDescriptor { NSString *name_; // valueNames_ is a single c string with all of the value names appended // together, each null terminated. -calcValueNameOffsets fills in // nameOffsets_ with the offsets to allow quicker access to the individual // names. const char *valueNames_; const int32_t *values_; GPBEnumValidationFunc enumVerifier_; const uint8_t *extraTextFormatInfo_; uint32_t *nameOffsets_; uint32_t valueCount_; } @synthesize name = name_; @synthesize enumVerifier = enumVerifier_; + (instancetype) allocDescriptorForName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier { GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name valueNames:valueNames values:values count:valueCount enumVerifier:enumVerifier]; return descriptor; } + (instancetype) allocDescriptorForName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier extraTextFormatInfo:(const char *)extraTextFormatInfo { // Call the common case. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name valueNames:valueNames values:values count:valueCount enumVerifier:enumVerifier]; // Set the extra info. descriptor->extraTextFormatInfo_ = (const uint8_t *)extraTextFormatInfo; return descriptor; } - (instancetype)initWithName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier { if ((self = [super init])) { name_ = [name copy]; valueNames_ = valueNames; values_ = values; valueCount_ = valueCount; enumVerifier_ = enumVerifier; } return self; } - (void)dealloc { [name_ release]; if (nameOffsets_) free(nameOffsets_); [super dealloc]; } - (void)calcValueNameOffsets { @synchronized(self) { if (nameOffsets_ != NULL) { return; } uint32_t *offsets = malloc(valueCount_ * sizeof(uint32_t)); const char *scan = valueNames_; for (uint32_t i = 0; i < valueCount_; ++i) { offsets[i] = (uint32_t)(scan - valueNames_); while (*scan != '\0') ++scan; ++scan; // Step over the null. } nameOffsets_ = offsets; } } - (NSString *)enumNameForValue:(int32_t)number { if (nameOffsets_ == NULL) [self calcValueNameOffsets]; for (uint32_t i = 0; i < valueCount_; ++i) { if (values_[i] == number) { const char *valueName = valueNames_ + nameOffsets_[i]; NSString *fullName = [NSString stringWithFormat:@"%@_%s", name_, valueName]; return fullName; } } return nil; } - (BOOL)getValue:(int32_t *)outValue forEnumName:(NSString *)name { // Must have the prefix. NSUInteger prefixLen = name_.length + 1; if ((name.length <= prefixLen) || ![name hasPrefix:name_] || ([name characterAtIndex:prefixLen - 1] != '_')) { return NO; } // Skip over the prefix. const char *nameAsCStr = [name UTF8String]; nameAsCStr += prefixLen; if (nameOffsets_ == NULL) [self calcValueNameOffsets]; // Find it. for (uint32_t i = 0; i < valueCount_; ++i) { const char *valueName = valueNames_ + nameOffsets_[i]; if (strcmp(nameAsCStr, valueName) == 0) { if (outValue) { *outValue = values_[i]; } return YES; } } return NO; } - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName { if (nameOffsets_ == NULL) [self calcValueNameOffsets]; for (uint32_t i = 0; i < valueCount_; ++i) { int32_t value = values_[i]; NSString *valueTextFormatName = [self textFormatNameForValue:value]; if ([valueTextFormatName isEqual:textFormatName]) { if (outValue) { *outValue = value; } return YES; } } return NO; } - (NSString *)textFormatNameForValue:(int32_t)number { if (nameOffsets_ == NULL) [self calcValueNameOffsets]; // Find the EnumValue descriptor and its index. BOOL foundIt = NO; uint32_t valueDescriptorIndex; for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; ++valueDescriptorIndex) { if (values_[valueDescriptorIndex] == number) { foundIt = YES; break; } } if (!foundIt) { return nil; } NSString *result = nil; // Naming adds an underscore between enum name and value name, skip that also. const char *valueName = valueNames_ + nameOffsets_[valueDescriptorIndex]; NSString *shortName = @(valueName); // See if it is in the map of special format handling. if (extraTextFormatInfo_) { result = GPBDecodeTextFormatName(extraTextFormatInfo_, (int32_t)valueDescriptorIndex, shortName); } // Logic here needs to match what objectivec_enum.cc does in the proto // compiler. if (result == nil) { NSUInteger len = [shortName length]; NSMutableString *worker = [NSMutableString stringWithCapacity:len]; for (NSUInteger i = 0; i < len; i++) { unichar c = [shortName characterAtIndex:i]; if (i > 0 && c >= 'A' && c <= 'Z') { [worker appendString:@"_"]; } [worker appendFormat:@"%c", toupper((char)c)]; } result = worker; } return result; } @end @implementation GPBExtensionDescriptor { GPBGenericValue defaultValue_; } @synthesize containingMessageClass = containingMessageClass_; - (instancetype)initWithExtensionDescription: (GPBExtensionDescription *)description { if ((self = [super init])) { description_ = description; #if defined(DEBUG) && DEBUG const char *className = description->messageOrGroupClassName; if (className) { NSAssert(objc_lookUpClass(className) != Nil, @"Class %s not defined", className); } #endif if (description->extendedClass) { Class containingClass = objc_lookUpClass(description->extendedClass); NSAssert(containingClass, @"Class %s not defined", description->extendedClass); containingMessageClass_ = containingClass; } GPBDataType type = description_->dataType; if (type == GPBDataTypeBytes) { // Data stored as a length prefixed c-string in descriptor records. const uint8_t *bytes = (const uint8_t *)description->defaultValue.valueData; if (bytes) { uint32_t length = *((uint32_t *)bytes); // The length is stored in network byte order. length = ntohl(length); bytes += sizeof(length); defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length]; } } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) { // The default is looked up in -defaultValue instead since extensions // aren't common, we avoid the hit startup hit and it avoid initialization // order issues. } else { defaultValue_ = description->defaultValue; } } return self; } - (void)dealloc { if ((description_->dataType == GPBDataTypeBytes) && !GPBExtensionIsRepeated(description_)) { [defaultValue_.valueData release]; } [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { #pragma unused(zone) // Immutable. return [self retain]; } - (NSString *)singletonName { return @(description_->singletonName); } - (const char *)singletonNameC { return description_->singletonName; } - (uint32_t)fieldNumber { return description_->fieldNumber; } - (GPBDataType)dataType { return description_->dataType; } - (GPBWireFormat)wireType { return GPBWireFormatForType(description_->dataType, GPBExtensionIsPacked(description_)); } - (GPBWireFormat)alternateWireType { NSAssert(GPBExtensionIsRepeated(description_), @"Only valid on repeated extensions"); return GPBWireFormatForType(description_->dataType, !GPBExtensionIsPacked(description_)); } - (BOOL)isRepeated { return GPBExtensionIsRepeated(description_); } - (BOOL)isMap { return (description_->options & GPBFieldMapKeyMask) != 0; } - (BOOL)isPackable { return GPBExtensionIsPacked(description_); } - (Class)msgClass { return objc_getClass(description_->messageOrGroupClassName); } - (GPBEnumDescriptor *)enumDescriptor { if (description_->dataType == GPBDataTypeEnum) { GPBEnumDescriptor *enumDescriptor = description_->enumDescriptorFunc(); return enumDescriptor; } return nil; } - (id)defaultValue { if (GPBExtensionIsRepeated(description_)) { return nil; } switch (description_->dataType) { case GPBDataTypeBool: return @(defaultValue_.valueBool); case GPBDataTypeFloat: return @(defaultValue_.valueFloat); case GPBDataTypeDouble: return @(defaultValue_.valueDouble); case GPBDataTypeInt32: case GPBDataTypeSInt32: case GPBDataTypeEnum: case GPBDataTypeSFixed32: return @(defaultValue_.valueInt32); case GPBDataTypeInt64: case GPBDataTypeSInt64: case GPBDataTypeSFixed64: return @(defaultValue_.valueInt64); case GPBDataTypeUInt32: case GPBDataTypeFixed32: return @(defaultValue_.valueUInt32); case GPBDataTypeUInt64: case GPBDataTypeFixed64: return @(defaultValue_.valueUInt64); case GPBDataTypeBytes: // Like message fields, the default is zero length data. return (defaultValue_.valueData ? defaultValue_.valueData : GPBEmptyNSData()); case GPBDataTypeString: // Like message fields, the default is zero length string. return (defaultValue_.valueString ? defaultValue_.valueString : @""); case GPBDataTypeGroup: case GPBDataTypeMessage: return nil; } } - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other { int32_t selfNumber = description_->fieldNumber; int32_t otherNumber = other->description_->fieldNumber; if (selfNumber < otherNumber) { return NSOrderedAscending; } else if (selfNumber == otherNumber) { return NSOrderedSame; } else { return NSOrderedDescending; } } @end #pragma clang diagnostic pop ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDescriptor_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This header is private to the ProtobolBuffers library and must NOT be // included by any sources outside this library. The contents of this file are // subject to change at any time without notice. #import "GPBDescriptor.h" #import "GPBWireFormat.h" // Describes attributes of the field. typedef NS_OPTIONS(uint16_t, GPBFieldFlags) { GPBFieldNone = 0, // These map to standard protobuf concepts. GPBFieldRequired = 1 << 0, GPBFieldRepeated = 1 << 1, GPBFieldPacked = 1 << 2, GPBFieldOptional = 1 << 3, GPBFieldHasDefaultValue = 1 << 4, // Indicates the field needs custom handling for the TextFormat name, if not // set, the name can be derived from the ObjC name. GPBFieldTextFormatNameCustom = 1 << 6, // Indicates the field has an enum descriptor. GPBFieldHasEnumDescriptor = 1 << 7, // These are not standard protobuf concepts, they are specific to the // Objective C runtime. // These bits are used to mark the field as a map and what the key // type is. GPBFieldMapKeyMask = 0xF << 8, GPBFieldMapKeyInt32 = 1 << 8, GPBFieldMapKeyInt64 = 2 << 8, GPBFieldMapKeyUInt32 = 3 << 8, GPBFieldMapKeyUInt64 = 4 << 8, GPBFieldMapKeySInt32 = 5 << 8, GPBFieldMapKeySInt64 = 6 << 8, GPBFieldMapKeyFixed32 = 7 << 8, GPBFieldMapKeyFixed64 = 8 << 8, GPBFieldMapKeySFixed32 = 9 << 8, GPBFieldMapKeySFixed64 = 10 << 8, GPBFieldMapKeyBool = 11 << 8, GPBFieldMapKeyString = 12 << 8, }; // NOTE: The structures defined here have their members ordered to minimize // their size. This directly impacts the size of apps since these exist per // field/extension. // Describes a single field in a protobuf as it is represented as an ivar. typedef struct GPBMessageFieldDescription { // Name of ivar. const char *name; union { const char *className; // Name for message class. // For enums only: If EnumDescriptors are compiled in, it will be that, // otherwise it will be the verifier. GPBEnumDescriptorFunc enumDescFunc; GPBEnumValidationFunc enumVerifier; } dataTypeSpecific; // The field number for the ivar. uint32_t number; // The index (in bits) into _has_storage_. // >= 0: the bit to use for a value being set. // = GPBNoHasBit(INT32_MAX): no storage used. // < 0: in a oneOf, use a full int32 to record the field active. int32_t hasIndex; // Offset of the variable into it's structure struct. uint32_t offset; // Field flags. Use accessor functions below. GPBFieldFlags flags; // Data type of the ivar. GPBDataType dataType; } GPBMessageFieldDescription; // Fields in messages defined in a 'proto2' syntax file can provide a default // value. This struct provides the default along with the field info. typedef struct GPBMessageFieldDescriptionWithDefault { // Default value for the ivar. GPBGenericValue defaultValue; GPBMessageFieldDescription core; } GPBMessageFieldDescriptionWithDefault; // Describes attributes of the extension. typedef NS_OPTIONS(uint8_t, GPBExtensionOptions) { GPBExtensionNone = 0, // These map to standard protobuf concepts. GPBExtensionRepeated = 1 << 0, GPBExtensionPacked = 1 << 1, GPBExtensionSetWireFormat = 1 << 2, }; // An extension typedef struct GPBExtensionDescription { GPBGenericValue defaultValue; const char *singletonName; const char *extendedClass; const char *messageOrGroupClassName; GPBEnumDescriptorFunc enumDescriptorFunc; int32_t fieldNumber; GPBDataType dataType; GPBExtensionOptions options; } GPBExtensionDescription; typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { GPBDescriptorInitializationFlag_None = 0, GPBDescriptorInitializationFlag_FieldsWithDefault = 1 << 0, GPBDescriptorInitializationFlag_WireFormat = 1 << 1, }; @interface GPBDescriptor () { @package NSArray *fields_; NSArray *oneofs_; uint32_t storageSize_; } // fieldDescriptions have to be long lived, they are held as raw pointers. + (instancetype) allocDescriptorForClass:(Class)messageClass rootClass:(Class)rootClass file:(GPBFileDescriptor *)file fields:(void *)fieldDescriptions fieldCount:(uint32_t)fieldCount storageSize:(uint32_t)storageSize flags:(GPBDescriptorInitializationFlags)flags; - (instancetype)initWithClass:(Class)messageClass file:(GPBFileDescriptor *)file fields:(NSArray *)fields storageSize:(uint32_t)storage wireFormat:(BOOL)wireFormat; // Called right after init to provide extra information to avoid init having // an explosion of args. These pointers are recorded, so they are expected // to live for the lifetime of the app. - (void)setupOneofs:(const char **)oneofNames count:(uint32_t)count firstHasIndex:(int32_t)firstHasIndex; - (void)setupExtraTextInfo:(const char *)extraTextFormatInfo; - (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count; - (void)setupContainingMessageClassName:(const char *)msgClassName; - (void)setupMessageClassNameSuffix:(NSString *)suffix; @end @interface GPBFileDescriptor () - (instancetype)initWithPackage:(NSString *)package objcPrefix:(NSString *)objcPrefix syntax:(GPBFileSyntax)syntax; - (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax; @end @interface GPBOneofDescriptor () { @package const char *name_; NSArray *fields_; SEL caseSel_; } // name must be long lived. - (instancetype)initWithName:(const char *)name fields:(NSArray *)fields; @end @interface GPBFieldDescriptor () { @package GPBMessageFieldDescription *description_; GPB_UNSAFE_UNRETAINED GPBOneofDescriptor *containingOneof_; SEL getSel_; SEL setSel_; SEL hasOrCountSel_; // *Count for map<>/repeated fields, has* otherwise. SEL setHasSel_; } // Single initializer // description has to be long lived, it is held as a raw pointer. - (instancetype)initWithFieldDescription:(void *)description includesDefault:(BOOL)includesDefault syntax:(GPBFileSyntax)syntax; @end @interface GPBEnumDescriptor () // valueNames, values and extraTextFormatInfo have to be long lived, they are // held as raw pointers. + (instancetype) allocDescriptorForName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier; + (instancetype) allocDescriptorForName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier extraTextFormatInfo:(const char *)extraTextFormatInfo; - (instancetype)initWithName:(NSString *)name valueNames:(const char *)valueNames values:(const int32_t *)values count:(uint32_t)valueCount enumVerifier:(GPBEnumValidationFunc)enumVerifier; @end @interface GPBExtensionDescriptor () { @package GPBExtensionDescription *description_; } @property(nonatomic, readonly) GPBWireFormat wireType; // For repeated extensions, alternateWireType is the wireType with the opposite // value for the packable property. i.e. - if the extension was marked packed // it would be the wire type for unpacked; if the extension was marked unpacked, // it would be the wire type for packed. @property(nonatomic, readonly) GPBWireFormat alternateWireType; // description has to be long lived, it is held as a raw pointer. - (instancetype)initWithExtensionDescription: (GPBExtensionDescription *)description; - (NSComparisonResult)compareByFieldNumber:(GPBExtensionDescriptor *)other; @end CF_EXTERN_C_BEGIN // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" GPB_INLINE BOOL GPBFieldIsMapOrArray(GPBFieldDescriptor *field) { return (field->description_->flags & (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0; } GPB_INLINE GPBDataType GPBGetFieldDataType(GPBFieldDescriptor *field) { return field->description_->dataType; } GPB_INLINE int32_t GPBFieldHasIndex(GPBFieldDescriptor *field) { return field->description_->hasIndex; } GPB_INLINE uint32_t GPBFieldNumber(GPBFieldDescriptor *field) { return field->description_->number; } #pragma clang diagnostic pop uint32_t GPBFieldTag(GPBFieldDescriptor *self); // For repeated fields, alternateWireType is the wireType with the opposite // value for the packable property. i.e. - if the field was marked packed it // would be the wire type for unpacked; if the field was marked unpacked, it // would be the wire type for packed. uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self); GPB_INLINE BOOL GPBPreserveUnknownFields(GPBFileSyntax syntax) { return syntax != GPBFileSyntaxProto3; } GPB_INLINE BOOL GPBHasPreservingUnknownEnumSemantics(GPBFileSyntax syntax) { return syntax == GPBFileSyntaxProto3; } GPB_INLINE BOOL GPBExtensionIsRepeated(GPBExtensionDescription *description) { return (description->options & GPBExtensionRepeated) != 0; } GPB_INLINE BOOL GPBExtensionIsPacked(GPBExtensionDescription *description) { return (description->options & GPBExtensionPacked) != 0; } GPB_INLINE BOOL GPBExtensionIsWireFormat(GPBExtensionDescription *description) { return (description->options & GPBExtensionSetWireFormat) != 0; } // Helper for compile time assets. #ifndef GPBInternalCompileAssert #if __has_feature(c_static_assert) || __has_extension(c_static_assert) #define GPBInternalCompileAssert(test, msg) _Static_assert((test), #msg) #else // Pre-Xcode 7 support. #define GPBInternalCompileAssertSymbolInner(line, msg) GPBInternalCompileAssert ## line ## __ ## msg #define GPBInternalCompileAssertSymbol(line, msg) GPBInternalCompileAssertSymbolInner(line, msg) #define GPBInternalCompileAssert(test, msg) \ typedef char GPBInternalCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] #endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) #endif // GPBInternalCompileAssert // Sanity check that there isn't padding between the field description // structures with and without a default. GPBInternalCompileAssert(sizeof(GPBMessageFieldDescriptionWithDefault) == (sizeof(GPBGenericValue) + sizeof(GPBMessageFieldDescription)), DescriptionsWithDefault_different_size_than_expected); CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDictionary.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBRuntimeTypes.h" // Note on naming: for the classes holding numeric values, a more natural // naming of the method might be things like "-valueForKey:", // "-setValue:forKey:"; etc. But those selectors are also defined by Key Value // Coding (KVC) as categories on NSObject. So "overloading" the selectors with // other meanings can cause warnings (based on compiler settings), but more // importantly, some of those selector get called as KVC breaks up keypaths. // So if those selectors are used, using KVC will compile cleanly, but could // crash as it invokes those selectors with the wrong types of arguments. NS_ASSUME_NONNULL_BEGIN //%PDDM-EXPAND DECLARE_DICTIONARIES() // This block of code is generated, do not edit it directly. #pragma mark - UInt32 -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32UInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(uint32_t key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32UInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32Int32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32Int32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(uint32_t key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32Int32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32UInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(uint32_t key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32UInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32Int64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32Int64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(uint32_t key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32Int64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32BoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32BoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(uint32_t key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32BoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32FloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32FloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(uint32_t key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32FloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32DoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32DoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(uint32_t key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32DoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32EnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBUInt32EnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(uint32_t key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(uint32_t key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(uint32_t)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt32 -> Object /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt32ObjectDictionary<__covariant ObjectType> : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param object The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(uint32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param objects The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const uint32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param objects The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const uint32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt32ObjectDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Fetches the object stored under the given key. * * @param key Key under which the value is stored, if present. * * @return The object if found, nil otherwise. **/ - (ObjectType)objectForKey:(uint32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **object**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(uint32_t key, ObjectType object, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt32ObjectDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param object The value to set. * @param key The key under which to store the value. **/ - (void)setObject:(ObjectType)object forKey:(uint32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeObjectForKey:(uint32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32UInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32UInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(int32_t key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32UInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32Int32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32Int32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(int32_t key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32Int32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32UInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32UInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(int32_t key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32UInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32Int64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32Int64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(int32_t key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32Int64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32BoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32BoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(int32_t key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32BoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32FloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32FloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(int32_t key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32FloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32DoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32DoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(int32_t key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32DoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32EnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBInt32EnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(int32_t key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(int32_t key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(int32_t)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int32 -> Object /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt32ObjectDictionary<__covariant ObjectType> : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param object The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(int32_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param objects The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const int32_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param objects The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const int32_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt32ObjectDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Fetches the object stored under the given key. * * @param key Key under which the value is stored, if present. * * @return The object if found, nil otherwise. **/ - (ObjectType)objectForKey:(int32_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **object**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(int32_t key, ObjectType object, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt32ObjectDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param object The value to set. * @param key The key under which to store the value. **/ - (void)setObject:(ObjectType)object forKey:(int32_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeObjectForKey:(int32_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64UInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(uint64_t key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64UInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64Int32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64Int32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(uint64_t key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64Int32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64UInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(uint64_t key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64UInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64Int64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64Int64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(uint64_t key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64Int64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64BoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64BoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(uint64_t key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64BoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64FloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64FloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(uint64_t key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64FloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64DoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64DoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(uint64_t key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64DoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64EnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBUInt64EnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(uint64_t key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(uint64_t key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(uint64_t)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - UInt64 -> Object /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBUInt64ObjectDictionary<__covariant ObjectType> : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param object The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(uint64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param objects The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const uint64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param objects The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const uint64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBUInt64ObjectDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Fetches the object stored under the given key. * * @param key Key under which the value is stored, if present. * * @return The object if found, nil otherwise. **/ - (ObjectType)objectForKey:(uint64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **object**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(uint64_t key, ObjectType object, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBUInt64ObjectDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param object The value to set. * @param key The key under which to store the value. **/ - (void)setObject:(ObjectType)object forKey:(uint64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeObjectForKey:(uint64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64UInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64UInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(int64_t key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64UInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64Int32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64Int32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(int64_t key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64Int32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64UInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64UInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(int64_t key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64UInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64Int64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64Int64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(int64_t key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64Int64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64BoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64BoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(int64_t key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64BoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64FloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64FloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(int64_t key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64FloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64DoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64DoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(int64_t key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64DoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64EnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBInt64EnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(int64_t key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(int64_t key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(int64_t)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Int64 -> Object /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBInt64ObjectDictionary<__covariant ObjectType> : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param object The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(int64_t)key; /** * Creates and initializes a dictionary with the entries given. * * @param objects The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const int64_t [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param objects The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const int64_t [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBInt64ObjectDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Fetches the object stored under the given key. * * @param key Key under which the value is stored, if present. * * @return The object if found, nil otherwise. **/ - (ObjectType)objectForKey:(int64_t)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **object**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(int64_t key, ObjectType object, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBInt64ObjectDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param object The value to set. * @param key The key under which to store the value. **/ - (void)setObject:(ObjectType)object forKey:(int64_t)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeObjectForKey:(int64_t)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolUInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolUInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(BOOL key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolUInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(BOOL key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolUInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolUInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(BOOL key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolUInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(BOOL key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolBoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolBoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(BOOL key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolBoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolFloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolFloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(BOOL key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolFloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolDoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolDoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(BOOL key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolDoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolEnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBBoolEnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(BOOL key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(BOOL key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBBoolEnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(BOOL)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - Bool -> Object /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBBoolObjectDictionary<__covariant ObjectType> : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param object The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(BOOL)key; /** * Creates and initializes a dictionary with the entries given. * * @param objects The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const BOOL [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param objects The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects forKeys:(const BOOL [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBBoolObjectDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Fetches the object stored under the given key. * * @param key Key under which the value is stored, if present. * * @return The object if found, nil otherwise. **/ - (ObjectType)objectForKey:(BOOL)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **object**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(BOOL key, ObjectType object, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBBoolObjectDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param object The value to set. * @param key The key under which to store the value. **/ - (void)setObject:(ObjectType)object forKey:(BOOL)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeObjectForKey:(BOOL)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> UInt32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringUInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringUInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(NSString *key, uint32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringUInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt32:(uint32_t)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt32ForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Int32 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringInt32Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringInt32Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt32:(nullable int32_t *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(NSString *key, int32_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringInt32Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt32:(int32_t)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt32ForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> UInt64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringUInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringUInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(NSString *key, uint64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringUInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setUInt64:(uint64_t)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeUInt64ForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Int64 /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringInt64Dictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringInt64Dictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getInt64:(nullable int64_t *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(NSString *key, int64_t value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringInt64Dictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setInt64:(int64_t)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeInt64ForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Bool /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringBoolDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithBool:(BOOL)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithBools:(const BOOL [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringBoolDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getBool:(nullable BOOL *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(NSString *key, BOOL value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringBoolDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setBool:(BOOL)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeBoolForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Float /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringFloatDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithFloat:(float)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithFloats:(const float [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringFloatDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getFloat:(nullable float *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(NSString *key, float value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringFloatDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setFloat:(float)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeFloatForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Double /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringDoubleDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the single entry given. * * @param value The value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithDouble:(double)value forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param values The values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; /** * Initializes this dictionary, copying the given values and keys. * * @param values The values to be placed in this dictionary. * @param keys The keys under which to store the values. * @param count The number of elements to copy into the dictionary. * * @return A newly initialized dictionary with a copy of the values and keys. **/ - (instancetype)initWithDoubles:(const double [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes this dictionary, copying the entries from the given dictionary. * * @param dictionary Dictionary containing the entries to add to this dictionary. * * @return A newly initialized dictionary with the entries of the given dictionary. **/ - (instancetype)initWithDictionary:(GPBStringDoubleDictionary *)dictionary; /** * Initializes this dictionary with the requested capacity. * * @param numItems Number of items needed for this dictionary. * * @return A newly initialized dictionary with the requested capacity. **/ - (instancetype)initWithCapacity:(NSUInteger)numItems; /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getDouble:(nullable double *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(NSString *key, double value, BOOL *stop))block; /** * Adds the keys and values from another dictionary. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addEntriesFromDictionary:(GPBStringDoubleDictionary *)otherDictionary; /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setDouble:(double)value forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeDoubleForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end #pragma mark - String -> Enum /** * Class used for map fields of * values. This performs better than boxing into NSNumbers in NSDictionaries. * * @note This class is not meant to be subclassed. **/ @interface GPBStringEnumDictionary : NSObject /** Number of entries stored in this dictionary. */ @property(nonatomic, readonly) NSUInteger count; /** The validation function to check if the enums are valid. */ @property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; /** * @return A newly instanced and empty dictionary. **/ + (instancetype)dictionary; /** * Creates and initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly instanced dictionary. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Creates and initializes a dictionary with the single entry given. * * @param func The enum validation function for the dictionary. * @param rawValue The raw enum value to be placed in the dictionary. * @param key The key under which to store the value. * * @return A newly instanced dictionary with the key and value in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(NSString *)key; /** * Creates and initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly instanced dictionary with the keys and values in it. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count; /** * Creates and initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly instanced dictionary with the entries from the given * dictionary in it. **/ + (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary; /** * Creates and initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly instanced dictionary with the given capacity. **/ + (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; /** * Initializes a dictionary with the given validation function. * * @param func The enum validation function for the dictionary. * * @return A newly initialized dictionary. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; /** * Initializes a dictionary with the entries given. * * @param func The enum validation function for the dictionary. * @param values The raw enum values values to be placed in the dictionary. * @param keys The keys under which to store the values. * @param count The number of entries to store in the dictionary. * * @return A newly initialized dictionary with the keys and values in it. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; /** * Initializes a dictionary with the entries from the given. * dictionary. * * @param dictionary Dictionary containing the entries to add to the dictionary. * * @return A newly initialized dictionary with the entries from the given * dictionary in it. **/ - (instancetype)initWithDictionary:(GPBStringEnumDictionary *)dictionary; /** * Initializes a dictionary with the given capacity. * * @param func The enum validation function for the dictionary. * @param numItems Capacity needed for the dictionary. * * @return A newly initialized dictionary with the given capacity. **/ - (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func capacity:(NSUInteger)numItems; // These will return kGPBUnrecognizedEnumeratorValue if the value for the key // is not a valid enumerator as defined by validationFunc. If the actual value is // desired, use "raw" version of the method. /** * Gets the value for the given key. * * @param value Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getEnum:(nullable int32_t *)value forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **value**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(NSString *key, int32_t value, BOOL *stop))block; /** * Gets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param rawValue Pointer into which the value will be set, if found. * @param key Key under which the value is stored, if present. * * @return YES if the key was found and the value was copied, NO otherwise. **/ - (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(NSString *)key; /** * Enumerates the keys and values on this dictionary with the given block. * * @note This method bypass the validationFunc to enable the access of values that * were not known at the time the binary was compiled. * * @param block The block to enumerate with. * **key**: The key for the current entry. * **rawValue**: The value for the current entry * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(NSString *key, int32_t rawValue, BOOL *stop))block; /** * Adds the keys and raw enum values from another dictionary. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param otherDictionary Dictionary containing entries to be added to this * dictionary. **/ - (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value // to the default value. Use the rawValue methods below to assign non enumerator // values. /** * Sets the value for the given key. * * @param value The value to set. * @param key The key under which to store the value. **/ - (void)setEnum:(int32_t)value forKey:(NSString *)key; /** * Sets the raw enum value for the given key. * * @note This method bypass the validationFunc to enable the setting of values that * were not known at the time the binary was compiled. * * @param rawValue The raw enum value to set. * @param key The key under which to store the raw enum value. **/ - (void)setRawValue:(int32_t)rawValue forKey:(NSString *)key; /** * Removes the entry for the given key. * * @param aKey Key to be removed from this dictionary. **/ - (void)removeEnumForKey:(NSString *)aKey; /** * Removes all entries in this dictionary. **/ - (void)removeAll; @end //%PDDM-EXPAND-END DECLARE_DICTIONARIES() NS_ASSUME_NONNULL_END //%PDDM-DEFINE DECLARE_DICTIONARIES() //%DICTIONARY_INTERFACES_FOR_POD_KEY(UInt32, uint32_t) //%DICTIONARY_INTERFACES_FOR_POD_KEY(Int32, int32_t) //%DICTIONARY_INTERFACES_FOR_POD_KEY(UInt64, uint64_t) //%DICTIONARY_INTERFACES_FOR_POD_KEY(Int64, int64_t) //%DICTIONARY_INTERFACES_FOR_POD_KEY(Bool, BOOL) //%DICTIONARY_POD_INTERFACES_FOR_KEY(String, NSString, *, OBJECT) //%PDDM-DEFINE DICTIONARY_INTERFACES_FOR_POD_KEY(KEY_NAME, KEY_TYPE) //%DICTIONARY_POD_INTERFACES_FOR_KEY(KEY_NAME, KEY_TYPE, , POD) //%DICTIONARY_POD_KEY_TO_OBJECT_INTERFACE(KEY_NAME, KEY_TYPE, Object, ObjectType) //%PDDM-DEFINE DICTIONARY_POD_INTERFACES_FOR_KEY(KEY_NAME, KEY_TYPE, KisP, KHELPER) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, UInt32, uint32_t) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Int32, int32_t) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, UInt64, uint64_t) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Int64, int64_t) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Bool, BOOL) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Float, float) //%DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Double, double) //%DICTIONARY_KEY_TO_ENUM_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, Enum, int32_t) //%PDDM-DEFINE DICTIONARY_KEY_TO_POD_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE) //%DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, POD, VALUE_NAME, value) //%PDDM-DEFINE DICTIONARY_POD_KEY_TO_OBJECT_INTERFACE(KEY_NAME, KEY_TYPE, VALUE_NAME, VALUE_TYPE) //%DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, , POD, VALUE_NAME, VALUE_TYPE, OBJECT, Object, object) //%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME) //%/** //% * Gets the value for the given key. //% * //% * @param value Pointer into which the value will be set, if found. //% * @param key Key under which the value is stored, if present. //% * //% * @return YES if the key was found and the value was copied, NO otherwise. //% **/ //%- (BOOL)get##VNAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key; //%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_TYPE, VNAME) //%/** //% * Fetches the object stored under the given key. //% * //% * @param key Key under which the value is stored, if present. //% * //% * @return The object if found, nil otherwise. //% **/ //%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key; //%PDDM-DEFINE VALUE_FOR_KEY_Enum(KEY_TYPE, VALUE_TYPE, VNAME) //%VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME) //%PDDM-DEFINE ARRAY_ARG_MODIFIERPOD() // Nothing //%PDDM-DEFINE ARRAY_ARG_MODIFIEREnum() // Nothing //%PDDM-DEFINE ARRAY_ARG_MODIFIEROBJECT() //%GPB_UNSAFE_UNRETAINED ## //%PDDM-DEFINE DICTIONARY_CLASS_DECLPOD(KEY_NAME, VALUE_NAME, VALUE_TYPE) //%GPB##KEY_NAME##VALUE_NAME##Dictionary //%PDDM-DEFINE DICTIONARY_CLASS_DECLEnum(KEY_NAME, VALUE_NAME, VALUE_TYPE) //%GPB##KEY_NAME##VALUE_NAME##Dictionary //%PDDM-DEFINE DICTIONARY_CLASS_DECLOBJECT(KEY_NAME, VALUE_NAME, VALUE_TYPE) //%GPB##KEY_NAME##VALUE_NAME##Dictionary<__covariant VALUE_TYPE> //%PDDM-DEFINE DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) //%#pragma mark - KEY_NAME -> VALUE_NAME //% //%/** //% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##> //% * values. This performs better than boxing into NSNumbers in NSDictionaries. //% * //% * @note This class is not meant to be subclassed. //% **/ //%@interface DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) : NSObject //% //%/** Number of entries stored in this dictionary. */ //%@property(nonatomic, readonly) NSUInteger count; //% //%/** //% * @return A newly instanced and empty dictionary. //% **/ //%+ (instancetype)dictionary; //% //%/** //% * Creates and initializes a dictionary with the single entry given. //% * //% * @param ##VNAME_VAR The value to be placed in the dictionary. //% * @param key ##VNAME_VAR$S## The key under which to store the value. //% * //% * @return A newly instanced dictionary with the key and value in it. //% **/ //%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR //% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key; //% //%/** //% * Creates and initializes a dictionary with the entries given. //% * //% * @param ##VNAME_VAR##s The values to be placed in the dictionary. //% * @param keys ##VNAME_VAR$S## The keys under which to store the values. //% * @param count ##VNAME_VAR$S## The number of entries to store in the dictionary. //% * //% * @return A newly instanced dictionary with the keys and values in it. //% **/ //%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s //% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys //% ##VNAME$S## count:(NSUInteger)count; //% //%/** //% * Creates and initializes a dictionary with the entries from the given. //% * dictionary. //% * //% * @param dictionary Dictionary containing the entries to add to the dictionary. //% * //% * @return A newly instanced dictionary with the entries from the given //% * dictionary in it. //% **/ //%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; //% //%/** //% * Creates and initializes a dictionary with the given capacity. //% * //% * @param numItems Capacity needed for the dictionary. //% * //% * @return A newly instanced dictionary with the given capacity. //% **/ //%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; //% //%/** //% * Initializes this dictionary, copying the given values and keys. //% * //% * @param ##VNAME_VAR##s The values to be placed in this dictionary. //% * @param keys ##VNAME_VAR$S## The keys under which to store the values. //% * @param count ##VNAME_VAR$S## The number of elements to copy into the dictionary. //% * //% * @return A newly initialized dictionary with a copy of the values and keys. //% **/ //%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s //% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys //% ##VNAME$S## count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; //% //%/** //% * Initializes this dictionary, copying the entries from the given dictionary. //% * //% * @param dictionary Dictionary containing the entries to add to this dictionary. //% * //% * @return A newly initialized dictionary with the entries of the given dictionary. //% **/ //%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; //% //%/** //% * Initializes this dictionary with the requested capacity. //% * //% * @param numItems Number of items needed for this dictionary. //% * //% * @return A newly initialized dictionary with the requested capacity. //% **/ //%- (instancetype)initWithCapacity:(NSUInteger)numItems; //% //%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) //% //%/** //% * Adds the keys and values from another dictionary. //% * //% * @param otherDictionary Dictionary containing entries to be added to this //% * dictionary. //% **/ //%- (void)addEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary; //% //%DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) //% //%@end //% //%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE) //%DICTIONARY_KEY_TO_ENUM_INTERFACE2(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, Enum) //%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_INTERFACE2(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER) //%#pragma mark - KEY_NAME -> VALUE_NAME //% //%/** //% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##> //% * values. This performs better than boxing into NSNumbers in NSDictionaries. //% * //% * @note This class is not meant to be subclassed. //% **/ //%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary : NSObject //% //%/** Number of entries stored in this dictionary. */ //%@property(nonatomic, readonly) NSUInteger count; //%/** The validation function to check if the enums are valid. */ //%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc; //% //%/** //% * @return A newly instanced and empty dictionary. //% **/ //%+ (instancetype)dictionary; //% //%/** //% * Creates and initializes a dictionary with the given validation function. //% * //% * @param func The enum validation function for the dictionary. //% * //% * @return A newly instanced dictionary. //% **/ //%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func; //% //%/** //% * Creates and initializes a dictionary with the single entry given. //% * //% * @param func The enum validation function for the dictionary. //% * @param rawValue The raw enum value to be placed in the dictionary. //% * @param key The key under which to store the value. //% * //% * @return A newly instanced dictionary with the key and value in it. //% **/ //%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValue:(VALUE_TYPE)rawValue //% forKey:(KEY_TYPE##KisP$S##KisP)key; //% //%/** //% * Creates and initializes a dictionary with the entries given. //% * //% * @param func The enum validation function for the dictionary. //% * @param values The raw enum values values to be placed in the dictionary. //% * @param keys The keys under which to store the values. //% * @param count The number of entries to store in the dictionary. //% * //% * @return A newly instanced dictionary with the keys and values in it. //% **/ //%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values //% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys //% count:(NSUInteger)count; //% //%/** //% * Creates and initializes a dictionary with the entries from the given. //% * dictionary. //% * //% * @param dictionary Dictionary containing the entries to add to the dictionary. //% * //% * @return A newly instanced dictionary with the entries from the given //% * dictionary in it. //% **/ //%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; //% //%/** //% * Creates and initializes a dictionary with the given capacity. //% * //% * @param func The enum validation function for the dictionary. //% * @param numItems Capacity needed for the dictionary. //% * //% * @return A newly instanced dictionary with the given capacity. //% **/ //%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)numItems; //% //%/** //% * Initializes a dictionary with the given validation function. //% * //% * @param func The enum validation function for the dictionary. //% * //% * @return A newly initialized dictionary. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func; //% //%/** //% * Initializes a dictionary with the entries given. //% * //% * @param func The enum validation function for the dictionary. //% * @param values The raw enum values values to be placed in the dictionary. //% * @param keys The keys under which to store the values. //% * @param count The number of entries to store in the dictionary. //% * //% * @return A newly initialized dictionary with the keys and values in it. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values //% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys //% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER; //% //%/** //% * Initializes a dictionary with the entries from the given. //% * dictionary. //% * //% * @param dictionary Dictionary containing the entries to add to the dictionary. //% * //% * @return A newly initialized dictionary with the entries from the given //% * dictionary in it. //% **/ //%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary; //% //%/** //% * Initializes a dictionary with the given capacity. //% * //% * @param func The enum validation function for the dictionary. //% * @param numItems Capacity needed for the dictionary. //% * //% * @return A newly initialized dictionary with the given capacity. //% **/ //%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func //% capacity:(NSUInteger)numItems; //% //%// These will return kGPBUnrecognizedEnumeratorValue if the value for the key //%// is not a valid enumerator as defined by validationFunc. If the actual value is //%// desired, use "raw" version of the method. //% //%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, Enum, value) //% //%/** //% * Gets the raw enum value for the given key. //% * //% * @note This method bypass the validationFunc to enable the access of values that //% * were not known at the time the binary was compiled. //% * //% * @param rawValue Pointer into which the value will be set, if found. //% * @param key Key under which the value is stored, if present. //% * //% * @return YES if the key was found and the value was copied, NO otherwise. //% **/ //%- (BOOL)getRawValue:(nullable VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key; //% //%/** //% * Enumerates the keys and values on this dictionary with the given block. //% * //% * @note This method bypass the validationFunc to enable the access of values that //% * were not known at the time the binary was compiled. //% * //% * @param block The block to enumerate with. //% * **key**: The key for the current entry. //% * **rawValue**: The value for the current entry //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateKeysAndRawValuesUsingBlock: //% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE rawValue, BOOL *stop))block; //% //%/** //% * Adds the keys and raw enum values from another dictionary. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param otherDictionary Dictionary containing entries to be added to this //% * dictionary. //% **/ //%- (void)addRawEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary; //% //%// If value is not a valid enumerator as defined by validationFunc, these //%// methods will assert in debug, and will log in release and assign the value //%// to the default value. Use the rawValue methods below to assign non enumerator //%// values. //% //%DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, Enum, value) //% //%@end //% //%PDDM-DEFINE DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) //%VALUE_FOR_KEY_##VHELPER(KEY_TYPE##KisP$S##KisP, VALUE_TYPE, VNAME) //% //%/** //% * Enumerates the keys and values on this dictionary with the given block. //% * //% * @param block The block to enumerate with. //% * **key**: ##VNAME_VAR$S## The key for the current entry. //% * **VNAME_VAR**: The value for the current entry //% * **stop**: ##VNAME_VAR$S## A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateKeysAnd##VNAME##sUsingBlock: //% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block; //%PDDM-DEFINE DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR) //%/** //% * Sets the value for the given key. //% * //% * @param ##VNAME_VAR The value to set. //% * @param key ##VNAME_VAR$S## The key under which to store the value. //% **/ //%- (void)set##VNAME##:(VALUE_TYPE)##VNAME_VAR forKey:(KEY_TYPE##KisP$S##KisP)key; //%DICTIONARY_EXTRA_MUTABLE_METHODS_##VHELPER(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) //%/** //% * Removes the entry for the given key. //% * //% * @param aKey Key to be removed from this dictionary. //% **/ //%- (void)remove##VNAME##ForKey:(KEY_TYPE##KisP$S##KisP)aKey; //% //%/** //% * Removes all entries in this dictionary. //% **/ //%- (void)removeAll; //%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_POD(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) // Empty //%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_OBJECT(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) // Empty //%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_Enum(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE) //% //%/** //% * Sets the raw enum value for the given key. //% * //% * @note This method bypass the validationFunc to enable the setting of values that //% * were not known at the time the binary was compiled. //% * //% * @param rawValue The raw enum value to set. //% * @param key The key under which to store the raw enum value. //% **/ //%- (void)setRawValue:(VALUE_TYPE)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key; //% ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDictionary.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBDictionary_PackagePrivate.h" #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" // ------------------------------ NOTE ------------------------------ // At the moment, this is all using NSNumbers in NSDictionaries under // the hood, but it is all hidden so we can come back and optimize // with direct CFDictionary usage later. The reason that wasn't // done yet is needing to support 32bit iOS builds. Otherwise // it would be pretty simple to store all this data in CFDictionaries // directly. // ------------------------------------------------------------------ // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" // Used to include code only visible to specific versions of the static // analyzer. Useful for wrapping code that only exists to silence the analyzer. // Determine the values you want to use for BEGIN_APPLE_BUILD_VERSION, // END_APPLE_BUILD_VERSION using: // xcrun clang -dM -E -x c /dev/null | grep __apple_build_version__ // Example usage: // #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif #define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ (defined(__clang_analyzer__) && \ (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \ __apple_build_version__ <= END_APPLE_BUILD_VERSION)) enum { kMapKeyFieldNumber = 1, kMapValueFieldNumber = 2, }; static BOOL DictDefault_IsValidValue(int32_t value) { // Anything but the bad value marker is allowed. return (value != kGPBUnrecognizedEnumeratorValue); } //%PDDM-DEFINE SERIALIZE_SUPPORT_2_TYPE(VALUE_NAME, VALUE_TYPE, GPBDATATYPE_NAME1, GPBDATATYPE_NAME2) //%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { //% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { //% return GPBCompute##GPBDATATYPE_NAME1##Size(fieldNum, value); //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { //% return GPBCompute##GPBDATATYPE_NAME2##Size(fieldNum, value); //% } else { //% NSCAssert(NO, @"Unexpected type %d", dataType); //% return 0; //% } //%} //% //%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { //% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { //% [stream write##GPBDATATYPE_NAME1##:fieldNum value:value]; //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { //% [stream write##GPBDATATYPE_NAME2##:fieldNum value:value]; //% } else { //% NSCAssert(NO, @"Unexpected type %d", dataType); //% } //%} //% //%PDDM-DEFINE SERIALIZE_SUPPORT_3_TYPE(VALUE_NAME, VALUE_TYPE, GPBDATATYPE_NAME1, GPBDATATYPE_NAME2, GPBDATATYPE_NAME3) //%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { //% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { //% return GPBCompute##GPBDATATYPE_NAME1##Size(fieldNum, value); //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { //% return GPBCompute##GPBDATATYPE_NAME2##Size(fieldNum, value); //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME3) { //% return GPBCompute##GPBDATATYPE_NAME3##Size(fieldNum, value); //% } else { //% NSCAssert(NO, @"Unexpected type %d", dataType); //% return 0; //% } //%} //% //%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { //% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { //% [stream write##GPBDATATYPE_NAME1##:fieldNum value:value]; //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME2) { //% [stream write##GPBDATATYPE_NAME2##:fieldNum value:value]; //% } else if (dataType == GPBDataType##GPBDATATYPE_NAME3) { //% [stream write##GPBDATATYPE_NAME3##:fieldNum value:value]; //% } else { //% NSCAssert(NO, @"Unexpected type %d", dataType); //% } //%} //% //%PDDM-DEFINE SIMPLE_SERIALIZE_SUPPORT(VALUE_NAME, VALUE_TYPE, VisP) //%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE VisP##value, uint32_t fieldNum, GPBDataType dataType) { //% NSCAssert(dataType == GPBDataType##VALUE_NAME, @"bad type: %d", dataType); //% #pragma unused(dataType) // For when asserts are off in release. //% return GPBCompute##VALUE_NAME##Size(fieldNum, value); //%} //% //%static void WriteDict##VALUE_NAME##Field(GPBCodedOutputStream *stream, VALUE_TYPE VisP##value, uint32_t fieldNum, GPBDataType dataType) { //% NSCAssert(dataType == GPBDataType##VALUE_NAME, @"bad type: %d", dataType); //% #pragma unused(dataType) // For when asserts are off in release. //% [stream write##VALUE_NAME##:fieldNum value:value]; //%} //% //%PDDM-DEFINE SERIALIZE_SUPPORT_HELPERS() //%SERIALIZE_SUPPORT_3_TYPE(Int32, int32_t, Int32, SInt32, SFixed32) //%SERIALIZE_SUPPORT_2_TYPE(UInt32, uint32_t, UInt32, Fixed32) //%SERIALIZE_SUPPORT_3_TYPE(Int64, int64_t, Int64, SInt64, SFixed64) //%SERIALIZE_SUPPORT_2_TYPE(UInt64, uint64_t, UInt64, Fixed64) //%SIMPLE_SERIALIZE_SUPPORT(Bool, BOOL, ) //%SIMPLE_SERIALIZE_SUPPORT(Enum, int32_t, ) //%SIMPLE_SERIALIZE_SUPPORT(Float, float, ) //%SIMPLE_SERIALIZE_SUPPORT(Double, double, ) //%SIMPLE_SERIALIZE_SUPPORT(String, NSString, *) //%SERIALIZE_SUPPORT_3_TYPE(Object, id, Message, String, Bytes) //%PDDM-EXPAND SERIALIZE_SUPPORT_HELPERS() // This block of code is generated, do not edit it directly. static size_t ComputeDictInt32FieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeInt32) { return GPBComputeInt32Size(fieldNum, value); } else if (dataType == GPBDataTypeSInt32) { return GPBComputeSInt32Size(fieldNum, value); } else if (dataType == GPBDataTypeSFixed32) { return GPBComputeSFixed32Size(fieldNum, value); } else { NSCAssert(NO, @"Unexpected type %d", dataType); return 0; } } static void WriteDictInt32Field(GPBCodedOutputStream *stream, int32_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeInt32) { [stream writeInt32:fieldNum value:value]; } else if (dataType == GPBDataTypeSInt32) { [stream writeSInt32:fieldNum value:value]; } else if (dataType == GPBDataTypeSFixed32) { [stream writeSFixed32:fieldNum value:value]; } else { NSCAssert(NO, @"Unexpected type %d", dataType); } } static size_t ComputeDictUInt32FieldSize(uint32_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeUInt32) { return GPBComputeUInt32Size(fieldNum, value); } else if (dataType == GPBDataTypeFixed32) { return GPBComputeFixed32Size(fieldNum, value); } else { NSCAssert(NO, @"Unexpected type %d", dataType); return 0; } } static void WriteDictUInt32Field(GPBCodedOutputStream *stream, uint32_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeUInt32) { [stream writeUInt32:fieldNum value:value]; } else if (dataType == GPBDataTypeFixed32) { [stream writeFixed32:fieldNum value:value]; } else { NSCAssert(NO, @"Unexpected type %d", dataType); } } static size_t ComputeDictInt64FieldSize(int64_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeInt64) { return GPBComputeInt64Size(fieldNum, value); } else if (dataType == GPBDataTypeSInt64) { return GPBComputeSInt64Size(fieldNum, value); } else if (dataType == GPBDataTypeSFixed64) { return GPBComputeSFixed64Size(fieldNum, value); } else { NSCAssert(NO, @"Unexpected type %d", dataType); return 0; } } static void WriteDictInt64Field(GPBCodedOutputStream *stream, int64_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeInt64) { [stream writeInt64:fieldNum value:value]; } else if (dataType == GPBDataTypeSInt64) { [stream writeSInt64:fieldNum value:value]; } else if (dataType == GPBDataTypeSFixed64) { [stream writeSFixed64:fieldNum value:value]; } else { NSCAssert(NO, @"Unexpected type %d", dataType); } } static size_t ComputeDictUInt64FieldSize(uint64_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeUInt64) { return GPBComputeUInt64Size(fieldNum, value); } else if (dataType == GPBDataTypeFixed64) { return GPBComputeFixed64Size(fieldNum, value); } else { NSCAssert(NO, @"Unexpected type %d", dataType); return 0; } } static void WriteDictUInt64Field(GPBCodedOutputStream *stream, uint64_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeUInt64) { [stream writeUInt64:fieldNum value:value]; } else if (dataType == GPBDataTypeFixed64) { [stream writeFixed64:fieldNum value:value]; } else { NSCAssert(NO, @"Unexpected type %d", dataType); } } static size_t ComputeDictBoolFieldSize(BOOL value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeBool, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. return GPBComputeBoolSize(fieldNum, value); } static void WriteDictBoolField(GPBCodedOutputStream *stream, BOOL value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeBool, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. [stream writeBool:fieldNum value:value]; } static size_t ComputeDictEnumFieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeEnum, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. return GPBComputeEnumSize(fieldNum, value); } static void WriteDictEnumField(GPBCodedOutputStream *stream, int32_t value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeEnum, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. [stream writeEnum:fieldNum value:value]; } static size_t ComputeDictFloatFieldSize(float value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeFloat, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. return GPBComputeFloatSize(fieldNum, value); } static void WriteDictFloatField(GPBCodedOutputStream *stream, float value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeFloat, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. [stream writeFloat:fieldNum value:value]; } static size_t ComputeDictDoubleFieldSize(double value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeDouble, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. return GPBComputeDoubleSize(fieldNum, value); } static void WriteDictDoubleField(GPBCodedOutputStream *stream, double value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeDouble, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. [stream writeDouble:fieldNum value:value]; } static size_t ComputeDictStringFieldSize(NSString *value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeString, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. return GPBComputeStringSize(fieldNum, value); } static void WriteDictStringField(GPBCodedOutputStream *stream, NSString *value, uint32_t fieldNum, GPBDataType dataType) { NSCAssert(dataType == GPBDataTypeString, @"bad type: %d", dataType); #pragma unused(dataType) // For when asserts are off in release. [stream writeString:fieldNum value:value]; } static size_t ComputeDictObjectFieldSize(id value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeMessage) { return GPBComputeMessageSize(fieldNum, value); } else if (dataType == GPBDataTypeString) { return GPBComputeStringSize(fieldNum, value); } else if (dataType == GPBDataTypeBytes) { return GPBComputeBytesSize(fieldNum, value); } else { NSCAssert(NO, @"Unexpected type %d", dataType); return 0; } } static void WriteDictObjectField(GPBCodedOutputStream *stream, id value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeMessage) { [stream writeMessage:fieldNum value:value]; } else if (dataType == GPBDataTypeString) { [stream writeString:fieldNum value:value]; } else if (dataType == GPBDataTypeBytes) { [stream writeBytes:fieldNum value:value]; } else { NSCAssert(NO, @"Unexpected type %d", dataType); } } //%PDDM-EXPAND-END SERIALIZE_SUPPORT_HELPERS() size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { GPBDataType mapValueType = GPBGetFieldDataType(field); __block size_t result = 0; [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { #pragma unused(stop) size_t msgSize = GPBComputeStringSize(kMapKeyFieldNumber, key); msgSize += ComputeDictObjectFieldSize(obj, kMapValueFieldNumber, mapValueType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * dict.count; return result; } void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream, NSDictionary *dict, GPBFieldDescriptor *field) { NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); GPBDataType mapValueType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = GPBComputeStringSize(kMapKeyFieldNumber, key); msgSize += ComputeDictObjectFieldSize(obj, kMapValueFieldNumber, mapValueType); // Write the size and fields. [outputStream writeInt32NoTag:(int32_t)msgSize]; [outputStream writeString:kMapKeyFieldNumber value:key]; WriteDictObjectField(outputStream, obj, kMapValueFieldNumber, mapValueType); }]; } BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type"); #pragma unused(field) // For when asserts are off in release. for (GPBMessage *msg in [dict objectEnumerator]) { if (!msg.initialized) { return NO; } } return YES; } // Note: if the type is an object, it the retain pass back to the caller. static void ReadValue(GPBCodedInputStream *stream, GPBGenericValue *valueToFill, GPBDataType type, GPBExtensionRegistry *registry, GPBFieldDescriptor *field) { switch (type) { case GPBDataTypeBool: valueToFill->valueBool = GPBCodedInputStreamReadBool(&stream->state_); break; case GPBDataTypeFixed32: valueToFill->valueUInt32 = GPBCodedInputStreamReadFixed32(&stream->state_); break; case GPBDataTypeSFixed32: valueToFill->valueInt32 = GPBCodedInputStreamReadSFixed32(&stream->state_); break; case GPBDataTypeFloat: valueToFill->valueFloat = GPBCodedInputStreamReadFloat(&stream->state_); break; case GPBDataTypeFixed64: valueToFill->valueUInt64 = GPBCodedInputStreamReadFixed64(&stream->state_); break; case GPBDataTypeSFixed64: valueToFill->valueInt64 = GPBCodedInputStreamReadSFixed64(&stream->state_); break; case GPBDataTypeDouble: valueToFill->valueDouble = GPBCodedInputStreamReadDouble(&stream->state_); break; case GPBDataTypeInt32: valueToFill->valueInt32 = GPBCodedInputStreamReadInt32(&stream->state_); break; case GPBDataTypeInt64: valueToFill->valueInt64 = GPBCodedInputStreamReadInt32(&stream->state_); break; case GPBDataTypeSInt32: valueToFill->valueInt32 = GPBCodedInputStreamReadSInt32(&stream->state_); break; case GPBDataTypeSInt64: valueToFill->valueInt64 = GPBCodedInputStreamReadSInt64(&stream->state_); break; case GPBDataTypeUInt32: valueToFill->valueUInt32 = GPBCodedInputStreamReadUInt32(&stream->state_); break; case GPBDataTypeUInt64: valueToFill->valueUInt64 = GPBCodedInputStreamReadUInt64(&stream->state_); break; case GPBDataTypeBytes: [valueToFill->valueData release]; valueToFill->valueData = GPBCodedInputStreamReadRetainedBytes(&stream->state_); break; case GPBDataTypeString: [valueToFill->valueString release]; valueToFill->valueString = GPBCodedInputStreamReadRetainedString(&stream->state_); break; case GPBDataTypeMessage: { GPBMessage *message = [[field.msgClass alloc] init]; [stream readMessage:message extensionRegistry:registry]; [valueToFill->valueMessage release]; valueToFill->valueMessage = message; break; } case GPBDataTypeGroup: NSCAssert(NO, @"Can't happen"); break; case GPBDataTypeEnum: valueToFill->valueEnum = GPBCodedInputStreamReadEnum(&stream->state_); break; } } void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, GPBExtensionRegistry *registry, GPBFieldDescriptor *field, GPBMessage *parentMessage) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); GPBGenericValue key; GPBGenericValue value; // Zero them (but pick up any enum default for proto2). key.valueString = value.valueString = nil; if (valueDataType == GPBDataTypeEnum) { value = field.defaultValue; } GPBCodedInputStreamState *state = &stream->state_; uint32_t keyTag = GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO)); uint32_t valueTag = GPBWireFormatMakeTag(kMapValueFieldNumber, GPBWireFormatForType(valueDataType, NO)); BOOL hitError = NO; while (YES) { uint32_t tag = GPBCodedInputStreamReadTag(state); if (tag == keyTag) { ReadValue(stream, &key, keyDataType, registry, field); } else if (tag == valueTag) { ReadValue(stream, &value, valueDataType, registry, field); } else if (tag == 0) { // zero signals EOF / limit reached break; } else { // Unknown if (![stream skipField:tag]){ hitError = YES; break; } } } if (!hitError) { // Handle the special defaults and/or missing key/value. if ((keyDataType == GPBDataTypeString) && (key.valueString == nil)) { key.valueString = [@"" retain]; } if (GPBDataTypeIsObject(valueDataType) && value.valueString == nil) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" switch (valueDataType) { case GPBDataTypeString: value.valueString = [@"" retain]; break; case GPBDataTypeBytes: value.valueData = [GPBEmptyNSData() retain]; break; #if defined(__clang_analyzer__) case GPBDataTypeGroup: // Maps can't really have Groups as the value type, but this case is needed // so the analyzer won't report the posibility of send nil in for the value // in the NSMutableDictionary case below. #endif case GPBDataTypeMessage: { value.valueMessage = [[field.msgClass alloc] init]; break; } default: // Nothing break; } #pragma clang diagnostic pop } if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { #if GPB_STATIC_ANALYZER_ONLY(6020053, 7000181) // Limited to Xcode 6.4 - 7.2, are known to fail here. The upper end can // be raised as needed for new Xcodes. // // This is only needed on a "shallow" analyze; on a "deep" analyze, the // existing code path gets this correct. In shallow, the analyzer decides // GPBDataTypeIsObject(valueDataType) is both false and true on a single // path through this function, allowing nil to be used for the // setObject:forKey:. if (value.valueString == nil) { value.valueString = [@"" retain]; } #endif // mapDictionary is an NSMutableDictionary [(NSMutableDictionary *)mapDictionary setObject:value.valueString forKey:key.valueString]; } else { if (valueDataType == GPBDataTypeEnum) { if (GPBHasPreservingUnknownEnumSemantics([parentMessage descriptor].file.syntax) || [field isValidEnumValue:value.valueEnum]) { [mapDictionary setGPBGenericValue:&value forGPBGenericValueKey:&key]; } else { NSData *data = [mapDictionary serializedDataForUnknownValue:value.valueEnum forKey:&key keyDataType:keyDataType]; [parentMessage addUnknownMapEntry:GPBFieldNumber(field) value:data]; } } else { [mapDictionary setGPBGenericValue:&value forGPBGenericValueKey:&key]; } } } if (GPBDataTypeIsObject(keyDataType)) { [key.valueString release]; } if (GPBDataTypeIsObject(valueDataType)) { [value.valueString release]; } } // // Macros for the common basic cases. // //%PDDM-DEFINE DICTIONARY_IMPL_FOR_POD_KEY(KEY_NAME, KEY_TYPE) //%DICTIONARY_POD_IMPL_FOR_KEY(KEY_NAME, KEY_TYPE, , POD) //%DICTIONARY_POD_KEY_TO_OBJECT_IMPL(KEY_NAME, KEY_TYPE, Object, id) //%PDDM-DEFINE DICTIONARY_POD_IMPL_FOR_KEY(KEY_NAME, KEY_TYPE, KisP, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, UInt32, uint32_t, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Int32, int32_t, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, UInt64, uint64_t, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Int64, int64_t, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Bool, BOOL, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Float, float, KHELPER) //%DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, Double, double, KHELPER) //%DICTIONARY_KEY_TO_ENUM_IMPL(KEY_NAME, KEY_TYPE, KisP, Enum, int32_t, KHELPER) //%PDDM-DEFINE DICTIONARY_KEY_TO_POD_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER) //%DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, POD, VALUE_NAME, value) //%PDDM-DEFINE DICTIONARY_POD_KEY_TO_OBJECT_IMPL(KEY_NAME, KEY_TYPE, VALUE_NAME, VALUE_TYPE) //%DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, , VALUE_NAME, VALUE_TYPE, POD, OBJECT, Object, object) //%PDDM-DEFINE DICTIONARY_COMMON_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR) //%#pragma mark - KEY_NAME -> VALUE_NAME //% //%@implementation GPB##KEY_NAME##VALUE_NAME##Dictionary { //% @package //% NSMutableDictionary *_dictionary; //%} //% //%+ (instancetype)dictionary { //% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease]; //%} //% //%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR //% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key { //% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR //% KEY_NAME$S VALUE_NAME$S ##VNAME$S## forKeys:&key //% KEY_NAME$S VALUE_NAME$S ##VNAME$S## count:1] autorelease]; //%} //% //%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s //% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP [])keys //% ##VNAME$S## count:(NSUInteger)count { //% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s //% KEY_NAME$S VALUE_NAME$S forKeys:keys //% KEY_NAME$S VALUE_NAME$S count:count] autorelease]; //%} //% //%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { //% // Cast is needed so the compiler knows what class we are invoking initWithDictionary: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; //%} //% //%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { //% return [[[self alloc] initWithCapacity:numItems] autorelease]; //%} //% //%- (instancetype)init { //% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; //%} //% //%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s //% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP [])keys //% ##VNAME$S## count:(NSUInteger)count { //% self = [super init]; //% if (self) { //% _dictionary = [[NSMutableDictionary alloc] init]; //% if (count && VNAME_VAR##s && keys) { //% for (NSUInteger i = 0; i < count; ++i) { //%DICTIONARY_VALIDATE_VALUE_##VHELPER(VNAME_VAR##s[i], ______)##DICTIONARY_VALIDATE_KEY_##KHELPER(keys[i], ______) [_dictionary setObject:WRAPPED##VHELPER(VNAME_VAR##s[i]) forKey:WRAPPED##KHELPER(keys[i])]; //% } //% } //% } //% return self; //%} //% //%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { //% self = [self initWith##VNAME##s:NULL forKeys:NULL count:0]; //% if (self) { //% if (dictionary) { //% [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; //% } //% } //% return self; //%} //% //%- (instancetype)initWithCapacity:(NSUInteger)numItems { //% #pragma unused(numItems) //% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; //%} //% //%DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ) //% //%VALUE_FOR_KEY_##VHELPER(KEY_TYPE##KisP$S##KisP, VALUE_NAME, VALUE_TYPE, KHELPER) //% //%DICTIONARY_MUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ) //% //%@end //% //%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_IMPL(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER) //%DICTIONARY_KEY_TO_ENUM_IMPL2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, POD) //%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_IMPL2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER) //%#pragma mark - KEY_NAME -> VALUE_NAME //% //%@implementation GPB##KEY_NAME##VALUE_NAME##Dictionary { //% @package //% NSMutableDictionary *_dictionary; //% GPBEnumValidationFunc _validationFunc; //%} //% //%@synthesize validationFunc = _validationFunc; //% //%+ (instancetype)dictionary { //% return [[[self alloc] initWithValidationFunction:NULL //% rawValues:NULL //% forKeys:NULL //% count:0] autorelease]; //%} //% //%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { //% return [[[self alloc] initWithValidationFunction:func //% rawValues:NULL //% forKeys:NULL //% count:0] autorelease]; //%} //% //%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func //% rawValue:(VALUE_TYPE)rawValue //% forKey:(KEY_TYPE##KisP$S##KisP)key { //% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func //% KEY_NAME$S VALUE_NAME$S rawValues:&rawValue //% KEY_NAME$S VALUE_NAME$S forKeys:&key //% KEY_NAME$S VALUE_NAME$S count:1] autorelease]; //%} //% //%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func //% rawValues:(const VALUE_TYPE [])rawValues //% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys //% count:(NSUInteger)count { //% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithValidationFunction:func //% KEY_NAME$S VALUE_NAME$S rawValues:rawValues //% KEY_NAME$S VALUE_NAME$S forKeys:keys //% KEY_NAME$S VALUE_NAME$S count:count] autorelease]; //%} //% //%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { //% // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: //% // on to get the type correct. //% return [[(GPB##KEY_NAME##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; //%} //% //%+ (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func //% capacity:(NSUInteger)numItems { //% return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; //%} //% //%- (instancetype)init { //% return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; //%} //% //%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { //% return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; //%} //% //%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func //% rawValues:(const VALUE_TYPE [])rawValues //% forKeys:(const KEY_TYPE##KisP$S##KisP [])keys //% count:(NSUInteger)count { //% self = [super init]; //% if (self) { //% _dictionary = [[NSMutableDictionary alloc] init]; //% _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); //% if (count && rawValues && keys) { //% for (NSUInteger i = 0; i < count; ++i) { //%DICTIONARY_VALIDATE_KEY_##KHELPER(keys[i], ______) [_dictionary setObject:WRAPPED##VHELPER(rawValues[i]) forKey:WRAPPED##KHELPER(keys[i])]; //% } //% } //% } //% return self; //%} //% //%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary { //% self = [self initWithValidationFunction:dictionary.validationFunc //% rawValues:NULL //% forKeys:NULL //% count:0]; //% if (self) { //% if (dictionary) { //% [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; //% } //% } //% return self; //%} //% //%- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func //% capacity:(NSUInteger)numItems { //% #pragma unused(numItems) //% return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; //%} //% //%DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, Value, value, Raw) //% //%- (BOOL)getEnum:(VALUE_TYPE *)value forKey:(KEY_TYPE##KisP$S##KisP)key { //% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; //% if (wrapped && value) { //% VALUE_TYPE result = UNWRAP##VALUE_NAME(wrapped); //% if (!_validationFunc(result)) { //% result = kGPBUnrecognizedEnumeratorValue; //% } //% *value = result; //% } //% return (wrapped != NULL); //%} //% //%- (BOOL)getRawValue:(VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key { //% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; //% if (wrapped && rawValue) { //% *rawValue = UNWRAP##VALUE_NAME(wrapped); //% } //% return (wrapped != NULL); //%} //% //%- (void)enumerateKeysAndEnumsUsingBlock: //% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE value, BOOL *stop))block { //% GPBEnumValidationFunc func = _validationFunc; //% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey, //% ENUM_TYPE##VHELPER(VALUE_TYPE)##aValue, //% BOOL *stop) { //% VALUE_TYPE unwrapped = UNWRAP##VALUE_NAME(aValue); //% if (!func(unwrapped)) { //% unwrapped = kGPBUnrecognizedEnumeratorValue; //% } //% block(UNWRAP##KEY_NAME(aKey), unwrapped, stop); //% }]; //%} //% //%DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, Value, Enum, value, Raw) //% //%- (void)setEnum:(VALUE_TYPE)value forKey:(KEY_TYPE##KisP$S##KisP)key { //%DICTIONARY_VALIDATE_KEY_##KHELPER(key, ) if (!_validationFunc(value)) { //% [NSException raise:NSInvalidArgumentException //% format:@"GPB##KEY_NAME##VALUE_NAME##Dictionary: Attempt to set an unknown enum value (%d)", //% value]; //% } //% //% [_dictionary setObject:WRAPPED##VHELPER(value) forKey:WRAPPED##KHELPER(key)]; //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //%} //% //%@end //% //%PDDM-DEFINE DICTIONARY_IMMUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ACCESSOR_NAME) //%- (void)dealloc { //% NSAssert(!_autocreator, //% @"%@: Autocreator must be cleared before release, autocreator: %@", //% [self class], _autocreator); //% [_dictionary release]; //% [super dealloc]; //%} //% //%- (instancetype)copyWithZone:(NSZone *)zone { //% return [[GPB##KEY_NAME##VALUE_NAME##Dictionary allocWithZone:zone] initWithDictionary:self]; //%} //% //%- (BOOL)isEqual:(id)other { //% if (self == other) { //% return YES; //% } //% if (![other isKindOfClass:[GPB##KEY_NAME##VALUE_NAME##Dictionary class]]) { //% return NO; //% } //% GPB##KEY_NAME##VALUE_NAME##Dictionary *otherDictionary = other; //% return [_dictionary isEqual:otherDictionary->_dictionary]; //%} //% //%- (NSUInteger)hash { //% return _dictionary.count; //%} //% //%- (NSString *)description { //% return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; //%} //% //%- (NSUInteger)count { //% return _dictionary.count; //%} //% //%- (void)enumerateKeysAnd##ACCESSOR_NAME##VNAME##sUsingBlock: //% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block { //% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey, //% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u, //% BOOL *stop) { //% block(UNWRAP##KEY_NAME(aKey), UNWRAP##VALUE_NAME(a##VNAME_VAR$u), stop); //% }]; //%} //% //%EXTRA_METHODS_##VHELPER(KEY_NAME, VALUE_NAME)- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { //% NSUInteger count = _dictionary.count; //% if (count == 0) { //% return 0; //% } //% //% GPBDataType valueDataType = GPBGetFieldDataType(field); //% GPBDataType keyDataType = field.mapKeyDataType; //% __block size_t result = 0; //% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey, //% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u##, //% BOOL *stop) { //% #pragma unused(stop) //% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType); //% msgSize += ComputeDict##VALUE_NAME##FieldSize(UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType); //% result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; //% }]; //% size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); //% result += tagSize * count; //% return result; //%} //% //%- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream //% asField:(GPBFieldDescriptor *)field { //% GPBDataType valueDataType = GPBGetFieldDataType(field); //% GPBDataType keyDataType = field.mapKeyDataType; //% uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); //% [_dictionary enumerateKeysAndObjectsUsingBlock:^(ENUM_TYPE##KHELPER(KEY_TYPE)##aKey, //% ENUM_TYPE##VHELPER(VALUE_TYPE)##a##VNAME_VAR$u, //% BOOL *stop) { //% #pragma unused(stop) //% // Write the tag. //% [outputStream writeInt32NoTag:tag]; //% // Write the size of the message. //% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType); //% msgSize += ComputeDict##VALUE_NAME##FieldSize(UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType); //% [outputStream writeInt32NoTag:(int32_t)msgSize]; //% // Write the fields. //% WriteDict##KEY_NAME##Field(outputStream, UNWRAP##KEY_NAME(aKey), kMapKeyFieldNumber, keyDataType); //% WriteDict##VALUE_NAME##Field(outputStream, UNWRAP##VALUE_NAME(a##VNAME_VAR$u), kMapValueFieldNumber, valueDataType); //% }]; //%} //% //%SERIAL_DATA_FOR_ENTRY_##VHELPER(KEY_NAME, VALUE_NAME)- (void)setGPBGenericValue:(GPBGenericValue *)value //% forGPBGenericValueKey:(GPBGenericValue *)key { //% [_dictionary setObject:WRAPPED##VHELPER(value->##GPBVALUE_##VHELPER(VALUE_NAME)##) forKey:WRAPPED##KHELPER(key->value##KEY_NAME)]; //%} //% //%- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { //% [self enumerateKeysAnd##ACCESSOR_NAME##VNAME##sUsingBlock:^(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop) { //% #pragma unused(stop) //% block(TEXT_FORMAT_OBJ##KEY_NAME(key), TEXT_FORMAT_OBJ##VALUE_NAME(VNAME_VAR)); //% }]; //%} //%PDDM-DEFINE DICTIONARY_MUTABLE_CORE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_VAR, ACCESSOR_NAME) //%DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME, VNAME_VAR, ACCESSOR_NAME) //%PDDM-DEFINE DICTIONARY_MUTABLE_CORE2(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, KHELPER, VHELPER, VNAME, VNAME_REMOVE, VNAME_VAR, ACCESSOR_NAME) //%- (void)add##ACCESSOR_NAME##EntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary { //% if (otherDictionary) { //% [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //% } //%} //% //%- (void)set##ACCESSOR_NAME##VNAME##:(VALUE_TYPE)VNAME_VAR forKey:(KEY_TYPE##KisP$S##KisP)key { //%DICTIONARY_VALIDATE_VALUE_##VHELPER(VNAME_VAR, )##DICTIONARY_VALIDATE_KEY_##KHELPER(key, ) [_dictionary setObject:WRAPPED##VHELPER(VNAME_VAR) forKey:WRAPPED##KHELPER(key)]; //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //%} //% //%- (void)remove##VNAME_REMOVE##ForKey:(KEY_TYPE##KisP$S##KisP)aKey { //% [_dictionary removeObjectForKey:WRAPPED##KHELPER(aKey)]; //%} //% //%- (void)removeAll { //% [_dictionary removeAllObjects]; //%} // // Custom Generation for Bool keys // //%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_POD_IMPL(VALUE_NAME, VALUE_TYPE) //%DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, POD, VALUE_NAME, value) //%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(VALUE_NAME, VALUE_TYPE) //%DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, OBJECT, Object, object) //%PDDM-DEFINE DICTIONARY_BOOL_KEY_TO_VALUE_IMPL(VALUE_NAME, VALUE_TYPE, HELPER, VNAME, VNAME_VAR) //%#pragma mark - Bool -> VALUE_NAME //% //%@implementation GPBBool##VALUE_NAME##Dictionary { //% @package //% VALUE_TYPE _values[2]; //%BOOL_DICT_HAS_STORAGE_##HELPER()} //% //%+ (instancetype)dictionary { //% return [[[self alloc] initWith##VNAME##s:NULL forKeys:NULL count:0] autorelease]; //%} //% //%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)VNAME_VAR //% ##VNAME$S## forKey:(BOOL)key { //% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count: //% // on to get the type correct. //% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:&##VNAME_VAR //% VALUE_NAME$S ##VNAME$S## forKeys:&key //% VALUE_NAME$S ##VNAME$S## count:1] autorelease]; //%} //% //%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE [])##VNAME_VAR##s //% ##VNAME$S## forKeys:(const BOOL [])keys //% ##VNAME$S## count:(NSUInteger)count { //% // Cast is needed so the compiler knows what class we are invoking initWith##VNAME##s:forKeys:count: //% // on to get the type correct. //% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWith##VNAME##s:##VNAME_VAR##s //% VALUE_NAME$S ##VNAME$S## forKeys:keys //% VALUE_NAME$S ##VNAME$S## count:count] autorelease]; //%} //% //%+ (instancetype)dictionaryWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary { //% // Cast is needed so the compiler knows what class we are invoking initWithDictionary: //% // on to get the type correct. //% return [[(GPBBool##VALUE_NAME##Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; //%} //% //%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { //% return [[[self alloc] initWithCapacity:numItems] autorelease]; //%} //% //%- (instancetype)init { //% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; //%} //% //%BOOL_DICT_INITS_##HELPER(VALUE_NAME, VALUE_TYPE) //% //%- (instancetype)initWithCapacity:(NSUInteger)numItems { //% #pragma unused(numItems) //% return [self initWith##VNAME##s:NULL forKeys:NULL count:0]; //%} //% //%BOOL_DICT_DEALLOC##HELPER() //% //%- (instancetype)copyWithZone:(NSZone *)zone { //% return [[GPBBool##VALUE_NAME##Dictionary allocWithZone:zone] initWithDictionary:self]; //%} //% //%- (BOOL)isEqual:(id)other { //% if (self == other) { //% return YES; //% } //% if (![other isKindOfClass:[GPBBool##VALUE_NAME##Dictionary class]]) { //% return NO; //% } //% GPBBool##VALUE_NAME##Dictionary *otherDictionary = other; //% if ((BOOL_DICT_W_HAS##HELPER(0, ) != BOOL_DICT_W_HAS##HELPER(0, otherDictionary->)) || //% (BOOL_DICT_W_HAS##HELPER(1, ) != BOOL_DICT_W_HAS##HELPER(1, otherDictionary->))) { //% return NO; //% } //% if ((BOOL_DICT_W_HAS##HELPER(0, ) && (NEQ_##HELPER(_values[0], otherDictionary->_values[0]))) || //% (BOOL_DICT_W_HAS##HELPER(1, ) && (NEQ_##HELPER(_values[1], otherDictionary->_values[1])))) { //% return NO; //% } //% return YES; //%} //% //%- (NSUInteger)hash { //% return (BOOL_DICT_W_HAS##HELPER(0, ) ? 1 : 0) + (BOOL_DICT_W_HAS##HELPER(1, ) ? 1 : 0); //%} //% //%- (NSString *)description { //% NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; //% if (BOOL_DICT_W_HAS##HELPER(0, )) { //% [result appendFormat:@"NO: STR_FORMAT_##HELPER(VALUE_NAME)", _values[0]]; //% } //% if (BOOL_DICT_W_HAS##HELPER(1, )) { //% [result appendFormat:@"YES: STR_FORMAT_##HELPER(VALUE_NAME)", _values[1]]; //% } //% [result appendString:@" }"]; //% return result; //%} //% //%- (NSUInteger)count { //% return (BOOL_DICT_W_HAS##HELPER(0, ) ? 1 : 0) + (BOOL_DICT_W_HAS##HELPER(1, ) ? 1 : 0); //%} //% //%BOOL_VALUE_FOR_KEY_##HELPER(VALUE_NAME, VALUE_TYPE) //% //%BOOL_SET_GPBVALUE_FOR_KEY_##HELPER(VALUE_NAME, VALUE_TYPE, VisP) //% //%- (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { //% if (BOOL_DICT_HAS##HELPER(0, )) { //% block(@"false", TEXT_FORMAT_OBJ##VALUE_NAME(_values[0])); //% } //% if (BOOL_DICT_W_HAS##HELPER(1, )) { //% block(@"true", TEXT_FORMAT_OBJ##VALUE_NAME(_values[1])); //% } //%} //% //%- (void)enumerateKeysAnd##VNAME##sUsingBlock: //% (void (^)(BOOL key, VALUE_TYPE VNAME_VAR, BOOL *stop))block { //% BOOL stop = NO; //% if (BOOL_DICT_HAS##HELPER(0, )) { //% block(NO, _values[0], &stop); //% } //% if (!stop && BOOL_DICT_W_HAS##HELPER(1, )) { //% block(YES, _values[1], &stop); //% } //%} //% //%BOOL_EXTRA_METHODS_##HELPER(Bool, VALUE_NAME)- (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { //% GPBDataType valueDataType = GPBGetFieldDataType(field); //% NSUInteger count = 0; //% size_t result = 0; //% for (int i = 0; i < 2; ++i) { //% if (BOOL_DICT_HAS##HELPER(i, )) { //% ++count; //% size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); //% msgSize += ComputeDict##VALUE_NAME##FieldSize(_values[i], kMapValueFieldNumber, valueDataType); //% result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; //% } //% } //% size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); //% result += tagSize * count; //% return result; //%} //% //%- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream //% asField:(GPBFieldDescriptor *)field { //% GPBDataType valueDataType = GPBGetFieldDataType(field); //% uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); //% for (int i = 0; i < 2; ++i) { //% if (BOOL_DICT_HAS##HELPER(i, )) { //% // Write the tag. //% [outputStream writeInt32NoTag:tag]; //% // Write the size of the message. //% size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); //% msgSize += ComputeDict##VALUE_NAME##FieldSize(_values[i], kMapValueFieldNumber, valueDataType); //% [outputStream writeInt32NoTag:(int32_t)msgSize]; //% // Write the fields. //% WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); //% WriteDict##VALUE_NAME##Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); //% } //% } //%} //% //%BOOL_DICT_MUTATIONS_##HELPER(VALUE_NAME, VALUE_TYPE) //% //%@end //% // // Helpers for PODs // //%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_NAME, VALUE_TYPE, KHELPER) //%- (BOOL)get##VALUE_NAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key { //% NSNumber *wrapped = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; //% if (wrapped && value) { //% *value = UNWRAP##VALUE_NAME(wrapped); //% } //% return (wrapped != NULL); //%} //%PDDM-DEFINE WRAPPEDPOD(VALUE) //%@(VALUE) //%PDDM-DEFINE UNWRAPUInt32(VALUE) //%[VALUE unsignedIntValue] //%PDDM-DEFINE UNWRAPInt32(VALUE) //%[VALUE intValue] //%PDDM-DEFINE UNWRAPUInt64(VALUE) //%[VALUE unsignedLongLongValue] //%PDDM-DEFINE UNWRAPInt64(VALUE) //%[VALUE longLongValue] //%PDDM-DEFINE UNWRAPBool(VALUE) //%[VALUE boolValue] //%PDDM-DEFINE UNWRAPFloat(VALUE) //%[VALUE floatValue] //%PDDM-DEFINE UNWRAPDouble(VALUE) //%[VALUE doubleValue] //%PDDM-DEFINE UNWRAPEnum(VALUE) //%[VALUE intValue] //%PDDM-DEFINE TEXT_FORMAT_OBJUInt32(VALUE) //%[NSString stringWithFormat:@"%u", VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJInt32(VALUE) //%[NSString stringWithFormat:@"%d", VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJUInt64(VALUE) //%[NSString stringWithFormat:@"%llu", VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJInt64(VALUE) //%[NSString stringWithFormat:@"%lld", VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJBool(VALUE) //%(VALUE ? @"true" : @"false") //%PDDM-DEFINE TEXT_FORMAT_OBJFloat(VALUE) //%[NSString stringWithFormat:@"%.*g", FLT_DIG, VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJDouble(VALUE) //%[NSString stringWithFormat:@"%.*lg", DBL_DIG, VALUE] //%PDDM-DEFINE TEXT_FORMAT_OBJEnum(VALUE) //%@(VALUE) //%PDDM-DEFINE ENUM_TYPEPOD(TYPE) //%NSNumber * //%PDDM-DEFINE NEQ_POD(VAL1, VAL2) //%VAL1 != VAL2 //%PDDM-DEFINE EXTRA_METHODS_POD(KEY_NAME, VALUE_NAME) // Empty //%PDDM-DEFINE BOOL_EXTRA_METHODS_POD(KEY_NAME, VALUE_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD(KEY_NAME, VALUE_NAME) //%SERIAL_DATA_FOR_ENTRY_POD_##VALUE_NAME(KEY_NAME) //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_UInt32(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Int32(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_UInt64(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Int64(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Bool(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Float(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Double(KEY_NAME) // Empty //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_POD_Enum(KEY_NAME) //%- (NSData *)serializedDataForUnknownValue:(int32_t)value //% forKey:(GPBGenericValue *)key //% keyDataType:(GPBDataType)keyDataType { //% size_t msgSize = ComputeDict##KEY_NAME##FieldSize(key->value##KEY_NAME, kMapKeyFieldNumber, keyDataType); //% msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); //% NSMutableData *data = [NSMutableData dataWithLength:msgSize]; //% GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; //% WriteDict##KEY_NAME##Field(outputStream, key->value##KEY_NAME, kMapKeyFieldNumber, keyDataType); //% WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); //% [outputStream release]; //% return data; //%} //% //%PDDM-DEFINE GPBVALUE_POD(VALUE_NAME) //%value##VALUE_NAME //%PDDM-DEFINE DICTIONARY_VALIDATE_VALUE_POD(VALUE_NAME, EXTRA_INDENT) // Empty //%PDDM-DEFINE DICTIONARY_VALIDATE_KEY_POD(KEY_NAME, EXTRA_INDENT) // Empty //%PDDM-DEFINE BOOL_DICT_HAS_STORAGE_POD() //% BOOL _valueSet[2]; //% //%PDDM-DEFINE BOOL_DICT_INITS_POD(VALUE_NAME, VALUE_TYPE) //%- (instancetype)initWith##VALUE_NAME##s:(const VALUE_TYPE [])values //% ##VALUE_NAME$S## forKeys:(const BOOL [])keys //% ##VALUE_NAME$S## count:(NSUInteger)count { //% self = [super init]; //% if (self) { //% for (NSUInteger i = 0; i < count; ++i) { //% int idx = keys[i] ? 1 : 0; //% _values[idx] = values[i]; //% _valueSet[idx] = YES; //% } //% } //% return self; //%} //% //%- (instancetype)initWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary { //% self = [self initWith##VALUE_NAME##s:NULL forKeys:NULL count:0]; //% if (self) { //% if (dictionary) { //% for (int i = 0; i < 2; ++i) { //% if (dictionary->_valueSet[i]) { //% _values[i] = dictionary->_values[i]; //% _valueSet[i] = YES; //% } //% } //% } //% } //% return self; //%} //%PDDM-DEFINE BOOL_DICT_DEALLOCPOD() //%#if !defined(NS_BLOCK_ASSERTIONS) //%- (void)dealloc { //% NSAssert(!_autocreator, //% @"%@: Autocreator must be cleared before release, autocreator: %@", //% [self class], _autocreator); //% [super dealloc]; //%} //%#endif // !defined(NS_BLOCK_ASSERTIONS) //%PDDM-DEFINE BOOL_DICT_W_HASPOD(IDX, REF) //%BOOL_DICT_HASPOD(IDX, REF) //%PDDM-DEFINE BOOL_DICT_HASPOD(IDX, REF) //%REF##_valueSet[IDX] //%PDDM-DEFINE BOOL_VALUE_FOR_KEY_POD(VALUE_NAME, VALUE_TYPE) //%- (BOOL)get##VALUE_NAME##:(VALUE_TYPE *)value forKey:(BOOL)key { //% int idx = (key ? 1 : 0); //% if (_valueSet[idx]) { //% if (value) { //% *value = _values[idx]; //% } //% return YES; //% } //% return NO; //%} //%PDDM-DEFINE BOOL_SET_GPBVALUE_FOR_KEY_POD(VALUE_NAME, VALUE_TYPE, VisP) //%- (void)setGPBGenericValue:(GPBGenericValue *)value //% forGPBGenericValueKey:(GPBGenericValue *)key { //% int idx = (key->valueBool ? 1 : 0); //% _values[idx] = value->value##VALUE_NAME; //% _valueSet[idx] = YES; //%} //%PDDM-DEFINE BOOL_DICT_MUTATIONS_POD(VALUE_NAME, VALUE_TYPE) //%- (void)addEntriesFromDictionary:(GPBBool##VALUE_NAME##Dictionary *)otherDictionary { //% if (otherDictionary) { //% for (int i = 0; i < 2; ++i) { //% if (otherDictionary->_valueSet[i]) { //% _valueSet[i] = YES; //% _values[i] = otherDictionary->_values[i]; //% } //% } //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //% } //%} //% //%- (void)set##VALUE_NAME:(VALUE_TYPE)value forKey:(BOOL)key { //% int idx = (key ? 1 : 0); //% _values[idx] = value; //% _valueSet[idx] = YES; //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //%} //% //%- (void)remove##VALUE_NAME##ForKey:(BOOL)aKey { //% _valueSet[aKey ? 1 : 0] = NO; //%} //% //%- (void)removeAll { //% _valueSet[0] = NO; //% _valueSet[1] = NO; //%} //%PDDM-DEFINE STR_FORMAT_POD(VALUE_NAME) //%STR_FORMAT_##VALUE_NAME() //%PDDM-DEFINE STR_FORMAT_UInt32() //%%u //%PDDM-DEFINE STR_FORMAT_Int32() //%%d //%PDDM-DEFINE STR_FORMAT_UInt64() //%%llu //%PDDM-DEFINE STR_FORMAT_Int64() //%%lld //%PDDM-DEFINE STR_FORMAT_Bool() //%%d //%PDDM-DEFINE STR_FORMAT_Float() //%%f //%PDDM-DEFINE STR_FORMAT_Double() //%%lf // // Helpers for Objects // //%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_NAME, VALUE_TYPE, KHELPER) //%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key { //% VALUE_TYPE result = [_dictionary objectForKey:WRAPPED##KHELPER(key)]; //% return result; //%} //%PDDM-DEFINE WRAPPEDOBJECT(VALUE) //%VALUE //%PDDM-DEFINE UNWRAPString(VALUE) //%VALUE //%PDDM-DEFINE UNWRAPObject(VALUE) //%VALUE //%PDDM-DEFINE TEXT_FORMAT_OBJString(VALUE) //%VALUE //%PDDM-DEFINE TEXT_FORMAT_OBJObject(VALUE) //%VALUE //%PDDM-DEFINE ENUM_TYPEOBJECT(TYPE) //%ENUM_TYPEOBJECT_##TYPE() //%PDDM-DEFINE ENUM_TYPEOBJECT_NSString() //%NSString * //%PDDM-DEFINE ENUM_TYPEOBJECT_id() //%id ## //%PDDM-DEFINE NEQ_OBJECT(VAL1, VAL2) //%![VAL1 isEqual:VAL2] //%PDDM-DEFINE EXTRA_METHODS_OBJECT(KEY_NAME, VALUE_NAME) //%- (BOOL)isInitialized { //% for (GPBMessage *msg in [_dictionary objectEnumerator]) { //% if (!msg.initialized) { //% return NO; //% } //% } //% return YES; //%} //% //%- (instancetype)deepCopyWithZone:(NSZone *)zone { //% GPB##KEY_NAME##VALUE_NAME##Dictionary *newDict = //% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; //% [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey, //% GPBMessage *msg, //% BOOL *stop) { //% #pragma unused(stop) //% GPBMessage *copiedMsg = [msg copyWithZone:zone]; //% [newDict->_dictionary setObject:copiedMsg forKey:aKey]; //% [copiedMsg release]; //% }]; //% return newDict; //%} //% //% //%PDDM-DEFINE BOOL_EXTRA_METHODS_OBJECT(KEY_NAME, VALUE_NAME) //%- (BOOL)isInitialized { //% if (_values[0] && ![_values[0] isInitialized]) { //% return NO; //% } //% if (_values[1] && ![_values[1] isInitialized]) { //% return NO; //% } //% return YES; //%} //% //%- (instancetype)deepCopyWithZone:(NSZone *)zone { //% GPB##KEY_NAME##VALUE_NAME##Dictionary *newDict = //% [[GPB##KEY_NAME##VALUE_NAME##Dictionary alloc] init]; //% for (int i = 0; i < 2; ++i) { //% if (_values[i] != nil) { //% newDict->_values[i] = [_values[i] copyWithZone:zone]; //% } //% } //% return newDict; //%} //% //% //%PDDM-DEFINE SERIAL_DATA_FOR_ENTRY_OBJECT(KEY_NAME, VALUE_NAME) // Empty //%PDDM-DEFINE GPBVALUE_OBJECT(VALUE_NAME) //%valueString //%PDDM-DEFINE DICTIONARY_VALIDATE_VALUE_OBJECT(VALUE_NAME, EXTRA_INDENT) //%##EXTRA_INDENT$S## if (!##VALUE_NAME) { //%##EXTRA_INDENT$S## [NSException raise:NSInvalidArgumentException //%##EXTRA_INDENT$S## format:@"Attempting to add nil object to a Dictionary"]; //%##EXTRA_INDENT$S## } //% //%PDDM-DEFINE DICTIONARY_VALIDATE_KEY_OBJECT(KEY_NAME, EXTRA_INDENT) //%##EXTRA_INDENT$S## if (!##KEY_NAME) { //%##EXTRA_INDENT$S## [NSException raise:NSInvalidArgumentException //%##EXTRA_INDENT$S## format:@"Attempting to add nil key to a Dictionary"]; //%##EXTRA_INDENT$S## } //% //%PDDM-DEFINE BOOL_DICT_HAS_STORAGE_OBJECT() // Empty //%PDDM-DEFINE BOOL_DICT_INITS_OBJECT(VALUE_NAME, VALUE_TYPE) //%- (instancetype)initWithObjects:(const VALUE_TYPE [])objects //% forKeys:(const BOOL [])keys //% count:(NSUInteger)count { //% self = [super init]; //% if (self) { //% for (NSUInteger i = 0; i < count; ++i) { //% if (!objects[i]) { //% [NSException raise:NSInvalidArgumentException //% format:@"Attempting to add nil object to a Dictionary"]; //% } //% int idx = keys[i] ? 1 : 0; //% [_values[idx] release]; //% _values[idx] = (VALUE_TYPE)[objects[i] retain]; //% } //% } //% return self; //%} //% //%- (instancetype)initWithDictionary:(GPBBool##VALUE_NAME##Dictionary *)dictionary { //% self = [self initWithObjects:NULL forKeys:NULL count:0]; //% if (self) { //% if (dictionary) { //% _values[0] = [dictionary->_values[0] retain]; //% _values[1] = [dictionary->_values[1] retain]; //% } //% } //% return self; //%} //%PDDM-DEFINE BOOL_DICT_DEALLOCOBJECT() //%- (void)dealloc { //% NSAssert(!_autocreator, //% @"%@: Autocreator must be cleared before release, autocreator: %@", //% [self class], _autocreator); //% [_values[0] release]; //% [_values[1] release]; //% [super dealloc]; //%} //%PDDM-DEFINE BOOL_DICT_W_HASOBJECT(IDX, REF) //%(BOOL_DICT_HASOBJECT(IDX, REF)) //%PDDM-DEFINE BOOL_DICT_HASOBJECT(IDX, REF) //%REF##_values[IDX] != nil //%PDDM-DEFINE BOOL_VALUE_FOR_KEY_OBJECT(VALUE_NAME, VALUE_TYPE) //%- (VALUE_TYPE)objectForKey:(BOOL)key { //% return _values[key ? 1 : 0]; //%} //%PDDM-DEFINE BOOL_SET_GPBVALUE_FOR_KEY_OBJECT(VALUE_NAME, VALUE_TYPE, VisP) //%- (void)setGPBGenericValue:(GPBGenericValue *)value //% forGPBGenericValueKey:(GPBGenericValue *)key { //% int idx = (key->valueBool ? 1 : 0); //% [_values[idx] release]; //% _values[idx] = [value->valueString retain]; //%} //%PDDM-DEFINE BOOL_DICT_MUTATIONS_OBJECT(VALUE_NAME, VALUE_TYPE) //%- (void)addEntriesFromDictionary:(GPBBool##VALUE_NAME##Dictionary *)otherDictionary { //% if (otherDictionary) { //% for (int i = 0; i < 2; ++i) { //% if (otherDictionary->_values[i] != nil) { //% [_values[i] release]; //% _values[i] = [otherDictionary->_values[i] retain]; //% } //% } //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //% } //%} //% //%- (void)setObject:(VALUE_TYPE)object forKey:(BOOL)key { //% if (!object) { //% [NSException raise:NSInvalidArgumentException //% format:@"Attempting to add nil object to a Dictionary"]; //% } //% int idx = (key ? 1 : 0); //% [_values[idx] release]; //% _values[idx] = [object retain]; //% if (_autocreator) { //% GPBAutocreatedDictionaryModified(_autocreator, self); //% } //%} //% //%- (void)removeObjectForKey:(BOOL)aKey { //% int idx = (aKey ? 1 : 0); //% [_values[idx] release]; //% _values[idx] = nil; //%} //% //%- (void)removeAll { //% for (int i = 0; i < 2; ++i) { //% [_values[i] release]; //% _values[i] = nil; //% } //%} //%PDDM-DEFINE STR_FORMAT_OBJECT(VALUE_NAME) //%%@ //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt32, uint32_t) // This block of code is generated, do not edit it directly. #pragma mark - UInt32 -> UInt32 @implementation GPBUInt32UInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32UInt32Dictionary class]]) { return NO; } GPBUInt32UInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(uint32_t key, uint32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue unsignedIntValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt32sUsingBlock:^(uint32_t key, uint32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%u", value]); }]; } - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedIntValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32UInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Int32 @implementation GPBUInt32Int32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32Int32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32Int32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32Int32Dictionary class]]) { return NO; } GPBUInt32Int32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(uint32_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt32sUsingBlock:^(uint32_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%d", value]); }]; } - (BOOL)getInt32:(nullable int32_t *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped intValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32Int32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> UInt64 @implementation GPBUInt32UInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32UInt64Dictionary class]]) { return NO; } GPBUInt32UInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(uint32_t key, uint64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue unsignedLongLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt64sUsingBlock:^(uint32_t key, uint64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%llu", value]); }]; } - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedLongLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32UInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Int64 @implementation GPBUInt32Int64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32Int64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32Int64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32Int64Dictionary class]]) { return NO; } GPBUInt32Int64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(uint32_t key, int64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue longLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt64sUsingBlock:^(uint32_t key, int64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%lld", value]); }]; } - (BOOL)getInt64:(nullable int64_t *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped longLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32Int64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Bool @implementation GPBUInt32BoolDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBUInt32BoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32BoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32BoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32BoolDictionary class]]) { return NO; } GPBUInt32BoolDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(uint32_t key, BOOL value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue boolValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueBool) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndBoolsUsingBlock:^(uint32_t key, BOOL value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], (value ? @"true" : @"false")); }]; } - (BOOL)getBool:(nullable BOOL *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped boolValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32BoolDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Float @implementation GPBUInt32FloatDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBUInt32FloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32FloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32FloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32FloatDictionary class]]) { return NO; } GPBUInt32FloatDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(uint32_t key, float value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue floatValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndFloatsUsingBlock:^(uint32_t key, float value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); }]; } - (BOOL)getFloat:(nullable float *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped floatValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32FloatDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Double @implementation GPBUInt32DoubleDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32DoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32DoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32DoubleDictionary class]]) { return NO; } GPBUInt32DoubleDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(uint32_t key, double value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue doubleValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndDoublesUsingBlock:^(uint32_t key, double value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); }]; } - (BOOL)getDouble:(nullable double *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped doubleValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt32DoubleDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt32 -> Enum @implementation GPBUInt32EnumDictionary { @package NSMutableDictionary *_dictionary; GPBEnumValidationFunc _validationFunc; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt32EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:rawValues forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); if (count && rawValues && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32EnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32EnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32EnumDictionary class]]) { return NO; } GPBUInt32EnumDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(uint32_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedIntValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictUInt32FieldSize(key->valueUInt32, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictUInt32Field(outputStream, key->valueUInt32, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndRawValuesUsingBlock:^(uint32_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], @(value)); }]; } - (BOOL)getEnum:(int32_t *)value forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { int32_t result = [wrapped intValue]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return (wrapped != NULL); } - (BOOL)getRawValue:(int32_t *)rawValue forKey:(uint32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && rawValue) { *rawValue = [wrapped intValue]; } return (wrapped != NULL); } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(uint32_t key, int32_t value, BOOL *stop))block { GPBEnumValidationFunc func = _validationFunc; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { int32_t unwrapped = [aValue intValue]; if (!func(unwrapped)) { unwrapped = kGPBUnrecognizedEnumeratorValue; } block([aKey unsignedIntValue], unwrapped, stop); }]; } - (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setRawValue:(int32_t)value forKey:(uint32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } - (void)setEnum:(int32_t)value forKey:(uint32_t)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBUInt32EnumDictionary: Attempt to set an unknown enum value (%d)", value]; } [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } @end #pragma mark - UInt32 -> Object @implementation GPBUInt32ObjectDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithObject:(id)object forKey:(uint32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:&object forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const uint32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithObjects:objects forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithObjects:NULL forKeys:NULL count:0]; } - (instancetype)initWithObjects:(const id [])objects forKeys:(const uint32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && objects && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!objects[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:objects[i] forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt32ObjectDictionary *)dictionary { self = [self initWithObjects:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithObjects:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt32ObjectDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt32ObjectDictionary class]]) { return NO; } GPBUInt32ObjectDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(uint32_t key, id object, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { block([aKey unsignedIntValue], aObject, stop); }]; } - (BOOL)isInitialized { for (GPBMessage *msg in [_dictionary objectEnumerator]) { if (!msg.initialized) { return NO; } } return YES; } - (instancetype)deepCopyWithZone:(NSZone *)zone { GPBUInt32ObjectDictionary *newDict = [[GPBUInt32ObjectDictionary alloc] init]; [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newDict->_dictionary setObject:copiedMsg forKey:aKey]; [copiedMsg release]; }]; return newDict; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt32FieldSize([aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt32Field(outputStream, [aKey unsignedIntValue], kMapKeyFieldNumber, keyDataType); WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:value->valueString forKey:@(key->valueUInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndObjectsUsingBlock:^(uint32_t key, id object, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%u", key], object); }]; } - (id)objectForKey:(uint32_t)key { id result = [_dictionary objectForKey:@(key)]; return result; } - (void)addEntriesFromDictionary:(GPBUInt32ObjectDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setObject:(id)object forKey:(uint32_t)key { if (!object) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:object forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(uint32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int32, int32_t) // This block of code is generated, do not edit it directly. #pragma mark - Int32 -> UInt32 @implementation GPBInt32UInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32UInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32UInt32Dictionary class]]) { return NO; } GPBInt32UInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(int32_t key, uint32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue unsignedIntValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt32sUsingBlock:^(int32_t key, uint32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%u", value]); }]; } - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedIntValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32UInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Int32 @implementation GPBInt32Int32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt32Int32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32Int32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32Int32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32Int32Dictionary class]]) { return NO; } GPBInt32Int32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(int32_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt32sUsingBlock:^(int32_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%d", value]); }]; } - (BOOL)getInt32:(nullable int32_t *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped intValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32Int32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> UInt64 @implementation GPBInt32UInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32UInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32UInt64Dictionary class]]) { return NO; } GPBInt32UInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(int32_t key, uint64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue unsignedLongLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt64sUsingBlock:^(int32_t key, uint64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%llu", value]); }]; } - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedLongLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32UInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Int64 @implementation GPBInt32Int64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt32Int64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32Int64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32Int64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32Int64Dictionary class]]) { return NO; } GPBInt32Int64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(int32_t key, int64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue longLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt64sUsingBlock:^(int32_t key, int64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%lld", value]); }]; } - (BOOL)getInt64:(nullable int64_t *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped longLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32Int64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Bool @implementation GPBInt32BoolDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBInt32BoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32BoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32BoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32BoolDictionary class]]) { return NO; } GPBInt32BoolDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(int32_t key, BOOL value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue boolValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueBool) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndBoolsUsingBlock:^(int32_t key, BOOL value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], (value ? @"true" : @"false")); }]; } - (BOOL)getBool:(nullable BOOL *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped boolValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32BoolDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Float @implementation GPBInt32FloatDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBInt32FloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32FloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32FloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32FloatDictionary class]]) { return NO; } GPBInt32FloatDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(int32_t key, float value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue floatValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndFloatsUsingBlock:^(int32_t key, float value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); }]; } - (BOOL)getFloat:(nullable float *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped floatValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32FloatDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Double @implementation GPBInt32DoubleDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32DoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32DoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32DoubleDictionary class]]) { return NO; } GPBInt32DoubleDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(int32_t key, double value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue doubleValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndDoublesUsingBlock:^(int32_t key, double value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); }]; } - (BOOL)getDouble:(nullable double *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped doubleValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt32DoubleDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int32 -> Enum @implementation GPBInt32EnumDictionary { @package NSMutableDictionary *_dictionary; GPBEnumValidationFunc _validationFunc; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt32EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:rawValues forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt32EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); if (count && rawValues && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32EnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32EnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32EnumDictionary class]]) { return NO; } GPBInt32EnumDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(int32_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey intValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictInt32FieldSize(key->valueInt32, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictInt32Field(outputStream, key->valueInt32, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndRawValuesUsingBlock:^(int32_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], @(value)); }]; } - (BOOL)getEnum:(int32_t *)value forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { int32_t result = [wrapped intValue]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return (wrapped != NULL); } - (BOOL)getRawValue:(int32_t *)rawValue forKey:(int32_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && rawValue) { *rawValue = [wrapped intValue]; } return (wrapped != NULL); } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(int32_t key, int32_t value, BOOL *stop))block { GPBEnumValidationFunc func = _validationFunc; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { int32_t unwrapped = [aValue intValue]; if (!func(unwrapped)) { unwrapped = kGPBUnrecognizedEnumeratorValue; } block([aKey intValue], unwrapped, stop); }]; } - (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setRawValue:(int32_t)value forKey:(int32_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } - (void)setEnum:(int32_t)value forKey:(int32_t)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBInt32EnumDictionary: Attempt to set an unknown enum value (%d)", value]; } [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } @end #pragma mark - Int32 -> Object @implementation GPBInt32ObjectDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithObject:(id)object forKey:(int32_t)key { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:&object forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const int32_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBInt32ObjectDictionary*)[self alloc] initWithObjects:objects forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt32ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithObjects:NULL forKeys:NULL count:0]; } - (instancetype)initWithObjects:(const id [])objects forKeys:(const int32_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && objects && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!objects[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:objects[i] forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt32ObjectDictionary *)dictionary { self = [self initWithObjects:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithObjects:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt32ObjectDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt32ObjectDictionary class]]) { return NO; } GPBInt32ObjectDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(int32_t key, id object, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { block([aKey intValue], aObject, stop); }]; } - (BOOL)isInitialized { for (GPBMessage *msg in [_dictionary objectEnumerator]) { if (!msg.initialized) { return NO; } } return YES; } - (instancetype)deepCopyWithZone:(NSZone *)zone { GPBInt32ObjectDictionary *newDict = [[GPBInt32ObjectDictionary alloc] init]; [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newDict->_dictionary setObject:copiedMsg forKey:aKey]; [copiedMsg release]; }]; return newDict; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt32FieldSize([aKey intValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt32Field(outputStream, [aKey intValue], kMapKeyFieldNumber, keyDataType); WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:value->valueString forKey:@(key->valueInt32)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndObjectsUsingBlock:^(int32_t key, id object, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%d", key], object); }]; } - (id)objectForKey:(int32_t)key { id result = [_dictionary objectForKey:@(key)]; return result; } - (void)addEntriesFromDictionary:(GPBInt32ObjectDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setObject:(id)object forKey:(int32_t)key { if (!object) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:object forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(int32_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt64, uint64_t) // This block of code is generated, do not edit it directly. #pragma mark - UInt64 -> UInt32 @implementation GPBUInt64UInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64UInt32Dictionary class]]) { return NO; } GPBUInt64UInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(uint64_t key, uint32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue unsignedIntValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt32sUsingBlock:^(uint64_t key, uint32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%u", value]); }]; } - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedIntValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64UInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Int32 @implementation GPBUInt64Int32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64Int32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64Int32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64Int32Dictionary class]]) { return NO; } GPBUInt64Int32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(uint64_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt32sUsingBlock:^(uint64_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%d", value]); }]; } - (BOOL)getInt32:(nullable int32_t *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped intValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64Int32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> UInt64 @implementation GPBUInt64UInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64UInt64Dictionary class]]) { return NO; } GPBUInt64UInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(uint64_t key, uint64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue unsignedLongLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt64sUsingBlock:^(uint64_t key, uint64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%llu", value]); }]; } - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedLongLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64UInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Int64 @implementation GPBUInt64Int64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64Int64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64Int64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64Int64Dictionary class]]) { return NO; } GPBUInt64Int64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(uint64_t key, int64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue longLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt64sUsingBlock:^(uint64_t key, int64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%lld", value]); }]; } - (BOOL)getInt64:(nullable int64_t *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped longLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64Int64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Bool @implementation GPBUInt64BoolDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBUInt64BoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64BoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64BoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64BoolDictionary class]]) { return NO; } GPBUInt64BoolDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(uint64_t key, BOOL value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue boolValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueBool) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndBoolsUsingBlock:^(uint64_t key, BOOL value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], (value ? @"true" : @"false")); }]; } - (BOOL)getBool:(nullable BOOL *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped boolValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64BoolDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Float @implementation GPBUInt64FloatDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBUInt64FloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64FloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64FloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64FloatDictionary class]]) { return NO; } GPBUInt64FloatDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(uint64_t key, float value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue floatValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndFloatsUsingBlock:^(uint64_t key, float value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); }]; } - (BOOL)getFloat:(nullable float *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped floatValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64FloatDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Double @implementation GPBUInt64DoubleDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64DoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64DoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64DoubleDictionary class]]) { return NO; } GPBUInt64DoubleDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(uint64_t key, double value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue doubleValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndDoublesUsingBlock:^(uint64_t key, double value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); }]; } - (BOOL)getDouble:(nullable double *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped doubleValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBUInt64DoubleDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - UInt64 -> Enum @implementation GPBUInt64EnumDictionary { @package NSMutableDictionary *_dictionary; GPBEnumValidationFunc _validationFunc; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt64EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:rawValues forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBUInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); if (count && rawValues && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64EnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64EnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64EnumDictionary class]]) { return NO; } GPBUInt64EnumDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(uint64_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey unsignedLongLongValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictUInt64FieldSize(key->valueUInt64, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictUInt64Field(outputStream, key->valueUInt64, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndRawValuesUsingBlock:^(uint64_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], @(value)); }]; } - (BOOL)getEnum:(int32_t *)value forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { int32_t result = [wrapped intValue]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return (wrapped != NULL); } - (BOOL)getRawValue:(int32_t *)rawValue forKey:(uint64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && rawValue) { *rawValue = [wrapped intValue]; } return (wrapped != NULL); } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(uint64_t key, int32_t value, BOOL *stop))block { GPBEnumValidationFunc func = _validationFunc; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { int32_t unwrapped = [aValue intValue]; if (!func(unwrapped)) { unwrapped = kGPBUnrecognizedEnumeratorValue; } block([aKey unsignedLongLongValue], unwrapped, stop); }]; } - (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setRawValue:(int32_t)value forKey:(uint64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } - (void)setEnum:(int32_t)value forKey:(uint64_t)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBUInt64EnumDictionary: Attempt to set an unknown enum value (%d)", value]; } [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } @end #pragma mark - UInt64 -> Object @implementation GPBUInt64ObjectDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithObject:(id)object forKey:(uint64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:&object forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const uint64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithObjects:objects forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBUInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithObjects:NULL forKeys:NULL count:0]; } - (instancetype)initWithObjects:(const id [])objects forKeys:(const uint64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && objects && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!objects[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:objects[i] forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBUInt64ObjectDictionary *)dictionary { self = [self initWithObjects:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithObjects:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBUInt64ObjectDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBUInt64ObjectDictionary class]]) { return NO; } GPBUInt64ObjectDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(uint64_t key, id object, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { block([aKey unsignedLongLongValue], aObject, stop); }]; } - (BOOL)isInitialized { for (GPBMessage *msg in [_dictionary objectEnumerator]) { if (!msg.initialized) { return NO; } } return YES; } - (instancetype)deepCopyWithZone:(NSZone *)zone { GPBUInt64ObjectDictionary *newDict = [[GPBUInt64ObjectDictionary alloc] init]; [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newDict->_dictionary setObject:copiedMsg forKey:aKey]; [copiedMsg release]; }]; return newDict; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictUInt64FieldSize([aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictUInt64Field(outputStream, [aKey unsignedLongLongValue], kMapKeyFieldNumber, keyDataType); WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:value->valueString forKey:@(key->valueUInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndObjectsUsingBlock:^(uint64_t key, id object, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%llu", key], object); }]; } - (id)objectForKey:(uint64_t)key { id result = [_dictionary objectForKey:@(key)]; return result; } - (void)addEntriesFromDictionary:(GPBUInt64ObjectDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setObject:(id)object forKey:(uint64_t)key { if (!object) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:object forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(uint64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int64, int64_t) // This block of code is generated, do not edit it directly. #pragma mark - Int64 -> UInt32 @implementation GPBInt64UInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64UInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64UInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64UInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64UInt32Dictionary class]]) { return NO; } GPBInt64UInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(int64_t key, uint32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue unsignedIntValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt32) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt32sUsingBlock:^(int64_t key, uint32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%u", value]); }]; } - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedIntValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64UInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Int32 @implementation GPBInt64Int32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBInt64Int32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64Int32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64Int32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64Int32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64Int32Dictionary class]]) { return NO; } GPBInt64Int32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(int64_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt32) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt32sUsingBlock:^(int64_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%d", value]); }]; } - (BOOL)getInt32:(nullable int32_t *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped intValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64Int32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> UInt64 @implementation GPBInt64UInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64UInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64UInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64UInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64UInt64Dictionary class]]) { return NO; } GPBInt64UInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(int64_t key, uint64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue unsignedLongLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt64) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt64sUsingBlock:^(int64_t key, uint64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%llu", value]); }]; } - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped unsignedLongLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64UInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Int64 @implementation GPBInt64Int64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBInt64Int64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64Int64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64Int64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64Int64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64Int64Dictionary class]]) { return NO; } GPBInt64Int64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(int64_t key, int64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue longLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt64) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt64sUsingBlock:^(int64_t key, int64_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%lld", value]); }]; } - (BOOL)getInt64:(nullable int64_t *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped longLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64Int64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Bool @implementation GPBInt64BoolDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBInt64BoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64BoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64BoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64BoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64BoolDictionary class]]) { return NO; } GPBInt64BoolDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(int64_t key, BOOL value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue boolValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueBool) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndBoolsUsingBlock:^(int64_t key, BOOL value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], (value ? @"true" : @"false")); }]; } - (BOOL)getBool:(nullable BOOL *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped boolValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64BoolDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Float @implementation GPBInt64FloatDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBInt64FloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64FloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64FloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64FloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64FloatDictionary class]]) { return NO; } GPBInt64FloatDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(int64_t key, float value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue floatValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueFloat) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndFloatsUsingBlock:^(int64_t key, float value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); }]; } - (BOOL)getFloat:(nullable float *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped floatValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64FloatDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Double @implementation GPBInt64DoubleDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64DoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(values[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64DoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64DoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64DoubleDictionary class]]) { return NO; } GPBInt64DoubleDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(int64_t key, double value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue doubleValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueDouble) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndDoublesUsingBlock:^(int64_t key, double value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); }]; } - (BOOL)getDouble:(nullable double *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { *value = [wrapped doubleValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBInt64DoubleDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - Int64 -> Enum @implementation GPBInt64EnumDictionary { @package NSMutableDictionary *_dictionary; GPBEnumValidationFunc _validationFunc; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt64EnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:rawValues forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBInt64EnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); if (count && rawValues && keys) { for (NSUInteger i = 0; i < count; ++i) { [_dictionary setObject:@(rawValues[i]) forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64EnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64EnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64EnumDictionary class]]) { return NO; } GPBInt64EnumDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(int64_t key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { block([aKey longLongValue], [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictInt64FieldSize(key->valueInt64, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictInt64Field(outputStream, key->valueInt64, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueEnum) forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndRawValuesUsingBlock:^(int64_t key, int32_t value, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], @(value)); }]; } - (BOOL)getEnum:(int32_t *)value forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && value) { int32_t result = [wrapped intValue]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return (wrapped != NULL); } - (BOOL)getRawValue:(int32_t *)rawValue forKey:(int64_t)key { NSNumber *wrapped = [_dictionary objectForKey:@(key)]; if (wrapped && rawValue) { *rawValue = [wrapped intValue]; } return (wrapped != NULL); } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(int64_t key, int32_t value, BOOL *stop))block { GPBEnumValidationFunc func = _validationFunc; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, NSNumber *aValue, BOOL *stop) { int32_t unwrapped = [aValue intValue]; if (!func(unwrapped)) { unwrapped = kGPBUnrecognizedEnumeratorValue; } block([aKey longLongValue], unwrapped, stop); }]; } - (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setRawValue:(int32_t)value forKey:(int64_t)key { [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } - (void)setEnum:(int32_t)value forKey:(int64_t)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBInt64EnumDictionary: Attempt to set an unknown enum value (%d)", value]; } [_dictionary setObject:@(value) forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } @end #pragma mark - Int64 -> Object @implementation GPBInt64ObjectDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithObject:(id)object forKey:(int64_t)key { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:&object forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const int64_t [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBInt64ObjectDictionary*)[self alloc] initWithObjects:objects forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBInt64ObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithObjects:NULL forKeys:NULL count:0]; } - (instancetype)initWithObjects:(const id [])objects forKeys:(const int64_t [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && objects && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!objects[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:objects[i] forKey:@(keys[i])]; } } } return self; } - (instancetype)initWithDictionary:(GPBInt64ObjectDictionary *)dictionary { self = [self initWithObjects:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithObjects:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBInt64ObjectDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBInt64ObjectDictionary class]]) { return NO; } GPBInt64ObjectDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(int64_t key, id object, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { block([aKey longLongValue], aObject, stop); }]; } - (BOOL)isInitialized { for (GPBMessage *msg in [_dictionary objectEnumerator]) { if (!msg.initialized) { return NO; } } return YES; } - (instancetype)deepCopyWithZone:(NSZone *)zone { GPBInt64ObjectDictionary *newDict = [[GPBInt64ObjectDictionary alloc] init]; [_dictionary enumerateKeysAndObjectsUsingBlock:^(id aKey, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newDict->_dictionary setObject:copiedMsg forKey:aKey]; [copiedMsg release]; }]; return newDict; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSNumber *aKey, id aObject, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictInt64FieldSize([aKey longLongValue], kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictObjectFieldSize(aObject, kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictInt64Field(outputStream, [aKey longLongValue], kMapKeyFieldNumber, keyDataType); WriteDictObjectField(outputStream, aObject, kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:value->valueString forKey:@(key->valueInt64)]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndObjectsUsingBlock:^(int64_t key, id object, BOOL *stop) { #pragma unused(stop) block([NSString stringWithFormat:@"%lld", key], object); }]; } - (id)objectForKey:(int64_t)key { id result = [_dictionary objectForKey:@(key)]; return result; } - (void)addEntriesFromDictionary:(GPBInt64ObjectDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setObject:(id)object forKey:(int64_t)key { if (!object) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } [_dictionary setObject:object forKey:@(key)]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(int64_t)aKey { [_dictionary removeObjectForKey:@(aKey)]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end //%PDDM-EXPAND DICTIONARY_POD_IMPL_FOR_KEY(String, NSString, *, OBJECT) // This block of code is generated, do not edit it directly. #pragma mark - String -> UInt32 @implementation GPBStringUInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBStringUInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringUInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringUInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringUInt32Dictionary class]]) { return NO; } GPBStringUInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(NSString *key, uint32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue unsignedIntValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt32FieldSize([aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictUInt32Field(outputStream, [aValue unsignedIntValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt32) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt32sUsingBlock:^(NSString *key, uint32_t value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%u", value]); }]; } - (BOOL)getUInt32:(nullable uint32_t *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped unsignedIntValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringUInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Int32 @implementation GPBStringInt32Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBStringInt32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringInt32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringInt32Dictionary class]]) { return NO; } GPBStringInt32Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(NSString *key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt32FieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictInt32Field(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt32) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt32sUsingBlock:^(NSString *key, int32_t value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%d", value]); }]; } - (BOOL)getInt32:(nullable int32_t *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped intValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringInt32Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> UInt64 @implementation GPBStringUInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBStringUInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringUInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringUInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringUInt64Dictionary class]]) { return NO; } GPBStringUInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(NSString *key, uint64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue unsignedLongLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictUInt64FieldSize([aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictUInt64Field(outputStream, [aValue unsignedLongLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueUInt64) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndUInt64sUsingBlock:^(NSString *key, uint64_t value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%llu", value]); }]; } - (BOOL)getUInt64:(nullable uint64_t *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped unsignedLongLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringUInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Int64 @implementation GPBStringInt64Dictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBStringInt64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringInt64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringInt64Dictionary class]]) { return NO; } GPBStringInt64Dictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(NSString *key, int64_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue longLongValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictInt64FieldSize([aValue longLongValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictInt64Field(outputStream, [aValue longLongValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueInt64) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndInt64sUsingBlock:^(NSString *key, int64_t value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%lld", value]); }]; } - (BOOL)getInt64:(nullable int64_t *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped longLongValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringInt64Dictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Bool @implementation GPBStringBoolDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBStringBoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringBoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringBoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringBoolDictionary class]]) { return NO; } GPBStringBoolDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(NSString *key, BOOL value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue boolValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictBoolFieldSize([aValue boolValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictBoolField(outputStream, [aValue boolValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueBool) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndBoolsUsingBlock:^(NSString *key, BOOL value, BOOL *stop) { #pragma unused(stop) block(key, (value ? @"true" : @"false")); }]; } - (BOOL)getBool:(nullable BOOL *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped boolValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringBoolDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Float @implementation GPBStringFloatDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBStringFloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringFloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringFloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringFloatDictionary class]]) { return NO; } GPBStringFloatDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(NSString *key, float value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue floatValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictFloatFieldSize([aValue floatValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictFloatField(outputStream, [aValue floatValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueFloat) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndFloatsUsingBlock:^(NSString *key, float value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%.*g", FLT_DIG, value]); }]; } - (BOOL)getFloat:(nullable float *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped floatValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringFloatDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Double @implementation GPBStringDoubleDictionary { @package NSMutableDictionary *_dictionary; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBStringDoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBStringDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; if (count && values && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(values[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringDoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringDoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringDoubleDictionary class]]) { return NO; } GPBStringDoubleDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(NSString *key, double value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue doubleValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictDoubleFieldSize([aValue doubleValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictDoubleField(outputStream, [aValue doubleValue], kMapValueFieldNumber, valueDataType); }]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueDouble) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndDoublesUsingBlock:^(NSString *key, double value, BOOL *stop) { #pragma unused(stop) block(key, [NSString stringWithFormat:@"%.*lg", DBL_DIG, value]); }]; } - (BOOL)getDouble:(nullable double *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { *value = [wrapped doubleValue]; } return (wrapped != NULL); } - (void)addEntriesFromDictionary:(GPBStringDoubleDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } @end #pragma mark - String -> Enum @implementation GPBStringEnumDictionary { @package NSMutableDictionary *_dictionary; GPBEnumValidationFunc _validationFunc; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(NSString *)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const NSString * [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBStringEnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:rawValues forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBStringEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const NSString * [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] init]; _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); if (count && rawValues && keys) { for (NSUInteger i = 0; i < count; ++i) { if (!keys[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(rawValues[i]) forKey:keys[i]]; } } } return self; } - (instancetype)initWithDictionary:(GPBStringEnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { [_dictionary addEntriesFromDictionary:dictionary->_dictionary]; } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBStringEnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBStringEnumDictionary class]]) { return NO; } GPBStringEnumDictionary *otherDictionary = other; return [_dictionary isEqual:otherDictionary->_dictionary]; } - (NSUInteger)hash { return _dictionary.count; } - (NSString *)description { return [NSString stringWithFormat:@"<%@ %p> { %@ }", [self class], self, _dictionary]; } - (NSUInteger)count { return _dictionary.count; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(NSString *key, int32_t value, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { block(aKey, [aValue intValue], stop); }]; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { NSUInteger count = _dictionary.count; if (count == 0) { return 0; } GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; __block size_t result = 0; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; }]; size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); GPBDataType keyDataType = field.mapKeyDataType; uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { #pragma unused(stop) // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictStringFieldSize(aKey, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize([aValue intValue], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictStringField(outputStream, aKey, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, [aValue intValue], kMapValueFieldNumber, valueDataType); }]; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictStringFieldSize(key->valueString, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictStringField(outputStream, key->valueString, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { [_dictionary setObject:@(value->valueEnum) forKey:key->valueString]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { [self enumerateKeysAndRawValuesUsingBlock:^(NSString *key, int32_t value, BOOL *stop) { #pragma unused(stop) block(key, @(value)); }]; } - (BOOL)getEnum:(int32_t *)value forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && value) { int32_t result = [wrapped intValue]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return (wrapped != NULL); } - (BOOL)getRawValue:(int32_t *)rawValue forKey:(NSString *)key { NSNumber *wrapped = [_dictionary objectForKey:key]; if (wrapped && rawValue) { *rawValue = [wrapped intValue]; } return (wrapped != NULL); } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(NSString *key, int32_t value, BOOL *stop))block { GPBEnumValidationFunc func = _validationFunc; [_dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *aKey, NSNumber *aValue, BOOL *stop) { int32_t unwrapped = [aValue intValue]; if (!func(unwrapped)) { unwrapped = kGPBUnrecognizedEnumeratorValue; } block(aKey, unwrapped, stop); }]; } - (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary { if (otherDictionary) { [_dictionary addEntriesFromDictionary:otherDictionary->_dictionary]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setRawValue:(int32_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(NSString *)aKey { [_dictionary removeObjectForKey:aKey]; } - (void)removeAll { [_dictionary removeAllObjects]; } - (void)setEnum:(int32_t)value forKey:(NSString *)key { if (!key) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil key to a Dictionary"]; } if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBStringEnumDictionary: Attempt to set an unknown enum value (%d)", value]; } [_dictionary setObject:@(value) forKey:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } @end //%PDDM-EXPAND-END (5 expansions) //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt32, uint32_t) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> UInt32 @implementation GPBBoolUInt32Dictionary { @package uint32_t _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithUInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt32:(uint32_t)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt32s:(const uint32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt32s:forKeys:count: // on to get the type correct. return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithUInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolUInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt32s:(const uint32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolUInt32Dictionary *)dictionary { self = [self initWithUInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt32s:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolUInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolUInt32Dictionary class]]) { return NO; } GPBBoolUInt32Dictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %u", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %u", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getUInt32:(uint32_t *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueUInt32; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%u", _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%u", _values[1]]); } } - (void)enumerateKeysAndUInt32sUsingBlock: (void (^)(BOOL key, uint32_t value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictUInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictUInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictUInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolUInt32Dictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt32:(uint32_t)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt32ForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int32, int32_t) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Int32 @implementation GPBBoolInt32Dictionary { @package int32_t _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithInt32s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt32:(int32_t)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt32s:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt32s:forKeys:count: // on to get the type correct. return [[(GPBBoolInt32Dictionary*)[self alloc] initWithInt32s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolInt32Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt32s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt32s:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolInt32Dictionary *)dictionary { self = [self initWithInt32s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt32s:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolInt32Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolInt32Dictionary class]]) { return NO; } GPBBoolInt32Dictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %d", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %d", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getInt32:(int32_t *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueInt32; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%d", _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%d", _values[1]]); } } - (void)enumerateKeysAndInt32sUsingBlock: (void (^)(BOOL key, int32_t value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolInt32Dictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt32:(int32_t)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt32ForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt64, uint64_t) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> UInt64 @implementation GPBBoolUInt64Dictionary { @package uint64_t _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithUInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithUInt64:(uint64_t)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithUInt64s:(const uint64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithUInt64s:forKeys:count: // on to get the type correct. return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithUInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolUInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithUInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithUInt64s:(const uint64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolUInt64Dictionary *)dictionary { self = [self initWithUInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithUInt64s:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolUInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolUInt64Dictionary class]]) { return NO; } GPBBoolUInt64Dictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %llu", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %llu", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getUInt64:(uint64_t *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueUInt64; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%llu", _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%llu", _values[1]]); } } - (void)enumerateKeysAndUInt64sUsingBlock: (void (^)(BOOL key, uint64_t value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictUInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictUInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictUInt64Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolUInt64Dictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setUInt64:(uint64_t)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeUInt64ForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int64, int64_t) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Int64 @implementation GPBBoolInt64Dictionary { @package int64_t _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithInt64s:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithInt64:(int64_t)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithInt64s:(const int64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithInt64s:forKeys:count: // on to get the type correct. return [[(GPBBoolInt64Dictionary*)[self alloc] initWithInt64s:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolInt64Dictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithInt64s:NULL forKeys:NULL count:0]; } - (instancetype)initWithInt64s:(const int64_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolInt64Dictionary *)dictionary { self = [self initWithInt64s:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithInt64s:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolInt64Dictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolInt64Dictionary class]]) { return NO; } GPBBoolInt64Dictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %lld", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %lld", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getInt64:(int64_t *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueInt64; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%lld", _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%lld", _values[1]]); } } - (void)enumerateKeysAndInt64sUsingBlock: (void (^)(BOOL key, int64_t value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt64FieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictInt64Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolInt64Dictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setInt64:(int64_t)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeInt64ForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Bool, BOOL) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Bool @implementation GPBBoolBoolDictionary { @package BOOL _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithBools:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithBool:(BOOL)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithBools:(const BOOL [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithBools:forKeys:count: // on to get the type correct. return [[(GPBBoolBoolDictionary*)[self alloc] initWithBools:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolBoolDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithBools:NULL forKeys:NULL count:0]; } - (instancetype)initWithBools:(const BOOL [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolBoolDictionary *)dictionary { self = [self initWithBools:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithBools:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolBoolDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolBoolDictionary class]]) { return NO; } GPBBoolBoolDictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %d", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %d", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getBool:(BOOL *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueBool; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", (_values[0] ? @"true" : @"false")); } if (_valueSet[1]) { block(@"true", (_values[1] ? @"true" : @"false")); } } - (void)enumerateKeysAndBoolsUsingBlock: (void (^)(BOOL key, BOOL value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictBoolFieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictBoolFieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictBoolField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolBoolDictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setBool:(BOOL)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeBoolForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Float, float) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Float @implementation GPBBoolFloatDictionary { @package float _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithFloats:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithFloat:(float)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithFloats:(const float [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithFloats:forKeys:count: // on to get the type correct. return [[(GPBBoolFloatDictionary*)[self alloc] initWithFloats:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolFloatDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithFloats:NULL forKeys:NULL count:0]; } - (instancetype)initWithFloats:(const float [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolFloatDictionary *)dictionary { self = [self initWithFloats:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithFloats:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolFloatDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolFloatDictionary class]]) { return NO; } GPBBoolFloatDictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %f", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %f", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getFloat:(float *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueFloat; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%.*g", FLT_DIG, _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%.*g", FLT_DIG, _values[1]]); } } - (void)enumerateKeysAndFloatsUsingBlock: (void (^)(BOOL key, float value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictFloatFieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictFloatFieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictFloatField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolFloatDictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setFloat:(float)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeFloatForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Double, double) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Double @implementation GPBBoolDoubleDictionary { @package double _values[2]; BOOL _valueSet[2]; } + (instancetype)dictionary { return [[[self alloc] initWithDoubles:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithDouble:(double)value forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:&value forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithDoubles:(const double [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithDoubles:forKeys:count: // on to get the type correct. return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDoubles:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolDoubleDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithDoubles:NULL forKeys:NULL count:0]; } - (instancetype)initWithDoubles:(const double [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = values[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolDoubleDictionary *)dictionary { self = [self initWithDoubles:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithDoubles:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolDoubleDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolDoubleDictionary class]]) { return NO; } GPBBoolDoubleDictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %lf", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %lf", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getDouble:(double *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { *value = _values[idx]; } return YES; } return NO; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueDouble; _valueSet[idx] = YES; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", [NSString stringWithFormat:@"%.*lg", DBL_DIG, _values[0]]); } if (_valueSet[1]) { block(@"true", [NSString stringWithFormat:@"%.*lg", DBL_DIG, _values[1]]); } } - (void)enumerateKeysAndDoublesUsingBlock: (void (^)(BOOL key, double value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictDoubleFieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictDoubleFieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictDoubleField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolDoubleDictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setDouble:(double)value forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeDoubleForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(Object, id) // This block of code is generated, do not edit it directly. #pragma mark - Bool -> Object @implementation GPBBoolObjectDictionary { @package id _values[2]; } + (instancetype)dictionary { return [[[self alloc] initWithObjects:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithObject:(id)object forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:&object forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithObjects:forKeys:count: // on to get the type correct. return [[(GPBBoolObjectDictionary*)[self alloc] initWithObjects:objects forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithDictionary: // on to get the type correct. return [[(GPBBoolObjectDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithCapacity:(NSUInteger)numItems { return [[[self alloc] initWithCapacity:numItems] autorelease]; } - (instancetype)init { return [self initWithObjects:NULL forKeys:NULL count:0]; } - (instancetype)initWithObjects:(const id [])objects forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { for (NSUInteger i = 0; i < count; ++i) { if (!objects[i]) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } int idx = keys[i] ? 1 : 0; [_values[idx] release]; _values[idx] = (id)[objects[i] retain]; } } return self; } - (instancetype)initWithDictionary:(GPBBoolObjectDictionary *)dictionary { self = [self initWithObjects:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { _values[0] = [dictionary->_values[0] retain]; _values[1] = [dictionary->_values[1] retain]; } } return self; } - (instancetype)initWithCapacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithObjects:NULL forKeys:NULL count:0]; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_values[0] release]; [_values[1] release]; [super dealloc]; } - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolObjectDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolObjectDictionary class]]) { return NO; } GPBBoolObjectDictionary *otherDictionary = other; if (((_values[0] != nil) != (otherDictionary->_values[0] != nil)) || ((_values[1] != nil) != (otherDictionary->_values[1] != nil))) { return NO; } if (((_values[0] != nil) && (![_values[0] isEqual:otherDictionary->_values[0]])) || ((_values[1] != nil) && (![_values[1] isEqual:otherDictionary->_values[1]]))) { return NO; } return YES; } - (NSUInteger)hash { return ((_values[0] != nil) ? 1 : 0) + ((_values[1] != nil) ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if ((_values[0] != nil)) { [result appendFormat:@"NO: %@", _values[0]]; } if ((_values[1] != nil)) { [result appendFormat:@"YES: %@", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return ((_values[0] != nil) ? 1 : 0) + ((_values[1] != nil) ? 1 : 0); } - (id)objectForKey:(BOOL)key { return _values[key ? 1 : 0]; } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); [_values[idx] release]; _values[idx] = [value->valueString retain]; } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_values[0] != nil) { block(@"false", _values[0]); } if ((_values[1] != nil)) { block(@"true", _values[1]); } } - (void)enumerateKeysAndObjectsUsingBlock: (void (^)(BOOL key, id object, BOOL *stop))block { BOOL stop = NO; if (_values[0] != nil) { block(NO, _values[0], &stop); } if (!stop && (_values[1] != nil)) { block(YES, _values[1], &stop); } } - (BOOL)isInitialized { if (_values[0] && ![_values[0] isInitialized]) { return NO; } if (_values[1] && ![_values[1] isInitialized]) { return NO; } return YES; } - (instancetype)deepCopyWithZone:(NSZone *)zone { GPBBoolObjectDictionary *newDict = [[GPBBoolObjectDictionary alloc] init]; for (int i = 0; i < 2; ++i) { if (_values[i] != nil) { newDict->_values[i] = [_values[i] copyWithZone:zone]; } } return newDict; } - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_values[i] != nil) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictObjectFieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_values[i] != nil) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictObjectFieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictObjectField(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)addEntriesFromDictionary:(GPBBoolObjectDictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_values[i] != nil) { [_values[i] release]; _values[i] = [otherDictionary->_values[i] retain]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setObject:(id)object forKey:(BOOL)key { if (!object) { [NSException raise:NSInvalidArgumentException format:@"Attempting to add nil object to a Dictionary"]; } int idx = (key ? 1 : 0); [_values[idx] release]; _values[idx] = [object retain]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(BOOL)aKey { int idx = (aKey ? 1 : 0); [_values[idx] release]; _values[idx] = nil; } - (void)removeAll { for (int i = 0; i < 2; ++i) { [_values[i] release]; _values[i] = nil; } } @end //%PDDM-EXPAND-END (8 expansions) #pragma mark - Bool -> Enum @implementation GPBBoolEnumDictionary { @package GPBEnumValidationFunc _validationFunc; int32_t _values[2]; BOOL _valueSet[2]; } @synthesize validationFunc = _validationFunc; + (instancetype)dictionary { return [[[self alloc] initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func { return [[[self alloc] initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)rawValue forKey:(BOOL)key { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:&rawValue forKeys:&key count:1] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])values forKeys:(const BOOL [])keys count:(NSUInteger)count { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBBoolEnumDictionary*)[self alloc] initWithValidationFunction:func rawValues:values forKeys:keys count:count] autorelease]; } + (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary { // Cast is needed so the compiler knows what class we are invoking initWithValues:forKeys:count: // on to get the type correct. return [[(GPBBoolEnumDictionary*)[self alloc] initWithDictionary:dictionary] autorelease]; } + (instancetype)dictionaryWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { return [[[self alloc] initWithValidationFunction:func capacity:numItems] autorelease]; } - (instancetype)init { return [self initWithValidationFunction:NULL rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func { return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func rawValues:(const int32_t [])rawValues forKeys:(const BOOL [])keys count:(NSUInteger)count { self = [super init]; if (self) { _validationFunc = (func != NULL ? func : DictDefault_IsValidValue); for (NSUInteger i = 0; i < count; ++i) { int idx = keys[i] ? 1 : 0; _values[idx] = rawValues[i]; _valueSet[idx] = YES; } } return self; } - (instancetype)initWithDictionary:(GPBBoolEnumDictionary *)dictionary { self = [self initWithValidationFunction:dictionary.validationFunc rawValues:NULL forKeys:NULL count:0]; if (self) { if (dictionary) { for (int i = 0; i < 2; ++i) { if (dictionary->_valueSet[i]) { _values[i] = dictionary->_values[i]; _valueSet[i] = YES; } } } } return self; } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)numItems { #pragma unused(numItems) return [self initWithValidationFunction:func rawValues:NULL forKeys:NULL count:0]; } #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } #endif // !defined(NS_BLOCK_ASSERTIONS) - (instancetype)copyWithZone:(NSZone *)zone { return [[GPBBoolEnumDictionary allocWithZone:zone] initWithDictionary:self]; } - (BOOL)isEqual:(id)other { if (self == other) { return YES; } if (![other isKindOfClass:[GPBBoolEnumDictionary class]]) { return NO; } GPBBoolEnumDictionary *otherDictionary = other; if ((_valueSet[0] != otherDictionary->_valueSet[0]) || (_valueSet[1] != otherDictionary->_valueSet[1])) { return NO; } if ((_valueSet[0] && (_values[0] != otherDictionary->_values[0])) || (_valueSet[1] && (_values[1] != otherDictionary->_values[1]))) { return NO; } return YES; } - (NSUInteger)hash { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (NSString *)description { NSMutableString *result = [NSMutableString stringWithFormat:@"<%@ %p> {", [self class], self]; if (_valueSet[0]) { [result appendFormat:@"NO: %d", _values[0]]; } if (_valueSet[1]) { [result appendFormat:@"YES: %d", _values[1]]; } [result appendString:@" }"]; return result; } - (NSUInteger)count { return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } - (BOOL)getEnum:(int32_t*)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { int32_t result = _values[idx]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; } *value = result; } return YES; } return NO; } - (BOOL)getRawValue:(int32_t*)rawValue forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (rawValue) { *rawValue = _values[idx]; } return YES; } return NO; } - (void)enumerateKeysAndRawValuesUsingBlock: (void (^)(BOOL key, int32_t value, BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); } if (!stop && _valueSet[1]) { block(YES, _values[1], &stop); } } - (void)enumerateKeysAndEnumsUsingBlock: (void (^)(BOOL key, int32_t rawValue, BOOL *stop))block { BOOL stop = NO; GPBEnumValidationFunc func = _validationFunc; int32_t validatedValue; if (_valueSet[0]) { validatedValue = _values[0]; if (!func(validatedValue)) { validatedValue = kGPBUnrecognizedEnumeratorValue; } block(NO, validatedValue, &stop); } if (!stop && _valueSet[1]) { validatedValue = _values[1]; if (!func(validatedValue)) { validatedValue = kGPBUnrecognizedEnumeratorValue; } block(YES, validatedValue, &stop); } } //%PDDM-EXPAND SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) // This block of code is generated, do not edit it directly. - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType { size_t msgSize = ComputeDictBoolFieldSize(key->valueBool, kMapKeyFieldNumber, keyDataType); msgSize += ComputeDictEnumFieldSize(value, kMapValueFieldNumber, GPBDataTypeEnum); NSMutableData *data = [NSMutableData dataWithLength:msgSize]; GPBCodedOutputStream *outputStream = [[GPBCodedOutputStream alloc] initWithData:data]; WriteDictBoolField(outputStream, key->valueBool, kMapKeyFieldNumber, keyDataType); WriteDictEnumField(outputStream, value, kMapValueFieldNumber, GPBDataTypeEnum); [outputStream release]; return data; } //%PDDM-EXPAND-END SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; size_t result = 0; for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { ++count; size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); result += GPBComputeRawVarint32SizeForInteger(msgSize) + msgSize; } } size_t tagSize = GPBComputeWireFormatTagSize(GPBFieldNumber(field), GPBDataTypeMessage); result += tagSize * count; return result; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); for (int i = 0; i < 2; ++i) { if (_valueSet[i]) { // Write the tag. [outputStream writeInt32NoTag:tag]; // Write the size of the message. size_t msgSize = ComputeDictBoolFieldSize((i == 1), kMapKeyFieldNumber, GPBDataTypeBool); msgSize += ComputeDictInt32FieldSize(_values[i], kMapValueFieldNumber, valueDataType); [outputStream writeInt32NoTag:(int32_t)msgSize]; // Write the fields. WriteDictBoolField(outputStream, (i == 1), kMapKeyFieldNumber, GPBDataTypeBool); WriteDictInt32Field(outputStream, _values[i], kMapValueFieldNumber, valueDataType); } } } - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", @(_values[0])); } if (_valueSet[1]) { block(@"true", @(_values[1])); } } - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueInt32; _valueSet[idx] = YES; } - (void)addRawEntriesFromDictionary:(GPBBoolEnumDictionary *)otherDictionary { if (otherDictionary) { for (int i = 0; i < 2; ++i) { if (otherDictionary->_valueSet[i]) { _valueSet[i] = YES; _values[i] = otherDictionary->_values[i]; } } if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } } - (void)setEnum:(int32_t)value forKey:(BOOL)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", value]; } int idx = (key ? 1 : 0); _values[idx] = value; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)setRawValue:(int32_t)rawValue forKey:(BOOL)key { int idx = (key ? 1 : 0); _values[idx] = rawValue; _valueSet[idx] = YES; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeEnumForKey:(BOOL)aKey { _valueSet[aKey ? 1 : 0] = NO; } - (void)removeAll { _valueSet[0] = NO; _valueSet[1] = NO; } @end #pragma mark - NSDictionary Subclass @implementation GPBAutocreatedDictionary { NSMutableDictionary *_dictionary; } - (void)dealloc { NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; } #pragma mark Required NSDictionary overrides - (instancetype)initWithObjects:(const id [])objects forKeys:(const id [])keys count:(NSUInteger)count { self = [super init]; if (self) { _dictionary = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys count:count]; } return self; } - (NSUInteger)count { return [_dictionary count]; } - (id)objectForKey:(id)aKey { return [_dictionary objectForKey:aKey]; } - (NSEnumerator *)keyEnumerator { if (_dictionary == nil) { _dictionary = [[NSMutableDictionary alloc] init]; } return [_dictionary keyEnumerator]; } #pragma mark Required NSMutableDictionary overrides // Only need to call GPBAutocreatedDictionaryModified() when adding things // since we only autocreate empty dictionaries. - (void)setObject:(id)anObject forKey:(id)aKey { if (_dictionary == nil) { _dictionary = [[NSMutableDictionary alloc] init]; } [_dictionary setObject:anObject forKey:aKey]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)removeObjectForKey:(id)aKey { [_dictionary removeObjectForKey:aKey]; } #pragma mark Extra things hooked - (id)copyWithZone:(NSZone *)zone { if (_dictionary == nil) { return [[NSMutableDictionary allocWithZone:zone] init]; } return [_dictionary copyWithZone:zone]; } - (id)mutableCopyWithZone:(NSZone *)zone { if (_dictionary == nil) { return [[NSMutableDictionary allocWithZone:zone] init]; } return [_dictionary mutableCopyWithZone:zone]; } // Not really needed, but subscripting is likely common enough it doesn't hurt // to ensure it goes directly to the real NSMutableDictionary. - (id)objectForKeyedSubscript:(id)key { return [_dictionary objectForKeyedSubscript:key]; } // Not really needed, but subscripting is likely common enough it doesn't hurt // to ensure it goes directly to the real NSMutableDictionary. - (void)setObject:(id)obj forKeyedSubscript:(id)key { if (_dictionary == nil) { _dictionary = [[NSMutableDictionary alloc] init]; } [_dictionary setObject:obj forKeyedSubscript:key]; if (_autocreator) { GPBAutocreatedDictionaryModified(_autocreator, self); } } - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:block]; } - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id key, id obj, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block]; } @end #pragma clang diagnostic pop ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBDictionary_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBDictionary.h" @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionRegistry; @class GPBFieldDescriptor; @protocol GPBDictionaryInternalsProtocol - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field; - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field; - (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key; - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block; @end //%PDDM-DEFINE DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(KEY_NAME) //%DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(KEY_NAME) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Object, Object) //%PDDM-DEFINE DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(KEY_NAME) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, UInt32, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Int32, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, UInt64, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Int64, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Bool, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Float, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Double, Basic) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Enum, Enum) //%PDDM-DEFINE DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, VALUE_NAME, HELPER) //%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary () { //% @package //% GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; //%} //%EXTRA_DICTIONARY_PRIVATE_INTERFACES_##HELPER()@end //% //%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Basic() // Empty //%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Object() //%- (BOOL)isInitialized; //%- (instancetype)deepCopyWithZone:(NSZone *)zone //% __attribute__((ns_returns_retained)); //% //%PDDM-DEFINE EXTRA_DICTIONARY_PRIVATE_INTERFACES_Enum() //%- (NSData *)serializedDataForUnknownValue:(int32_t)value //% forKey:(GPBGenericValue *)key //% keyDataType:(GPBDataType)keyDataType; //% //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt32) // This block of code is generated, do not edit it directly. @interface GPBUInt32UInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32Int32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32UInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32Int64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32BoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32FloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32DoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt32EnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end @interface GPBUInt32ObjectDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (BOOL)isInitialized; - (instancetype)deepCopyWithZone:(NSZone *)zone __attribute__((ns_returns_retained)); @end //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int32) // This block of code is generated, do not edit it directly. @interface GPBInt32UInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32Int32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32UInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32Int64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32BoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32FloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32DoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt32EnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end @interface GPBInt32ObjectDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (BOOL)isInitialized; - (instancetype)deepCopyWithZone:(NSZone *)zone __attribute__((ns_returns_retained)); @end //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt64) // This block of code is generated, do not edit it directly. @interface GPBUInt64UInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64Int32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64UInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64Int64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64BoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64FloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64DoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBUInt64EnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end @interface GPBUInt64ObjectDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (BOOL)isInitialized; - (instancetype)deepCopyWithZone:(NSZone *)zone __attribute__((ns_returns_retained)); @end //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int64) // This block of code is generated, do not edit it directly. @interface GPBInt64UInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64Int32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64UInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64Int64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64BoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64FloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64DoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBInt64EnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end @interface GPBInt64ObjectDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (BOOL)isInitialized; - (instancetype)deepCopyWithZone:(NSZone *)zone __attribute__((ns_returns_retained)); @end //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Bool) // This block of code is generated, do not edit it directly. @interface GPBBoolUInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolUInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolBoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolFloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolDoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBBoolEnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end @interface GPBBoolObjectDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (BOOL)isInitialized; - (instancetype)deepCopyWithZone:(NSZone *)zone __attribute__((ns_returns_retained)); @end //%PDDM-EXPAND DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(String) // This block of code is generated, do not edit it directly. @interface GPBStringUInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringInt32Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringUInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringInt64Dictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringBoolDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringFloatDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringDoubleDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @interface GPBStringEnumDictionary () { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key keyDataType:(GPBDataType)keyDataType; @end //%PDDM-EXPAND-END (6 expansions) #pragma mark - NSDictionary Subclass @interface GPBAutocreatedDictionary : NSMutableDictionary { @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end #pragma mark - Helpers CF_EXTERN_C_BEGIN // Helper to compute size when an NSDictionary is used for the map instead // of a custom type. size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field); // Helper to write out when an NSDictionary is used for the map instead // of a custom type. void GPBDictionaryWriteToStreamInternalHelper( GPBCodedOutputStream *outputStream, NSDictionary *dict, GPBFieldDescriptor *field); // Helper to check message initialization when an NSDictionary is used for // the map instead of a custom type. BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field); // Helper to read a map instead. void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, GPBExtensionRegistry *registry, GPBFieldDescriptor *field, GPBMessage *parentMessage); CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBExtensionInternals.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBDescriptor.h" @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionRegistry; void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry, GPBMessage *message); size_t GPBComputeExtensionSerializedSizeIncludingTag( GPBExtensionDescriptor *extension, id value); void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, id value, GPBCodedOutputStream *output); ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBExtensionInternals.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBExtensionInternals.h" #import #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry, GPBMessage *existingValue) __attribute__((ns_returns_retained)); GPB_INLINE size_t DataTypeSize(GPBDataType dataType) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" switch (dataType) { case GPBDataTypeBool: return 1; case GPBDataTypeFixed32: case GPBDataTypeSFixed32: case GPBDataTypeFloat: return 4; case GPBDataTypeFixed64: case GPBDataTypeSFixed64: case GPBDataTypeDouble: return 8; default: return 0; } #pragma clang diagnostic pop } static size_t ComputePBSerializedSizeNoTagOfObject(GPBDataType dataType, id object) { #define FIELD_CASE(TYPE, ACCESSOR) \ case GPBDataType##TYPE: \ return GPBCompute##TYPE##SizeNoTag([(NSNumber *)object ACCESSOR]); #define FIELD_CASE2(TYPE) \ case GPBDataType##TYPE: \ return GPBCompute##TYPE##SizeNoTag(object); switch (dataType) { FIELD_CASE(Bool, boolValue) FIELD_CASE(Float, floatValue) FIELD_CASE(Double, doubleValue) FIELD_CASE(Int32, intValue) FIELD_CASE(SFixed32, intValue) FIELD_CASE(SInt32, intValue) FIELD_CASE(Enum, intValue) FIELD_CASE(Int64, longLongValue) FIELD_CASE(SInt64, longLongValue) FIELD_CASE(SFixed64, longLongValue) FIELD_CASE(UInt32, unsignedIntValue) FIELD_CASE(Fixed32, unsignedIntValue) FIELD_CASE(UInt64, unsignedLongLongValue) FIELD_CASE(Fixed64, unsignedLongLongValue) FIELD_CASE2(Bytes) FIELD_CASE2(String) FIELD_CASE2(Message) FIELD_CASE2(Group) } #undef FIELD_CASE #undef FIELD_CASE2 } static size_t ComputeSerializedSizeIncludingTagOfObject( GPBExtensionDescription *description, id object) { #define FIELD_CASE(TYPE, ACCESSOR) \ case GPBDataType##TYPE: \ return GPBCompute##TYPE##Size(description->fieldNumber, \ [(NSNumber *)object ACCESSOR]); #define FIELD_CASE2(TYPE) \ case GPBDataType##TYPE: \ return GPBCompute##TYPE##Size(description->fieldNumber, object); switch (description->dataType) { FIELD_CASE(Bool, boolValue) FIELD_CASE(Float, floatValue) FIELD_CASE(Double, doubleValue) FIELD_CASE(Int32, intValue) FIELD_CASE(SFixed32, intValue) FIELD_CASE(SInt32, intValue) FIELD_CASE(Enum, intValue) FIELD_CASE(Int64, longLongValue) FIELD_CASE(SInt64, longLongValue) FIELD_CASE(SFixed64, longLongValue) FIELD_CASE(UInt32, unsignedIntValue) FIELD_CASE(Fixed32, unsignedIntValue) FIELD_CASE(UInt64, unsignedLongLongValue) FIELD_CASE(Fixed64, unsignedLongLongValue) FIELD_CASE2(Bytes) FIELD_CASE2(String) FIELD_CASE2(Group) case GPBDataTypeMessage: if (GPBExtensionIsWireFormat(description)) { return GPBComputeMessageSetExtensionSize(description->fieldNumber, object); } else { return GPBComputeMessageSize(description->fieldNumber, object); } } #undef FIELD_CASE #undef FIELD_CASE2 } static size_t ComputeSerializedSizeIncludingTagOfArray( GPBExtensionDescription *description, NSArray *values) { if (GPBExtensionIsPacked(description)) { size_t size = 0; size_t typeSize = DataTypeSize(description->dataType); if (typeSize != 0) { size = values.count * typeSize; } else { for (id value in values) { size += ComputePBSerializedSizeNoTagOfObject(description->dataType, value); } } return size + GPBComputeTagSize(description->fieldNumber) + GPBComputeRawVarint32SizeForInteger(size); } else { size_t size = 0; for (id value in values) { size += ComputeSerializedSizeIncludingTagOfObject(description, value); } return size; } } static void WriteObjectIncludingTagToCodedOutputStream( id object, GPBExtensionDescription *description, GPBCodedOutputStream *output) { #define FIELD_CASE(TYPE, ACCESSOR) \ case GPBDataType##TYPE: \ [output write##TYPE:description->fieldNumber \ value:[(NSNumber *)object ACCESSOR]]; \ return; #define FIELD_CASE2(TYPE) \ case GPBDataType##TYPE: \ [output write##TYPE:description->fieldNumber value:object]; \ return; switch (description->dataType) { FIELD_CASE(Bool, boolValue) FIELD_CASE(Float, floatValue) FIELD_CASE(Double, doubleValue) FIELD_CASE(Int32, intValue) FIELD_CASE(SFixed32, intValue) FIELD_CASE(SInt32, intValue) FIELD_CASE(Enum, intValue) FIELD_CASE(Int64, longLongValue) FIELD_CASE(SInt64, longLongValue) FIELD_CASE(SFixed64, longLongValue) FIELD_CASE(UInt32, unsignedIntValue) FIELD_CASE(Fixed32, unsignedIntValue) FIELD_CASE(UInt64, unsignedLongLongValue) FIELD_CASE(Fixed64, unsignedLongLongValue) FIELD_CASE2(Bytes) FIELD_CASE2(String) FIELD_CASE2(Group) case GPBDataTypeMessage: if (GPBExtensionIsWireFormat(description)) { [output writeMessageSetExtension:description->fieldNumber value:object]; } else { [output writeMessage:description->fieldNumber value:object]; } return; } #undef FIELD_CASE #undef FIELD_CASE2 } static void WriteObjectNoTagToCodedOutputStream( id object, GPBExtensionDescription *description, GPBCodedOutputStream *output) { #define FIELD_CASE(TYPE, ACCESSOR) \ case GPBDataType##TYPE: \ [output write##TYPE##NoTag:[(NSNumber *)object ACCESSOR]]; \ return; #define FIELD_CASE2(TYPE) \ case GPBDataType##TYPE: \ [output write##TYPE##NoTag:object]; \ return; switch (description->dataType) { FIELD_CASE(Bool, boolValue) FIELD_CASE(Float, floatValue) FIELD_CASE(Double, doubleValue) FIELD_CASE(Int32, intValue) FIELD_CASE(SFixed32, intValue) FIELD_CASE(SInt32, intValue) FIELD_CASE(Enum, intValue) FIELD_CASE(Int64, longLongValue) FIELD_CASE(SInt64, longLongValue) FIELD_CASE(SFixed64, longLongValue) FIELD_CASE(UInt32, unsignedIntValue) FIELD_CASE(Fixed32, unsignedIntValue) FIELD_CASE(UInt64, unsignedLongLongValue) FIELD_CASE(Fixed64, unsignedLongLongValue) FIELD_CASE2(Bytes) FIELD_CASE2(String) FIELD_CASE2(Message) case GPBDataTypeGroup: [output writeGroupNoTag:description->fieldNumber value:object]; return; } #undef FIELD_CASE #undef FIELD_CASE2 } static void WriteArrayIncludingTagsToCodedOutputStream( NSArray *values, GPBExtensionDescription *description, GPBCodedOutputStream *output) { if (GPBExtensionIsPacked(description)) { [output writeTag:description->fieldNumber format:GPBWireFormatLengthDelimited]; size_t dataSize = 0; size_t typeSize = DataTypeSize(description->dataType); if (typeSize != 0) { dataSize = values.count * typeSize; } else { for (id value in values) { dataSize += ComputePBSerializedSizeNoTagOfObject(description->dataType, value); } } [output writeRawVarintSizeTAs32:dataSize]; for (id value in values) { WriteObjectNoTagToCodedOutputStream(value, description, output); } } else { for (id value in values) { WriteObjectIncludingTagToCodedOutputStream(value, description, output); } } } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry, GPBMessage *message) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; if (isPackedOnStream) { NSCAssert(GPBExtensionIsRepeated(description), @"How was it packed if it isn't repeated?"); int32_t length = GPBCodedInputStreamReadInt32(state); size_t limit = GPBCodedInputStreamPushLimit(state, length); while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, nil); [message addExtension:extension value:value]; [value release]; } GPBCodedInputStreamPopLimit(state, limit); } else { id existingValue = nil; BOOL isRepeated = GPBExtensionIsRepeated(description); if (!isRepeated && GPBDataTypeIsMessage(description->dataType)) { existingValue = [message getExistingExtension:extension]; } id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, existingValue); if (isRepeated) { [message addExtension:extension value:value]; } else { [message setExtension:extension value:value]; } [value release]; } } void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, id value, GPBCodedOutputStream *output) { GPBExtensionDescription *description = extension->description_; if (GPBExtensionIsRepeated(description)) { WriteArrayIncludingTagsToCodedOutputStream(value, description, output); } else { WriteObjectIncludingTagToCodedOutputStream(value, description, output); } } size_t GPBComputeExtensionSerializedSizeIncludingTag( GPBExtensionDescriptor *extension, id value) { GPBExtensionDescription *description = extension->description_; if (GPBExtensionIsRepeated(description)) { return ComputeSerializedSizeIncludingTagOfArray(description, value); } else { return ComputeSerializedSizeIncludingTagOfObject(description, value); } } // Note that this returns a retained value intentionally. static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry, GPBMessage *existingValue) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; switch (description->dataType) { case GPBDataTypeBool: return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)]; case GPBDataTypeFixed32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)]; case GPBDataTypeSFixed32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)]; case GPBDataTypeFloat: return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)]; case GPBDataTypeFixed64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)]; case GPBDataTypeSFixed64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)]; case GPBDataTypeDouble: return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)]; case GPBDataTypeInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)]; case GPBDataTypeInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)]; case GPBDataTypeSInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)]; case GPBDataTypeSInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)]; case GPBDataTypeUInt32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)]; case GPBDataTypeUInt64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)]; case GPBDataTypeBytes: return GPBCodedInputStreamReadRetainedBytes(state); case GPBDataTypeString: return GPBCodedInputStreamReadRetainedString(state); case GPBDataTypeEnum: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)]; case GPBDataTypeGroup: case GPBDataTypeMessage: { GPBMessage *message; if (existingValue) { message = [existingValue retain]; } else { GPBDescriptor *decriptor = [extension.msgClass descriptor]; message = [[decriptor.messageClass alloc] init]; } if (description->dataType == GPBDataTypeGroup) { [input readGroup:description->fieldNumber message:message extensionRegistry:extensionRegistry]; } else { // description->dataType == GPBDataTypeMessage if (GPBExtensionIsWireFormat(description)) { // For MessageSet fields the message length will have already been // read. [message mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; } else { [input readMessage:message extensionRegistry:extensionRegistry]; } } return message; } } return nil; } #pragma clang diagnostic pop ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBExtensionRegistry.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import @class GPBDescriptor; @class GPBExtensionDescriptor; NS_ASSUME_NONNULL_BEGIN /** * A table of known extensions, searchable by name or field number. When * parsing a protocol message that might have extensions, you must provide a * GPBExtensionRegistry in which you have registered any extensions that you * want to be able to parse. Otherwise, those extensions will just be treated * like unknown fields. * * The *Root classes provide `+extensionRegistry` for the extensions defined * in a given file *and* all files it imports. You can also create a * GPBExtensionRegistry, and merge those registries to handle parsing * extensions defined from non overlapping files. * * ``` * GPBExtensionRegistry *registry = [[MyProtoFileRoot extensionRegistry] copy]; * [registry addExtension:[OtherMessage neededExtension]]; // Not in MyProtoFile * NSError *parseError; * MyMessage *msg = [MyMessage parseData:data extensionRegistry:registry error:&parseError]; * ``` **/ @interface GPBExtensionRegistry : NSObject /** * Adds the given GPBExtensionDescriptor to this registry. * * @param extension The extension description to add. **/ - (void)addExtension:(GPBExtensionDescriptor *)extension; /** * Adds all the extensions from another registry to this registry. * * @param registry The registry to merge into this registry. **/ - (void)addExtensions:(GPBExtensionRegistry *)registry; /** * Looks for the extension registered for the given field number on a given * GPBDescriptor. * * @param descriptor The descriptor to look for a registered extension on. * @param fieldNumber The field number of the extension to look for. * * @return The registered GPBExtensionDescriptor or nil if none was found. **/ - (nullable GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor fieldNumber:(NSInteger)fieldNumber; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBExtensionRegistry.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBExtensionRegistry.h" #import "GPBBootstrap.h" #import "GPBDescriptor.h" @implementation GPBExtensionRegistry { NSMutableDictionary *mutableClassMap_; } - (instancetype)init { if ((self = [super init])) { mutableClassMap_ = [[NSMutableDictionary alloc] init]; } return self; } - (void)dealloc { [mutableClassMap_ release]; [super dealloc]; } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (instancetype)copyWithZone:(NSZone *)zone { GPBExtensionRegistry *result = [[[self class] allocWithZone:zone] init]; if (result && mutableClassMap_.count) { [result->mutableClassMap_ addEntriesFromDictionary:mutableClassMap_]; } return result; } - (CFMutableDictionaryRef)extensionMapForContainingMessageClass: (Class)containingMessageClass { CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) [mutableClassMap_ objectForKey:containingMessageClass]; if (extensionMap == nil) { // Use a custom dictionary here because the keys are numbers and conversion // back and forth from NSNumber isn't worth the cost. extensionMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); [mutableClassMap_ setObject:(id)extensionMap forKey:(id)containingMessageClass]; } return extensionMap; } - (void)addExtension:(GPBExtensionDescriptor *)extension { if (extension == nil) { return; } Class containingMessageClass = extension.containingMessageClass; CFMutableDictionaryRef extensionMap = [self extensionMapForContainingMessageClass:containingMessageClass]; ssize_t key = extension.fieldNumber; CFDictionarySetValue(extensionMap, (const void *)key, extension); } - (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor fieldNumber:(NSInteger)fieldNumber { Class messageClass = descriptor.messageClass; CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) [mutableClassMap_ objectForKey:messageClass]; ssize_t key = fieldNumber; GPBExtensionDescriptor *result = (extensionMap ? CFDictionaryGetValue(extensionMap, (const void *)key) : nil); return result; } static void CopyKeyValue(const void *key, const void *value, void *context) { CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)context; CFDictionarySetValue(extensionMap, key, value); } - (void)addExtensions:(GPBExtensionRegistry *)registry { if (registry == nil) { // In the case where there are no extensions just ignore. return; } NSMutableDictionary *otherClassMap = registry->mutableClassMap_; [otherClassMap enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL * stop) { #pragma unused(stop) Class containingMessageClass = key; CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value; CFMutableDictionaryRef extensionMap = [self extensionMapForContainingMessageClass:containingMessageClass]; CFDictionaryApplyFunction(otherExtensionMap, CopyKeyValue, extensionMap); }]; } #pragma clang diagnostic pop @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBMessage.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBBootstrap.h" @class GPBDescriptor; @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionDescriptor; @class GPBExtensionRegistry; @class GPBFieldDescriptor; @class GPBUnknownFieldSet; NS_ASSUME_NONNULL_BEGIN CF_EXTERN_C_BEGIN /** NSError domain used for errors. */ extern NSString *const GPBMessageErrorDomain; /** Error codes for NSErrors originated in GPBMessage. */ typedef NS_ENUM(NSInteger, GPBMessageErrorCode) { /** Uncategorized error. */ GPBMessageErrorCodeOther = -100, /** Message couldn't be serialized because it is missing required fields. */ GPBMessageErrorCodeMissingRequiredField = -101, }; /** * Key under which the GPBMessage error's reason is stored inside the userInfo * dictionary. **/ extern NSString *const GPBErrorReasonKey; CF_EXTERN_C_END /** * Base class that each generated message subclasses from. * * @note While the class support NSSecureCoding, if the message has any * extensions, they will end up reloaded in @c unknownFields as there is * no way for the @c NSCoding plumbing to pass through a * @c GPBExtensionRegistry. To support extensions, instead of passing the * calls off to the Message, simple store the result of @c data, and then * when loading, fetch the data and use * @c +parseFromData:extensionRegistry:error: to provide an extension * registry. **/ @interface GPBMessage : NSObject // If you add an instance method/property to this class that may conflict with // fields declared in protos, you need to update objective_helpers.cc. The main // cases are methods that take no arguments, or setFoo:/hasFoo: type methods. /** * The set of unknown fields for this message. * * Only messages from proto files declared with "proto2" syntax support unknown * fields. For "proto3" syntax, any unknown fields found while parsing are * dropped. **/ @property(nonatomic, copy, nullable) GPBUnknownFieldSet *unknownFields; /** * Whether the message, along with all submessages, have the required fields * set. This is only applicable for files declared with "proto2" syntax, as * there are no required fields for "proto3" syntax. **/ @property(nonatomic, readonly, getter=isInitialized) BOOL initialized; /** * @return An autoreleased message with the default values set. **/ + (instancetype)message; /** * Creates a new instance by parsing the provided data. This method should be * sent to the generated message class that the data should be interpreted as. * If there is an error the method returns nil and the error is returned in * errorPtr (when provided). * * @note In DEBUG builds, the parsed message is checked to be sure all required * fields were provided, and the parse will fail if some are missing. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param data The data to parse. * @param errorPtr An optional error pointer to fill in with a failure reason if * the data can not be parsed. * * @return A new instance of the generated class. **/ + (nullable instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr; /** * Creates a new instance by parsing the data. This method should be sent to * the generated message class that the data should be interpreted as. If * there is an error the method returns nil and the error is returned in * errorPtr (when provided). * * @note In DEBUG builds, the parsed message is checked to be sure all required * fields were provided, and the parse will fail if some are missing. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param data The data to parse. * @param extensionRegistry The extension registry to use to look up extensions. * @param errorPtr An optional error pointer to fill in with a failure * reason if the data can not be parsed. * * @return A new instance of the generated class. **/ + (nullable instancetype)parseFromData:(NSData *)data extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr; /** * Creates a new instance by parsing the data from the given input stream. This * method should be sent to the generated message class that the data should * be interpreted as. If there is an error the method returns nil and the error * is returned in errorPtr (when provided). * * @note In DEBUG builds, the parsed message is checked to be sure all required * fields were provided, and the parse will fail if some are missing. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param input The stream to read data from. * @param extensionRegistry The extension registry to use to look up extensions. * @param errorPtr An optional error pointer to fill in with a failure * reason if the data can not be parsed. * * @return A new instance of the generated class. **/ + (nullable instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (nullable GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr; /** * Creates a new instance by parsing the data from the given input stream. This * method should be sent to the generated message class that the data should * be interpreted as. If there is an error the method returns nil and the error * is returned in errorPtr (when provided). * * @note Unlike the parseFrom... methods, this never checks to see if all of * the required fields are set. So this method can be used to reload * messages that may not be complete. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param input The stream to read data from. * @param extensionRegistry The extension registry to use to look up extensions. * @param errorPtr An optional error pointer to fill in with a failure * reason if the data can not be parsed. * * @return A new instance of the generated class. **/ + (nullable instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (nullable GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr; /** * Initializes an instance by parsing the data. This method should be sent to * the generated message class that the data should be interpreted as. If * there is an error the method returns nil and the error is returned in * errorPtr (when provided). * * @note In DEBUG builds, the parsed message is checked to be sure all required * fields were provided, and the parse will fail if some are missing. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param data The data to parse. * @param errorPtr An optional error pointer to fill in with a failure reason if * the data can not be parsed. * * @return An initialized instance of the generated class. **/ - (nullable instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr; /** * Initializes an instance by parsing the data. This method should be sent to * the generated message class that the data should be interpreted as. If * there is an error the method returns nil and the error is returned in * errorPtr (when provided). * * @note In DEBUG builds, the parsed message is checked to be sure all required * fields were provided, and the parse will fail if some are missing. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param data The data to parse. * @param extensionRegistry The extension registry to use to look up extensions. * @param errorPtr An optional error pointer to fill in with a failure * reason if the data can not be parsed. * * @return An initialized instance of the generated class. **/ - (nullable instancetype)initWithData:(NSData *)data extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr; /** * Initializes an instance by parsing the data from the given input stream. This * method should be sent to the generated message class that the data should * be interpreted as. If there is an error the method returns nil and the error * is returned in errorPtr (when provided). * * @note Unlike the parseFrom... methods, this never checks to see if all of * the required fields are set. So this method can be used to reload * messages that may not be complete. * * @note The errors returned are likely coming from the domain and codes listed * at the top of this file and GPBCodedInputStream.h. * * @param input The stream to read data from. * @param extensionRegistry The extension registry to use to look up extensions. * @param errorPtr An optional error pointer to fill in with a failure * reason if the data can not be parsed. * * @return An initialized instance of the generated class. **/ - (nullable instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (nullable GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr; /** * Parses the given data as this message's class, and merges those values into * this message. * * @param data The binary representation of the message to merge. * @param extensionRegistry The extension registry to use to look up extensions. * * @exception GPBCodedInputStreamException Exception thrown when parsing was * unsuccessful. **/ - (void)mergeFromData:(NSData *)data extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; /** * Merges the fields from another message (of the same type) into this * message. * * @param other Message to merge into this message. **/ - (void)mergeFrom:(GPBMessage *)other; /** * Writes out the message to the given coded output stream. * * @param output The coded output stream into which to write the message. **/ - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output; /** * Writes out the message to the given output stream. * * @param output The output stream into which to write the message. **/ - (void)writeToOutputStream:(NSOutputStream *)output; /** * Writes out a varint for the message size followed by the the message to * the given output stream. * * @param output The coded output stream into which to write the message. **/ - (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output; /** * Writes out a varint for the message size followed by the the message to * the given output stream. * * @param output The output stream into which to write the message. **/ - (void)writeDelimitedToOutputStream:(NSOutputStream *)output; /** * Serializes the message to an NSData. * * If there is an error while generating the data, nil is returned. * * @note This value is not cached, so if you are using it repeatedly, cache * it yourself. * * @note In DEBUG ONLY, the message is also checked for all required field, * if one is missing, nil will be returned. * * @return The binary representation of the message. **/ - (nullable NSData *)data; /** * Serializes a varint with the message size followed by the message data, * returning that as an NSData. * * @note This value is not cached, so if you are using it repeatedly, it is * recommended to keep a local copy. * * @return The binary representation of the size along with the message. **/ - (NSData *)delimitedData; /** * Calculates the size of the object if it were serialized. * * This is not a cached value. If you are following a pattern like this: * * ``` * size_t size = [aMsg serializedSize]; * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)]; * [foo writeSize:size]; * [foo appendData:[aMsg data]]; * ``` * * you would be better doing: * * ``` * NSData *data = [aMsg data]; * NSUInteger size = [aMsg length]; * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)]; * [foo writeSize:size]; * [foo appendData:data]; * ``` * * @return The size of the message in it's binary representation. **/ - (size_t)serializedSize; /** * @return The descriptor for the message class. **/ + (GPBDescriptor *)descriptor; /** * Return the descriptor for the message. **/ - (GPBDescriptor *)descriptor; /** * @return An array with the extension descriptors that are currently set on the * message. **/ - (NSArray *)extensionsCurrentlySet; /** * Checks whether there is an extension set on the message which matches the * given extension descriptor. * * @param extension Extension descriptor to check if it's set on the message. * * @return Whether the extension is currently set on the message. **/ - (BOOL)hasExtension:(GPBExtensionDescriptor *)extension; /* * Fetches the given extension's value for this message. * * Extensions use boxed values (NSNumbers) for PODs and NSMutableArrays for * repeated fields. If the extension is a Message one will be auto created for * you and returned similar to fields. * * @param extension The extension descriptor of the extension to fetch. * * @return The extension matching the given descriptor, or nil if none found. **/ - (nullable id)getExtension:(GPBExtensionDescriptor *)extension; /** * Sets the given extension's value for this message. This only applies for * single field extensions (i.e. - not repeated fields). * * Extensions use boxed values (NSNumbers). * * @param extension The extension descriptor under which to set the value. * @param value The value to be set as the extension. **/ - (void)setExtension:(GPBExtensionDescriptor *)extension value:(nullable id)value; /** * Adds the given value to the extension for this message. This only applies * to repeated field extensions. If the field is a repeated POD type, the value * should be an NSNumber. * * @param extension The extension descriptor under which to add the value. * @param value The value to be added to the repeated extension. **/ - (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value; /** * Replaces the value at the given index with the given value for the extension * on this message. This only applies to repeated field extensions. If the field * is a repeated POD type, the value is should be an NSNumber. * * @param extension The extension descriptor under which to replace the value. * @param index The index of the extension to be replaced. * @param value The value to be replaced in the repeated extension. **/ - (void)setExtension:(GPBExtensionDescriptor *)extension index:(NSUInteger)index value:(id)value; /** * Clears the given extension for this message. * * @param extension The extension descriptor to be cleared from this message. **/ - (void)clearExtension:(GPBExtensionDescriptor *)extension; /** * Resets all of the fields of this message to their default values. **/ - (void)clear; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBMessage.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBMessage_PackagePrivate.h" #import #import #import "GPBArray_PackagePrivate.h" #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBDictionary_PackagePrivate.h" #import "GPBExtensionInternals.h" #import "GPBExtensionRegistry.h" #import "GPBRootObject_PackagePrivate.h" #import "GPBUnknownFieldSet_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" NSString *const GPBMessageErrorDomain = GPBNSStringifySymbol(GPBMessageErrorDomain); NSString *const GPBErrorReasonKey = @"Reason"; static NSString *const kGPBDataCoderKey = @"GPBData"; // // PLEASE REMEMBER: // // This is the base class for *all* messages generated, so any selector defined, // *public* or *private* could end up colliding with a proto message field. So // avoid using selectors that could match a property, use C functions to hide // them, etc. // @interface GPBMessage () { @package GPBUnknownFieldSet *unknownFields_; NSMutableDictionary *extensionMap_; NSMutableDictionary *autocreatedExtensionMap_; // If the object was autocreated, we remember the creator so that if we get // mutated, we can inform the creator to make our field visible. GPBMessage *autocreator_; GPBFieldDescriptor *autocreatorField_; GPBExtensionDescriptor *autocreatorExtension_; } @end static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) __attribute__((ns_returns_retained)); static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax); static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) __attribute__((ns_returns_retained)); static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax); static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) __attribute__((ns_returns_retained)); #ifdef DEBUG static NSError *MessageError(NSInteger code, NSDictionary *userInfo) { return [NSError errorWithDomain:GPBMessageErrorDomain code:code userInfo:userInfo]; } #endif static NSError *ErrorFromException(NSException *exception) { NSError *error = nil; if ([exception.name isEqual:GPBCodedInputStreamException]) { NSDictionary *exceptionInfo = exception.userInfo; error = exceptionInfo[GPBCodedInputStreamUnderlyingErrorKey]; } if (!error) { NSString *reason = exception.reason; NSDictionary *userInfo = nil; if ([reason length]) { userInfo = @{ GPBErrorReasonKey : reason }; } error = [NSError errorWithDomain:GPBMessageErrorDomain code:GPBMessageErrorCodeOther userInfo:userInfo]; } return error; } static void CheckExtension(GPBMessage *self, GPBExtensionDescriptor *extension) { if ([self class] != extension.containingMessageClass) { [NSException raise:NSInvalidArgumentException format:@"Extension %@ used on wrong class (%@ instead of %@)", extension.singletonName, [self class], extension.containingMessageClass]; } } static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) { if (extensionMap.count == 0) { return nil; } NSMutableDictionary *result = [[NSMutableDictionary allocWithZone:zone] initWithCapacity:extensionMap.count]; for (GPBExtensionDescriptor *extension in extensionMap) { id value = [extensionMap objectForKey:extension]; BOOL isMessageExtension = GPBExtensionIsMessage(extension); if (extension.repeated) { if (isMessageExtension) { NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:[value count]]; for (GPBMessage *listValue in value) { GPBMessage *copiedValue = [listValue copyWithZone:zone]; [list addObject:copiedValue]; [copiedValue release]; } [result setObject:list forKey:extension]; [list release]; } else { NSMutableArray *copiedValue = [value mutableCopyWithZone:zone]; [result setObject:copiedValue forKey:extension]; [copiedValue release]; } } else { if (isMessageExtension) { GPBMessage *copiedValue = [value copyWithZone:zone]; [result setObject:copiedValue forKey:extension]; [copiedValue release]; } else { [result setObject:value forKey:extension]; } } } return result; } static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) { id result; GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { case GPBDataTypeBool: result = [[GPBBoolArray alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBUInt32Array alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBInt32Array alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBUInt64Array alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBInt64Array alloc] init]; break; case GPBDataTypeFloat: result = [[GPBFloatArray alloc] init]; break; case GPBDataTypeDouble: result = [[GPBDoubleArray alloc] init]; break; case GPBDataTypeEnum: result = [[GPBEnumArray alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeGroup: case GPBDataTypeMessage: case GPBDataTypeString: if (autocreator) { result = [[GPBAutocreatedArray alloc] init]; } else { result = [[NSMutableArray alloc] init]; } break; } if (autocreator) { if (GPBDataTypeIsObject(fieldDataType)) { GPBAutocreatedArray *autoArray = result; autoArray->_autocreator = autocreator; } else { GPBInt32Array *gpbArray = result; gpbArray->_autocreator = autocreator; } } return result; } static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) { id result; GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); switch (keyDataType) { case GPBDataTypeBool: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBBoolBoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBBoolUInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBBoolInt32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBBoolUInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBBoolInt64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBBoolFloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBBoolDoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBBoolEnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: result = [[GPBBoolObjectDictionary alloc] init]; break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBUInt32BoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBUInt32UInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBUInt32Int32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBUInt32UInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBUInt32Int64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBUInt32FloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBUInt32DoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBUInt32EnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: result = [[GPBUInt32ObjectDictionary alloc] init]; break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBInt32BoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBInt32UInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBInt32Int32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBInt32UInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBInt32Int64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBInt32FloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBInt32DoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBInt32EnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: result = [[GPBInt32ObjectDictionary alloc] init]; break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBUInt64BoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBUInt64UInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBUInt64Int32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBUInt64UInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBUInt64Int64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBUInt64FloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBUInt64DoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBUInt64EnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: result = [[GPBUInt64ObjectDictionary alloc] init]; break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBInt64BoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBInt64UInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBInt64Int32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBInt64UInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBInt64Int64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBInt64FloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBInt64DoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBInt64EnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: result = [[GPBInt64ObjectDictionary alloc] init]; break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeString: switch (valueDataType) { case GPBDataTypeBool: result = [[GPBStringBoolDictionary alloc] init]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: result = [[GPBStringUInt32Dictionary alloc] init]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: result = [[GPBStringInt32Dictionary alloc] init]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: result = [[GPBStringUInt64Dictionary alloc] init]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: result = [[GPBStringInt64Dictionary alloc] init]; break; case GPBDataTypeFloat: result = [[GPBStringFloatDictionary alloc] init]; break; case GPBDataTypeDouble: result = [[GPBStringDoubleDictionary alloc] init]; break; case GPBDataTypeEnum: result = [[GPBStringEnumDictionary alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: case GPBDataTypeMessage: case GPBDataTypeString: if (autocreator) { result = [[GPBAutocreatedDictionary alloc] init]; } else { result = [[NSMutableDictionary alloc] init]; } break; case GPBDataTypeGroup: NSCAssert(NO, @"shouldn't happen"); return nil; } break; case GPBDataTypeFloat: case GPBDataTypeDouble: case GPBDataTypeEnum: case GPBDataTypeBytes: case GPBDataTypeGroup: case GPBDataTypeMessage: NSCAssert(NO, @"shouldn't happen"); return nil; } if (autocreator) { if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { GPBAutocreatedDictionary *autoDict = result; autoDict->_autocreator = autocreator; } else { GPBInt32Int32Dictionary *gpbDict = result; gpbDict->_autocreator = autocreator; } } return result; } #if !defined(__clang_analyzer__) // These functions are blocked from the analyzer because the analyzer sees the // GPBSetRetainedObjectIvarWithFieldInternal() call as consuming the array/map, // so use of the array/map after the call returns is flagged as a use after // free. // But GPBSetRetainedObjectIvarWithFieldInternal() is "consuming" the retain // count be holding onto the object (it is transfering it), the object is // still valid after returning from the call. The other way to avoid this // would be to add a -retain/-autorelease, but that would force every // repeated/map field parsed into the autorelease pool which is both a memory // and performance hit. static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax) { id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!array) { // No lock needed, this is called from places expecting to mutate // so no threading protection is needed. array = CreateArrayForField(field, nil); GPBSetRetainedObjectIvarWithFieldInternal(self, field, array, syntax); } return array; } // This is like GPBGetObjectIvarWithField(), but for arrays, it should // only be used to wire the method into the class. static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!array) { // Check again after getting the lock. GPBPrepareReadOnlySemaphore(self); dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!array) { array = CreateArrayForField(field, self); GPBSetAutocreatedRetainedObjectIvarWithField(self, field, array); } dispatch_semaphore_signal(self->readOnlySemaphore_); } return array; } static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax) { id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!dict) { // No lock needed, this is called from places expecting to mutate // so no threading protection is needed. dict = CreateMapForField(field, nil); GPBSetRetainedObjectIvarWithFieldInternal(self, field, dict, syntax); } return dict; } // This is like GPBGetObjectIvarWithField(), but for maps, it should // only be used to wire the method into the class. static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!dict) { // Check again after getting the lock. GPBPrepareReadOnlySemaphore(self); dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!dict) { dict = CreateMapForField(field, self); GPBSetAutocreatedRetainedObjectIvarWithField(self, field, dict); } dispatch_semaphore_signal(self->readOnlySemaphore_); } return dict; } #endif // !defined(__clang_analyzer__) GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator, GPBFieldDescriptor *field) { GPBMessage *message = [[msgClass alloc] init]; message->autocreator_ = autocreator; message->autocreatorField_ = [field retain]; return message; } static GPBMessage *CreateMessageWithAutocreatorForExtension( Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension) __attribute__((ns_returns_retained)); static GPBMessage *CreateMessageWithAutocreatorForExtension( Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension) { GPBMessage *message = [[msgClass alloc] init]; message->autocreator_ = autocreator; message->autocreatorExtension_ = [extension retain]; return message; } BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent) { return (message->autocreator_ == parent); } void GPBBecomeVisibleToAutocreator(GPBMessage *self) { // Message objects that are implicitly created by accessing a message field // are initially not visible via the hasX selector. This method makes them // visible. if (self->autocreator_) { // This will recursively make all parent messages visible until it reaches a // super-creator that's visible. if (self->autocreatorField_) { GPBFileSyntax syntax = [self->autocreator_ descriptor].file.syntax; GPBSetObjectIvarWithFieldInternal(self->autocreator_, self->autocreatorField_, self, syntax); } else { [self->autocreator_ setExtension:self->autocreatorExtension_ value:self]; } } } void GPBAutocreatedArrayModified(GPBMessage *self, id array) { // When one of our autocreated arrays adds elements, make it visible. GPBDescriptor *descriptor = [[self class] descriptor]; for (GPBFieldDescriptor *field in descriptor->fields_) { if (field.fieldType == GPBFieldTypeRepeated) { id curArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (curArray == array) { if (GPBFieldDataTypeIsObject(field)) { GPBAutocreatedArray *autoArray = array; autoArray->_autocreator = nil; } else { GPBInt32Array *gpbArray = array; gpbArray->_autocreator = nil; } GPBBecomeVisibleToAutocreator(self); return; } } } NSCAssert(NO, @"Unknown autocreated %@ for %@.", [array class], self); } void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) { // When one of our autocreated dicts adds elements, make it visible. GPBDescriptor *descriptor = [[self class] descriptor]; for (GPBFieldDescriptor *field in descriptor->fields_) { if (field.fieldType == GPBFieldTypeMap) { id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (curDict == dictionary) { if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { GPBAutocreatedDictionary *autoDict = dictionary; autoDict->_autocreator = nil; } else { GPBInt32Int32Dictionary *gpbDict = dictionary; gpbDict->_autocreator = nil; } GPBBecomeVisibleToAutocreator(self); return; } } } NSCAssert(NO, @"Unknown autocreated %@ for %@.", [dictionary class], self); } void GPBClearMessageAutocreator(GPBMessage *self) { if ((self == nil) || !self->autocreator_) { return; } #if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS) // Either the autocreator must have its "has" flag set to YES, or it must be // NO and not equal to ourselves. BOOL autocreatorHas = (self->autocreatorField_ ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_) : [self->autocreator_ hasExtension:self->autocreatorExtension_]); GPBMessage *autocreatorFieldValue = (self->autocreatorField_ ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, self->autocreatorField_) : [self->autocreator_->autocreatedExtensionMap_ objectForKey:self->autocreatorExtension_]); NSCAssert(autocreatorHas || autocreatorFieldValue != self, @"Cannot clear autocreator because it still refers to self, self: %@.", self); #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) self->autocreator_ = nil; [self->autocreatorField_ release]; self->autocreatorField_ = nil; [self->autocreatorExtension_ release]; self->autocreatorExtension_ = nil; } static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { if (!self->unknownFields_) { self->unknownFields_ = [[GPBUnknownFieldSet alloc] init]; GPBBecomeVisibleToAutocreator(self); } return self->unknownFields_; } @implementation GPBMessage + (void)initialize { Class pbMessageClass = [GPBMessage class]; if ([self class] == pbMessageClass) { // This is here to start up the "base" class descriptor. [self descriptor]; // Message shares extension method resolving with GPBRootObject so insure // it is started up at the same time. (void)[GPBRootObject class]; } else if ([self superclass] == pbMessageClass) { // This is here to start up all the "message" subclasses. Just needs to be // done for the messages, not any of the subclasses. // This must be done in initialize to enforce thread safety of start up of // the protocol buffer library. // Note: The generated code for -descriptor calls // +[GPBDescriptor allocDescriptorForClass:...], passing the GPBRootObject // subclass for the file. That call chain is what ensures that *Root class // is started up to support extension resolution off the message class // (+resolveClassMethod: below) in a thread safe manner. [self descriptor]; } } + (instancetype)allocWithZone:(NSZone *)zone { // Override alloc to allocate our classes with the additional storage // required for the instance variables. GPBDescriptor *descriptor = [self descriptor]; return NSAllocateObject(self, descriptor->storageSize_, zone); } + (instancetype)alloc { return [self allocWithZone:nil]; } + (GPBDescriptor *)descriptor { // This is thread safe because it is called from +initialize. static GPBDescriptor *descriptor = NULL; static GPBFileDescriptor *fileDescriptor = NULL; if (!descriptor) { // Use a dummy file that marks it as proto2 syntax so when used generically // it supports unknowns/etc. fileDescriptor = [[GPBFileDescriptor alloc] initWithPackage:@"internal" syntax:GPBFileSyntaxProto2]; descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class] rootClass:Nil file:fileDescriptor fields:NULL fieldCount:0 storageSize:0 flags:0]; } return descriptor; } + (instancetype)message { return [[[self alloc] init] autorelease]; } - (instancetype)init { if ((self = [super init])) { messageStorage_ = (GPBMessage_StoragePtr)( ((uint8_t *)self) + class_getInstanceSize([self class])); } return self; } - (instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr { return [self initWithData:data extensionRegistry:nil error:errorPtr]; } - (instancetype)initWithData:(NSData *)data extensionRegistry:(GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr { if ((self = [self init])) { @try { [self mergeFromData:data extensionRegistry:extensionRegistry]; if (errorPtr) { *errorPtr = nil; } } @catch (NSException *exception) { [self release]; self = nil; if (errorPtr) { *errorPtr = ErrorFromException(exception); } } #ifdef DEBUG if (self && !self.initialized) { [self release]; self = nil; if (errorPtr) { *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); } } #endif } return self; } - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr { if ((self = [self init])) { @try { [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; if (errorPtr) { *errorPtr = nil; } } @catch (NSException *exception) { [self release]; self = nil; if (errorPtr) { *errorPtr = ErrorFromException(exception); } } #ifdef DEBUG if (self && !self.initialized) { [self release]; self = nil; if (errorPtr) { *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); } } #endif } return self; } - (void)dealloc { [self internalClear:NO]; NSCAssert(!autocreator_, @"Autocreator was not cleared before dealloc."); if (readOnlySemaphore_) { dispatch_release(readOnlySemaphore_); } [super dealloc]; } - (void)copyFieldsInto:(GPBMessage *)message zone:(NSZone *)zone descriptor:(GPBDescriptor *)descriptor { // Copy all the storage... memcpy(message->messageStorage_, messageStorage_, descriptor->storageSize_); GPBFileSyntax syntax = descriptor.file.syntax; // Loop over the fields doing fixup... for (GPBFieldDescriptor *field in descriptor->fields_) { if (GPBFieldIsMapOrArray(field)) { id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (value) { // We need to copy the array/map, but the catch is for message fields, // we also need to ensure all the messages as those need copying also. id newValue; if (GPBFieldDataTypeIsMessage(field)) { if (field.fieldType == GPBFieldTypeRepeated) { NSArray *existingArray = (NSArray *)value; NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:existingArray.count]; newValue = newArray; for (GPBMessage *msg in existingArray) { GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newArray addObject:copiedMsg]; [copiedMsg release]; } } else { if (field.mapKeyDataType == GPBDataTypeString) { // Map is an NSDictionary. NSDictionary *existingDict = value; NSMutableDictionary *newDict = [[NSMutableDictionary alloc] initWithCapacity:existingDict.count]; newValue = newDict; [existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) GPBMessage *copiedMsg = [msg copyWithZone:zone]; [newDict setObject:copiedMsg forKey:key]; [copiedMsg release]; }]; } else { // Is one of the GPB*ObjectDictionary classes. Type doesn't // matter, just need one to invoke the selector. GPBInt32ObjectDictionary *existingDict = value; newValue = [existingDict deepCopyWithZone:zone]; } } } else { // Not messages (but is a map/array)... if (field.fieldType == GPBFieldTypeRepeated) { if (GPBFieldDataTypeIsObject(field)) { // NSArray newValue = [value mutableCopyWithZone:zone]; } else { // GPB*Array newValue = [value copyWithZone:zone]; } } else { if (field.mapKeyDataType == GPBDataTypeString) { // NSDictionary newValue = [value mutableCopyWithZone:zone]; } else { // Is one of the GPB*Dictionary classes. Type doesn't matter, // just need one to invoke the selector. GPBInt32Int32Dictionary *existingDict = value; newValue = [existingDict copyWithZone:zone]; } } } // We retain here because the memcpy picked up the pointer value and // the next call to SetRetainedObject... will release the current value. [value retain]; GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, syntax); } } else if (GPBFieldDataTypeIsMessage(field)) { // For object types, if we have a value, copy it. If we don't, // zero it to remove the pointer to something that was autocreated // (and the ptr just got memcpyed). if (GPBGetHasIvarField(self, field)) { GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBMessage *newValue = [value copyWithZone:zone]; // We retain here because the memcpy picked up the pointer value and // the next call to SetRetainedObject... will release the current value. [value retain]; GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, syntax); } else { uint8_t *storage = (uint8_t *)message->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; *typePtr = NULL; } } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) { // A set string/data value (message picked off above), copy it. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id newValue = [value copyWithZone:zone]; // We retain here because the memcpy picked up the pointer value and // the next call to SetRetainedObject... will release the current value. [value retain]; GPBSetRetainedObjectIvarWithFieldInternal(message, field, newValue, syntax); } else { // memcpy took care of the rest of the primitive fields if they were set. } } // for (field in descriptor->fields_) } - (id)copyWithZone:(NSZone *)zone { GPBDescriptor *descriptor = [self descriptor]; GPBMessage *result = [[descriptor.messageClass allocWithZone:zone] init]; [self copyFieldsInto:result zone:zone descriptor:descriptor]; // Make immutable copies of the extra bits. result->unknownFields_ = [unknownFields_ copyWithZone:zone]; result->extensionMap_ = CloneExtensionMap(extensionMap_, zone); return result; } - (void)clear { [self internalClear:YES]; } - (void)internalClear:(BOOL)zeroStorage { GPBDescriptor *descriptor = [self descriptor]; for (GPBFieldDescriptor *field in descriptor->fields_) { if (GPBFieldIsMapOrArray(field)) { id arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (arrayOrMap) { if (field.fieldType == GPBFieldTypeRepeated) { if (GPBFieldDataTypeIsObject(field)) { if ([arrayOrMap isKindOfClass:[GPBAutocreatedArray class]]) { GPBAutocreatedArray *autoArray = arrayOrMap; if (autoArray->_autocreator == self) { autoArray->_autocreator = nil; } } } else { // Type doesn't matter, it is a GPB*Array. GPBInt32Array *gpbArray = arrayOrMap; if (gpbArray->_autocreator == self) { gpbArray->_autocreator = nil; } } } else { if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) { GPBAutocreatedDictionary *autoDict = arrayOrMap; if (autoDict->_autocreator == self) { autoDict->_autocreator = nil; } } } else { // Type doesn't matter, it is a GPB*Dictionary. GPBInt32Int32Dictionary *gpbDict = arrayOrMap; if (gpbDict->_autocreator == self) { gpbDict->_autocreator = nil; } } } [arrayOrMap release]; } } else if (GPBFieldDataTypeIsMessage(field)) { GPBClearAutocreatedMessageIvarWithField(self, field); GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [value release]; } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) { id value = GPBGetObjectIvarWithField(self, field); [value release]; } } // GPBClearMessageAutocreator() expects that its caller has already been // removed from autocreatedExtensionMap_ so we set to nil first. NSArray *autocreatedValues = [autocreatedExtensionMap_ allValues]; [autocreatedExtensionMap_ release]; autocreatedExtensionMap_ = nil; // Since we're clearing all of our extensions, make sure that we clear the // autocreator on any that we've created so they no longer refer to us. for (GPBMessage *value in autocreatedValues) { NSCAssert(GPBWasMessageAutocreatedBy(value, self), @"Autocreated extension does not refer back to self."); GPBClearMessageAutocreator(value); } [extensionMap_ release]; extensionMap_ = nil; [unknownFields_ release]; unknownFields_ = nil; // Note that clearing does not affect autocreator_. If we are being cleared // because of a dealloc, then autocreator_ should be nil anyway. If we are // being cleared because someone explicitly clears us, we don't want to // sever our relationship with our autocreator. if (zeroStorage) { memset(messageStorage_, 0, descriptor->storageSize_); } } - (BOOL)isInitialized { GPBDescriptor *descriptor = [self descriptor]; for (GPBFieldDescriptor *field in descriptor->fields_) { if (field.isRequired) { if (!GPBGetHasIvarField(self, field)) { return NO; } } if (GPBFieldDataTypeIsMessage(field)) { GPBFieldType fieldType = field.fieldType; if (fieldType == GPBFieldTypeSingle) { if (field.isRequired) { GPBMessage *message = GPBGetMessageMessageField(self, field); if (!message.initialized) { return NO; } } else { NSAssert(field.isOptional, @"%@: Single message field %@ not required or optional?", [self class], field.name); if (GPBGetHasIvarField(self, field)) { GPBMessage *message = GPBGetMessageMessageField(self, field); if (!message.initialized) { return NO; } } } } else if (fieldType == GPBFieldTypeRepeated) { NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); for (GPBMessage *message in array) { if (!message.initialized) { return NO; } } } else { // fieldType == GPBFieldTypeMap if (field.mapKeyDataType == GPBDataTypeString) { NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) { return NO; } } else { // Real type is GPB*ObjectDictionary, exact type doesn't matter. GPBInt32ObjectDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (map && ![map isInitialized]) { return NO; } } } } } __block BOOL result = YES; [extensionMap_ enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, id obj, BOOL *stop) { if (GPBExtensionIsMessage(extension)) { if (extension.isRepeated) { for (GPBMessage *msg in obj) { if (!msg.initialized) { result = NO; *stop = YES; break; } } } else { GPBMessage *asMsg = obj; if (!asMsg.initialized) { result = NO; *stop = YES; } } } }]; return result; } - (GPBDescriptor *)descriptor { return [[self class] descriptor]; } - (NSData *)data { #ifdef DEBUG if (!self.initialized) { return nil; } #endif NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]]; GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data]; @try { [self writeToCodedOutputStream:stream]; } @catch (NSException *exception) { // This really shouldn't happen. The only way writeToCodedOutputStream: // could throw is if something in the library has a bug and the // serializedSize was wrong. #ifdef DEBUG NSLog(@"%@: Internal exception while building message data: %@", [self class], exception); #endif data = nil; } [stream release]; return data; } - (NSData *)delimitedData { size_t serializedSize = [self serializedSize]; size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize); NSMutableData *data = [NSMutableData dataWithLength:(serializedSize + varintSize)]; GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data]; @try { [self writeDelimitedToCodedOutputStream:stream]; } @catch (NSException *exception) { // This really shouldn't happen. The only way writeToCodedOutputStream: // could throw is if something in the library has a bug and the // serializedSize was wrong. #ifdef DEBUG NSLog(@"%@: Internal exception while building message delimitedData: %@", [self class], exception); #endif // If it happens, truncate. data.length = 0; } [stream release]; return data; } - (void)writeToOutputStream:(NSOutputStream *)output { GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithOutputStream:output]; [self writeToCodedOutputStream:stream]; [stream release]; } - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output { GPBDescriptor *descriptor = [self descriptor]; NSArray *fieldsArray = descriptor->fields_; NSUInteger fieldCount = fieldsArray.count; const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; NSUInteger extensionRangesCount = descriptor.extensionRangesCount; for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { if (i == fieldCount) { [self writeExtensionsToCodedOutputStream:output range:extensionRanges[j++]]; } else if (j == extensionRangesCount || GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { [self writeField:fieldsArray[i++] toCodedOutputStream:output]; } else { [self writeExtensionsToCodedOutputStream:output range:extensionRanges[j++]]; } } if (descriptor.isWireFormat) { [unknownFields_ writeAsMessageSetTo:output]; } else { [unknownFields_ writeToCodedOutputStream:output]; } } - (void)writeDelimitedToOutputStream:(NSOutputStream *)output { GPBCodedOutputStream *codedOutput = [[GPBCodedOutputStream alloc] initWithOutputStream:output]; [self writeDelimitedToCodedOutputStream:codedOutput]; [codedOutput release]; } - (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output { [output writeRawVarintSizeTAs32:[self serializedSize]]; [self writeToCodedOutputStream:output]; } - (void)writeField:(GPBFieldDescriptor *)field toCodedOutputStream:(GPBCodedOutputStream *)output { GPBFieldType fieldType = field.fieldType; if (fieldType == GPBFieldTypeSingle) { BOOL has = GPBGetHasIvarField(self, field); if (!has) { return; } } uint32_t fieldNumber = GPBFieldNumber(field); //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE) //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE) //%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE) //% case GPBDataType##TYPE: //% if (fieldType == GPBFieldTypeRepeated) { //% uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; //% GPB##ARRAY_TYPE##Array *array = //% GPBGetObjectIvarWithFieldNoAutocreate(self, field); //% [output write##TYPE##Array:fieldNumber values:array tag:tag]; //% } else if (fieldType == GPBFieldTypeSingle) { //% [output write##TYPE:fieldNumber //% TYPE$S value:GPBGetMessage##REAL_TYPE##Field(self, field)]; //% } else { // fieldType == GPBFieldTypeMap //% // Exact type here doesn't matter. //% GPBInt32##ARRAY_TYPE##Dictionary *dict = //% GPBGetObjectIvarWithFieldNoAutocreate(self, field); //% [dict writeToCodedOutputStream:output asField:field]; //% } //% break; //% //%PDDM-DEFINE FIELD_CASE2(TYPE) //% case GPBDataType##TYPE: //% if (fieldType == GPBFieldTypeRepeated) { //% NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); //% [output write##TYPE##Array:fieldNumber values:array]; //% } else if (fieldType == GPBFieldTypeSingle) { //% // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check //% // again. //% [output write##TYPE:fieldNumber //% TYPE$S value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; //% } else { // fieldType == GPBFieldTypeMap //% // Exact type here doesn't matter. //% id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); //% GPBDataType mapKeyDataType = field.mapKeyDataType; //% if (mapKeyDataType == GPBDataTypeString) { //% GPBDictionaryWriteToStreamInternalHelper(output, dict, field); //% } else { //% [dict writeToCodedOutputStream:output asField:field]; //% } //% } //% break; //% switch (GPBGetFieldDataType(field)) { //%PDDM-EXPAND FIELD_CASE(Bool, Bool) // This block of code is generated, do not edit it directly. case GPBDataTypeBool: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBBoolArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeBoolArray:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeBool:fieldNumber value:GPBGetMessageBoolField(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32BoolDictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32) // This block of code is generated, do not edit it directly. case GPBDataTypeFixed32: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBUInt32Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeFixed32Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeFixed32:fieldNumber value:GPBGetMessageUInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32UInt32Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(SFixed32, Int32) // This block of code is generated, do not edit it directly. case GPBDataTypeSFixed32: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt32Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeSFixed32Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeSFixed32:fieldNumber value:GPBGetMessageInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int32Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Float, Float) // This block of code is generated, do not edit it directly. case GPBDataTypeFloat: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBFloatArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeFloatArray:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeFloat:fieldNumber value:GPBGetMessageFloatField(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32FloatDictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64) // This block of code is generated, do not edit it directly. case GPBDataTypeFixed64: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBUInt64Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeFixed64Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeFixed64:fieldNumber value:GPBGetMessageUInt64Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32UInt64Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(SFixed64, Int64) // This block of code is generated, do not edit it directly. case GPBDataTypeSFixed64: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt64Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeSFixed64Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeSFixed64:fieldNumber value:GPBGetMessageInt64Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int64Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Double, Double) // This block of code is generated, do not edit it directly. case GPBDataTypeDouble: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBDoubleArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeDoubleArray:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeDouble:fieldNumber value:GPBGetMessageDoubleField(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32DoubleDictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Int32, Int32) // This block of code is generated, do not edit it directly. case GPBDataTypeInt32: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt32Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeInt32Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeInt32:fieldNumber value:GPBGetMessageInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int32Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(Int64, Int64) // This block of code is generated, do not edit it directly. case GPBDataTypeInt64: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt64Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeInt64Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeInt64:fieldNumber value:GPBGetMessageInt64Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int64Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(SInt32, Int32) // This block of code is generated, do not edit it directly. case GPBDataTypeSInt32: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt32Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeSInt32Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeSInt32:fieldNumber value:GPBGetMessageInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int32Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(SInt64, Int64) // This block of code is generated, do not edit it directly. case GPBDataTypeSInt64: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBInt64Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeSInt64Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeSInt64:fieldNumber value:GPBGetMessageInt64Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32Int64Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(UInt32, UInt32) // This block of code is generated, do not edit it directly. case GPBDataTypeUInt32: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBUInt32Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeUInt32Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeUInt32:fieldNumber value:GPBGetMessageUInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32UInt32Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE(UInt64, UInt64) // This block of code is generated, do not edit it directly. case GPBDataTypeUInt64: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBUInt64Array *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeUInt64Array:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeUInt64:fieldNumber value:GPBGetMessageUInt64Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32UInt64Dictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum) // This block of code is generated, do not edit it directly. case GPBDataTypeEnum: if (fieldType == GPBFieldTypeRepeated) { uint32_t tag = field.isPackable ? GPBFieldTag(field) : 0; GPBEnumArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeEnumArray:fieldNumber values:array tag:tag]; } else if (fieldType == GPBFieldTypeSingle) { [output writeEnum:fieldNumber value:GPBGetMessageInt32Field(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. GPBInt32EnumDictionary *dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [dict writeToCodedOutputStream:output asField:field]; } break; //%PDDM-EXPAND FIELD_CASE2(Bytes) // This block of code is generated, do not edit it directly. case GPBDataTypeBytes: if (fieldType == GPBFieldTypeRepeated) { NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeBytesArray:fieldNumber values:array]; } else if (fieldType == GPBFieldTypeSingle) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check // again. [output writeBytes:fieldNumber value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBDataType mapKeyDataType = field.mapKeyDataType; if (mapKeyDataType == GPBDataTypeString) { GPBDictionaryWriteToStreamInternalHelper(output, dict, field); } else { [dict writeToCodedOutputStream:output asField:field]; } } break; //%PDDM-EXPAND FIELD_CASE2(String) // This block of code is generated, do not edit it directly. case GPBDataTypeString: if (fieldType == GPBFieldTypeRepeated) { NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeStringArray:fieldNumber values:array]; } else if (fieldType == GPBFieldTypeSingle) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check // again. [output writeString:fieldNumber value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBDataType mapKeyDataType = field.mapKeyDataType; if (mapKeyDataType == GPBDataTypeString) { GPBDictionaryWriteToStreamInternalHelper(output, dict, field); } else { [dict writeToCodedOutputStream:output asField:field]; } } break; //%PDDM-EXPAND FIELD_CASE2(Message) // This block of code is generated, do not edit it directly. case GPBDataTypeMessage: if (fieldType == GPBFieldTypeRepeated) { NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeMessageArray:fieldNumber values:array]; } else if (fieldType == GPBFieldTypeSingle) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check // again. [output writeMessage:fieldNumber value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBDataType mapKeyDataType = field.mapKeyDataType; if (mapKeyDataType == GPBDataTypeString) { GPBDictionaryWriteToStreamInternalHelper(output, dict, field); } else { [dict writeToCodedOutputStream:output asField:field]; } } break; //%PDDM-EXPAND FIELD_CASE2(Group) // This block of code is generated, do not edit it directly. case GPBDataTypeGroup: if (fieldType == GPBFieldTypeRepeated) { NSArray *array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [output writeGroupArray:fieldNumber values:array]; } else if (fieldType == GPBFieldTypeSingle) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has check // again. [output writeGroup:fieldNumber value:GPBGetObjectIvarWithFieldNoAutocreate(self, field)]; } else { // fieldType == GPBFieldTypeMap // Exact type here doesn't matter. id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); GPBDataType mapKeyDataType = field.mapKeyDataType; if (mapKeyDataType == GPBDataTypeString) { GPBDictionaryWriteToStreamInternalHelper(output, dict, field); } else { [dict writeToCodedOutputStream:output asField:field]; } } break; //%PDDM-EXPAND-END (18 expansions) } } #pragma mark - Extensions - (id)getExtension:(GPBExtensionDescriptor *)extension { CheckExtension(self, extension); id value = [extensionMap_ objectForKey:extension]; if (value != nil) { return value; } // No default for repeated. if (extension.isRepeated) { return nil; } // Non messages get their default. if (!GPBExtensionIsMessage(extension)) { return extension.defaultValue; } // Check for an autocreated value. GPBPrepareReadOnlySemaphore(self); dispatch_semaphore_wait(readOnlySemaphore_, DISPATCH_TIME_FOREVER); value = [autocreatedExtensionMap_ objectForKey:extension]; if (!value) { // Auto create the message extensions to match normal fields. value = CreateMessageWithAutocreatorForExtension(extension.msgClass, self, extension); if (autocreatedExtensionMap_ == nil) { autocreatedExtensionMap_ = [[NSMutableDictionary alloc] init]; } // We can't simply call setExtension here because that would clear the new // value's autocreator. [autocreatedExtensionMap_ setObject:value forKey:extension]; [value release]; } dispatch_semaphore_signal(readOnlySemaphore_); return value; } - (id)getExistingExtension:(GPBExtensionDescriptor *)extension { // This is an internal method so we don't need to call CheckExtension(). return [extensionMap_ objectForKey:extension]; } - (BOOL)hasExtension:(GPBExtensionDescriptor *)extension { #if defined(DEBUG) && DEBUG CheckExtension(self, extension); #endif // DEBUG return nil != [extensionMap_ objectForKey:extension]; } - (NSArray *)extensionsCurrentlySet { return [extensionMap_ allKeys]; } - (void)writeExtensionsToCodedOutputStream:(GPBCodedOutputStream *)output range:(GPBExtensionRange)range { NSArray *sortedExtensions = [[extensionMap_ allKeys] sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; uint32_t start = range.start; uint32_t end = range.end; for (GPBExtensionDescriptor *extension in sortedExtensions) { uint32_t fieldNumber = extension.fieldNumber; if (fieldNumber >= start && fieldNumber < end) { id value = [extensionMap_ objectForKey:extension]; GPBWriteExtensionValueToOutputStream(extension, value, output); } } } - (void)setExtension:(GPBExtensionDescriptor *)extension value:(id)value { if (!value) { [self clearExtension:extension]; return; } CheckExtension(self, extension); if (extension.repeated) { [NSException raise:NSInvalidArgumentException format:@"Must call addExtension() for repeated types."]; } if (extensionMap_ == nil) { extensionMap_ = [[NSMutableDictionary alloc] init]; } // This pointless cast is for CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION. // Without it, the compiler complains we're passing an id nullable when // setObject:forKey: requires a id nonnull for the value. The check for // !value at the start of the method ensures it isn't nil, but the check // isn't smart enough to realize that. [extensionMap_ setObject:(id)value forKey:extension]; GPBExtensionDescriptor *descriptor = extension; if (GPBExtensionIsMessage(descriptor) && !descriptor.isRepeated) { GPBMessage *autocreatedValue = [[autocreatedExtensionMap_ objectForKey:extension] retain]; // Must remove from the map before calling GPBClearMessageAutocreator() so // that GPBClearMessageAutocreator() knows its safe to clear. [autocreatedExtensionMap_ removeObjectForKey:extension]; GPBClearMessageAutocreator(autocreatedValue); [autocreatedValue release]; } GPBBecomeVisibleToAutocreator(self); } - (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value { CheckExtension(self, extension); if (!extension.repeated) { [NSException raise:NSInvalidArgumentException format:@"Must call setExtension() for singular types."]; } if (extensionMap_ == nil) { extensionMap_ = [[NSMutableDictionary alloc] init]; } NSMutableArray *list = [extensionMap_ objectForKey:extension]; if (list == nil) { list = [NSMutableArray array]; [extensionMap_ setObject:list forKey:extension]; } [list addObject:value]; GPBBecomeVisibleToAutocreator(self); } - (void)setExtension:(GPBExtensionDescriptor *)extension index:(NSUInteger)idx value:(id)value { CheckExtension(self, extension); if (!extension.repeated) { [NSException raise:NSInvalidArgumentException format:@"Must call setExtension() for singular types."]; } if (extensionMap_ == nil) { extensionMap_ = [[NSMutableDictionary alloc] init]; } NSMutableArray *list = [extensionMap_ objectForKey:extension]; [list replaceObjectAtIndex:idx withObject:value]; GPBBecomeVisibleToAutocreator(self); } - (void)clearExtension:(GPBExtensionDescriptor *)extension { CheckExtension(self, extension); // Only become visible if there was actually a value to clear. if ([extensionMap_ objectForKey:extension]) { [extensionMap_ removeObjectForKey:extension]; GPBBecomeVisibleToAutocreator(self); } } #pragma mark - mergeFrom - (void)mergeFromData:(NSData *)data extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; [input checkLastTagWas:0]; [input release]; } #pragma mark - mergeDelimitedFrom - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { GPBCodedInputStreamState *state = &input->state_; if (GPBCodedInputStreamIsAtEnd(state)) { return; } NSData *data = GPBCodedInputStreamReadRetainedBytesNoCopy(state); if (data == nil) { return; } [self mergeFromData:data extensionRegistry:extensionRegistry]; [data release]; } #pragma mark - Parse From Data Support + (instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr { return [self parseFromData:data extensionRegistry:nil error:errorPtr]; } + (instancetype)parseFromData:(NSData *)data extensionRegistry:(GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr { return [[[self alloc] initWithData:data extensionRegistry:extensionRegistry error:errorPtr] autorelease]; } + (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr { return [[[self alloc] initWithCodedInputStream:input extensionRegistry:extensionRegistry error:errorPtr] autorelease]; } #pragma mark - Parse Delimited From Data Support + (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (GPBExtensionRegistry *)extensionRegistry error:(NSError **)errorPtr { GPBMessage *message = [[[self alloc] init] autorelease]; @try { [message mergeDelimitedFromCodedInputStream:input extensionRegistry:extensionRegistry]; if (errorPtr) { *errorPtr = nil; } } @catch (NSException *exception) { message = nil; if (errorPtr) { *errorPtr = ErrorFromException(exception); } } #ifdef DEBUG if (message && !message.initialized) { message = nil; if (errorPtr) { *errorPtr = MessageError(GPBMessageErrorCodeMissingRequiredField, nil); } } #endif return message; } #pragma mark - Unknown Field Support - (GPBUnknownFieldSet *)unknownFields { return unknownFields_; } - (void)setUnknownFields:(GPBUnknownFieldSet *)unknownFields { if (unknownFields != unknownFields_) { [unknownFields_ release]; unknownFields_ = [unknownFields copy]; GPBBecomeVisibleToAutocreator(self); } } - (void)parseMessageSet:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { uint32_t typeId = 0; NSData *rawBytes = nil; GPBExtensionDescriptor *extension = nil; GPBCodedInputStreamState *state = &input->state_; while (true) { uint32_t tag = GPBCodedInputStreamReadTag(state); if (tag == 0) { break; } if (tag == GPBWireFormatMessageSetTypeIdTag) { typeId = GPBCodedInputStreamReadUInt32(state); if (typeId != 0) { extension = [extensionRegistry extensionForDescriptor:[self descriptor] fieldNumber:typeId]; } } else if (tag == GPBWireFormatMessageSetMessageTag) { rawBytes = [GPBCodedInputStreamReadRetainedBytesNoCopy(state) autorelease]; } else { if (![input skipField:tag]) { break; } } } [input checkLastTagWas:GPBWireFormatMessageSetItemEndTag]; if (rawBytes != nil && typeId != 0) { if (extension != nil) { GPBCodedInputStream *newInput = [[GPBCodedInputStream alloc] initWithData:rawBytes]; GPBExtensionMergeFromInputStream(extension, extension.packable, newInput, extensionRegistry, self); [newInput release]; } else { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); [unknownFields mergeMessageSetMessage:typeId data:rawBytes]; } } } - (BOOL)parseUnknownField:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry tag:(uint32_t)tag { GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag); int32_t fieldNumber = GPBWireFormatGetTagFieldNumber(tag); GPBDescriptor *descriptor = [self descriptor]; GPBExtensionDescriptor *extension = [extensionRegistry extensionForDescriptor:descriptor fieldNumber:fieldNumber]; if (extension == nil) { if (descriptor.wireFormat && GPBWireFormatMessageSetItemTag == tag) { [self parseMessageSet:input extensionRegistry:extensionRegistry]; return YES; } } else { if (extension.wireType == wireType) { GPBExtensionMergeFromInputStream(extension, extension.packable, input, extensionRegistry, self); return YES; } // Primitive, repeated types can be packed on unpacked on the wire, and are // parsed either way. if ([extension isRepeated] && !GPBDataTypeIsObject(extension->description_->dataType) && (extension.alternateWireType == wireType)) { GPBExtensionMergeFromInputStream(extension, !extension.packable, input, extensionRegistry, self); return YES; } } if ([GPBUnknownFieldSet isFieldTag:tag]) { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); return [unknownFields mergeFieldFrom:tag input:input]; } else { return NO; } } - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); [unknownFields addUnknownMapEntry:fieldNum value:data]; } #pragma mark - MergeFromCodedInputStream Support static void MergeSingleFieldFromCodedInputStream( GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \ case GPBDataType##NAME: { \ TYPE val = GPBCodedInputStreamRead##NAME(&input->state_); \ GPBSet##FUNC_TYPE##IvarWithFieldInternal(self, field, val, syntax); \ break; \ } #define CASE_SINGLE_OBJECT(NAME) \ case GPBDataType##NAME: { \ id val = GPBCodedInputStreamReadRetained##NAME(&input->state_); \ GPBSetRetainedObjectIvarWithFieldInternal(self, field, val, syntax); \ break; \ } CASE_SINGLE_POD(Bool, BOOL, Bool) CASE_SINGLE_POD(Fixed32, uint32_t, UInt32) CASE_SINGLE_POD(SFixed32, int32_t, Int32) CASE_SINGLE_POD(Float, float, Float) CASE_SINGLE_POD(Fixed64, uint64_t, UInt64) CASE_SINGLE_POD(SFixed64, int64_t, Int64) CASE_SINGLE_POD(Double, double, Double) CASE_SINGLE_POD(Int32, int32_t, Int32) CASE_SINGLE_POD(Int64, int64_t, Int64) CASE_SINGLE_POD(SInt32, int32_t, Int32) CASE_SINGLE_POD(SInt64, int64_t, Int64) CASE_SINGLE_POD(UInt32, uint32_t, UInt32) CASE_SINGLE_POD(UInt64, uint64_t, UInt64) CASE_SINGLE_OBJECT(Bytes) CASE_SINGLE_OBJECT(String) #undef CASE_SINGLE_POD #undef CASE_SINGLE_OBJECT case GPBDataTypeMessage: { if (GPBGetHasIvarField(self, field)) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has // check again. GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [input readMessage:message extensionRegistry:extensionRegistry]; } else { GPBMessage *message = [[field.msgClass alloc] init]; [input readMessage:message extensionRegistry:extensionRegistry]; GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax); } break; } case GPBDataTypeGroup: { if (GPBGetHasIvarField(self, field)) { // GPBGetObjectIvarWithFieldNoAutocreate() avoids doing the has // check again. GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry]; } else { GPBMessage *message = [[field.msgClass alloc] init]; [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry]; GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax); } break; } case GPBDataTypeEnum: { int32_t val = GPBCodedInputStreamReadEnum(&input->state_); if (GPBHasPreservingUnknownEnumSemantics(syntax) || [field isValidEnumValue:val]) { GPBSetInt32IvarWithFieldInternal(self, field, val, syntax); } else { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; } } } // switch } static void MergeRepeatedPackedFieldFromCodedInputStream( GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, GPBCodedInputStream *input) { GPBDataType fieldDataType = GPBGetFieldDataType(field); GPBCodedInputStreamState *state = &input->state_; id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax); int32_t length = GPBCodedInputStreamReadInt32(state); size_t limit = GPBCodedInputStreamPushLimit(state, length); while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { switch (fieldDataType) { #define CASE_REPEATED_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \ case GPBDataType##NAME: { \ TYPE val = GPBCodedInputStreamRead##NAME(state); \ [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \ break; \ } CASE_REPEATED_PACKED_POD(Bool, BOOL, Bool) CASE_REPEATED_PACKED_POD(Fixed32, uint32_t, UInt32) CASE_REPEATED_PACKED_POD(SFixed32, int32_t, Int32) CASE_REPEATED_PACKED_POD(Float, float, Float) CASE_REPEATED_PACKED_POD(Fixed64, uint64_t, UInt64) CASE_REPEATED_PACKED_POD(SFixed64, int64_t, Int64) CASE_REPEATED_PACKED_POD(Double, double, Double) CASE_REPEATED_PACKED_POD(Int32, int32_t, Int32) CASE_REPEATED_PACKED_POD(Int64, int64_t, Int64) CASE_REPEATED_PACKED_POD(SInt32, int32_t, Int32) CASE_REPEATED_PACKED_POD(SInt64, int64_t, Int64) CASE_REPEATED_PACKED_POD(UInt32, uint32_t, UInt32) CASE_REPEATED_PACKED_POD(UInt64, uint64_t, UInt64) #undef CASE_REPEATED_PACKED_POD case GPBDataTypeBytes: case GPBDataTypeString: case GPBDataTypeMessage: case GPBDataTypeGroup: NSCAssert(NO, @"Non primitive types can't be packed"); break; case GPBDataTypeEnum: { int32_t val = GPBCodedInputStreamReadEnum(state); if (GPBHasPreservingUnknownEnumSemantics(syntax) || [field isValidEnumValue:val]) { [(GPBEnumArray*)genericArray addRawValue:val]; } else { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; } break; } } // switch } // while(BytesUntilLimit() > 0) GPBCodedInputStreamPopLimit(state, limit); } static void MergeRepeatedNotPackedFieldFromCodedInputStream( GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { GPBCodedInputStreamState *state = &input->state_; id genericArray = GetOrCreateArrayIvarWithField(self, field, syntax); switch (GPBGetFieldDataType(field)) { #define CASE_REPEATED_NOT_PACKED_POD(NAME, TYPE, ARRAY_TYPE) \ case GPBDataType##NAME: { \ TYPE val = GPBCodedInputStreamRead##NAME(state); \ [(GPB##ARRAY_TYPE##Array *)genericArray addValue:val]; \ break; \ } #define CASE_REPEATED_NOT_PACKED_OBJECT(NAME) \ case GPBDataType##NAME: { \ id val = GPBCodedInputStreamReadRetained##NAME(state); \ [(NSMutableArray*)genericArray addObject:val]; \ [val release]; \ break; \ } CASE_REPEATED_NOT_PACKED_POD(Bool, BOOL, Bool) CASE_REPEATED_NOT_PACKED_POD(Fixed32, uint32_t, UInt32) CASE_REPEATED_NOT_PACKED_POD(SFixed32, int32_t, Int32) CASE_REPEATED_NOT_PACKED_POD(Float, float, Float) CASE_REPEATED_NOT_PACKED_POD(Fixed64, uint64_t, UInt64) CASE_REPEATED_NOT_PACKED_POD(SFixed64, int64_t, Int64) CASE_REPEATED_NOT_PACKED_POD(Double, double, Double) CASE_REPEATED_NOT_PACKED_POD(Int32, int32_t, Int32) CASE_REPEATED_NOT_PACKED_POD(Int64, int64_t, Int64) CASE_REPEATED_NOT_PACKED_POD(SInt32, int32_t, Int32) CASE_REPEATED_NOT_PACKED_POD(SInt64, int64_t, Int64) CASE_REPEATED_NOT_PACKED_POD(UInt32, uint32_t, UInt32) CASE_REPEATED_NOT_PACKED_POD(UInt64, uint64_t, UInt64) CASE_REPEATED_NOT_PACKED_OBJECT(Bytes) CASE_REPEATED_NOT_PACKED_OBJECT(String) #undef CASE_REPEATED_NOT_PACKED_POD #undef CASE_NOT_PACKED_OBJECT case GPBDataTypeMessage: { GPBMessage *message = [[field.msgClass alloc] init]; [input readMessage:message extensionRegistry:extensionRegistry]; [(NSMutableArray*)genericArray addObject:message]; [message release]; break; } case GPBDataTypeGroup: { GPBMessage *message = [[field.msgClass alloc] init]; [input readGroup:GPBFieldNumber(field) message:message extensionRegistry:extensionRegistry]; [(NSMutableArray*)genericArray addObject:message]; [message release]; break; } case GPBDataTypeEnum: { int32_t val = GPBCodedInputStreamReadEnum(state); if (GPBHasPreservingUnknownEnumSemantics(syntax) || [field isValidEnumValue:val]) { [(GPBEnumArray*)genericArray addRawValue:val]; } else { GPBUnknownFieldSet *unknownFields = GetOrMakeUnknownFields(self); [unknownFields mergeVarintField:GPBFieldNumber(field) value:val]; } break; } } // switch } - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { GPBDescriptor *descriptor = [self descriptor]; GPBFileSyntax syntax = descriptor.file.syntax; GPBCodedInputStreamState *state = &input->state_; uint32_t tag = 0; NSUInteger startingIndex = 0; NSArray *fields = descriptor->fields_; NSUInteger numFields = fields.count; while (YES) { BOOL merged = NO; tag = GPBCodedInputStreamReadTag(state); if (tag == 0) { break; // Reached end. } for (NSUInteger i = 0; i < numFields; ++i) { if (startingIndex >= numFields) startingIndex = 0; GPBFieldDescriptor *fieldDescriptor = fields[startingIndex]; if (GPBFieldTag(fieldDescriptor) == tag) { GPBFieldType fieldType = fieldDescriptor.fieldType; if (fieldType == GPBFieldTypeSingle) { MergeSingleFieldFromCodedInputStream(self, fieldDescriptor, syntax, input, extensionRegistry); // Well formed protos will only have a single field once, advance // the starting index to the next field. startingIndex += 1; } else if (fieldType == GPBFieldTypeRepeated) { if (fieldDescriptor.isPackable) { MergeRepeatedPackedFieldFromCodedInputStream( self, fieldDescriptor, syntax, input); // Well formed protos will only have a repeated field that is // packed once, advance the starting index to the next field. startingIndex += 1; } else { MergeRepeatedNotPackedFieldFromCodedInputStream( self, fieldDescriptor, syntax, input, extensionRegistry); } } else { // fieldType == GPBFieldTypeMap // GPB*Dictionary or NSDictionary, exact type doesn't matter at this // point. id map = GetOrCreateMapIvarWithField(self, fieldDescriptor, syntax); [input readMapEntry:map extensionRegistry:extensionRegistry field:fieldDescriptor parentMessage:self]; } merged = YES; break; } else { startingIndex += 1; } } // for(i < numFields) if (!merged && (tag != 0)) { // Primitive, repeated types can be packed on unpacked on the wire, and // are parsed either way. The above loop covered tag in the preferred // for, so this need to check the alternate form. for (NSUInteger i = 0; i < numFields; ++i) { if (startingIndex >= numFields) startingIndex = 0; GPBFieldDescriptor *fieldDescriptor = fields[startingIndex]; if ((fieldDescriptor.fieldType == GPBFieldTypeRepeated) && !GPBFieldDataTypeIsObject(fieldDescriptor) && (GPBFieldAlternateTag(fieldDescriptor) == tag)) { BOOL alternateIsPacked = !fieldDescriptor.isPackable; if (alternateIsPacked) { MergeRepeatedPackedFieldFromCodedInputStream( self, fieldDescriptor, syntax, input); // Well formed protos will only have a repeated field that is // packed once, advance the starting index to the next field. startingIndex += 1; } else { MergeRepeatedNotPackedFieldFromCodedInputStream( self, fieldDescriptor, syntax, input, extensionRegistry); } merged = YES; break; } else { startingIndex += 1; } } } if (!merged) { if (tag == 0) { // zero signals EOF / limit reached return; } else { if (GPBPreserveUnknownFields(syntax)) { if (![self parseUnknownField:input extensionRegistry:extensionRegistry tag:tag]) { // it's an endgroup tag return; } } else { if (![input skipField:tag]) { return; } } } } // if(!merged) } // while(YES) } #pragma mark - MergeFrom Support - (void)mergeFrom:(GPBMessage *)other { Class selfClass = [self class]; Class otherClass = [other class]; if (!([selfClass isSubclassOfClass:otherClass] || [otherClass isSubclassOfClass:selfClass])) { [NSException raise:NSInvalidArgumentException format:@"Classes must match %@ != %@", selfClass, otherClass]; } // We assume something will be done and become visible. GPBBecomeVisibleToAutocreator(self); GPBDescriptor *descriptor = [[self class] descriptor]; GPBFileSyntax syntax = descriptor.file.syntax; for (GPBFieldDescriptor *field in descriptor->fields_) { GPBFieldType fieldType = field.fieldType; if (fieldType == GPBFieldTypeSingle) { int32_t hasIndex = GPBFieldHasIndex(field); uint32_t fieldNumber = GPBFieldNumber(field); if (!GPBGetHasIvar(other, hasIndex, fieldNumber)) { // Other doesn't have the field set, on to the next. continue; } GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { case GPBDataTypeBool: GPBSetBoolIvarWithFieldInternal( self, field, GPBGetMessageBoolField(other, field), syntax); break; case GPBDataTypeSFixed32: case GPBDataTypeEnum: case GPBDataTypeInt32: case GPBDataTypeSInt32: GPBSetInt32IvarWithFieldInternal( self, field, GPBGetMessageInt32Field(other, field), syntax); break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: GPBSetUInt32IvarWithFieldInternal( self, field, GPBGetMessageUInt32Field(other, field), syntax); break; case GPBDataTypeSFixed64: case GPBDataTypeInt64: case GPBDataTypeSInt64: GPBSetInt64IvarWithFieldInternal( self, field, GPBGetMessageInt64Field(other, field), syntax); break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: GPBSetUInt64IvarWithFieldInternal( self, field, GPBGetMessageUInt64Field(other, field), syntax); break; case GPBDataTypeFloat: GPBSetFloatIvarWithFieldInternal( self, field, GPBGetMessageFloatField(other, field), syntax); break; case GPBDataTypeDouble: GPBSetDoubleIvarWithFieldInternal( self, field, GPBGetMessageDoubleField(other, field), syntax); break; case GPBDataTypeBytes: case GPBDataTypeString: { id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field); GPBSetObjectIvarWithFieldInternal(self, field, otherVal, syntax); break; } case GPBDataTypeMessage: case GPBDataTypeGroup: { id otherVal = GPBGetObjectIvarWithFieldNoAutocreate(other, field); if (GPBGetHasIvar(self, hasIndex, fieldNumber)) { GPBMessage *message = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [message mergeFrom:otherVal]; } else { GPBMessage *message = [otherVal copy]; GPBSetRetainedObjectIvarWithFieldInternal(self, field, message, syntax); } break; } } // switch() } else if (fieldType == GPBFieldTypeRepeated) { // In the case of a list, they need to be appended, and there is no // _hasIvar to worry about setting. id otherArray = GPBGetObjectIvarWithFieldNoAutocreate(other, field); if (otherArray) { GPBDataType fieldDataType = field->description_->dataType; if (GPBDataTypeIsObject(fieldDataType)) { NSMutableArray *resultArray = GetOrCreateArrayIvarWithField(self, field, syntax); [resultArray addObjectsFromArray:otherArray]; } else if (fieldDataType == GPBDataTypeEnum) { GPBEnumArray *resultArray = GetOrCreateArrayIvarWithField(self, field, syntax); [resultArray addRawValuesFromArray:otherArray]; } else { // The array type doesn't matter, that all implment // -addValuesFromArray:. GPBInt32Array *resultArray = GetOrCreateArrayIvarWithField(self, field, syntax); [resultArray addValuesFromArray:otherArray]; } } } else { // fieldType = GPBFieldTypeMap // In the case of a map, they need to be merged, and there is no // _hasIvar to worry about setting. id otherDict = GPBGetObjectIvarWithFieldNoAutocreate(other, field); if (otherDict) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = field->description_->dataType; if (GPBDataTypeIsObject(keyDataType) && GPBDataTypeIsObject(valueDataType)) { NSMutableDictionary *resultDict = GetOrCreateMapIvarWithField(self, field, syntax); [resultDict addEntriesFromDictionary:otherDict]; } else if (valueDataType == GPBDataTypeEnum) { // The exact type doesn't matter, just need to know it is a // GPB*EnumDictionary. GPBInt32EnumDictionary *resultDict = GetOrCreateMapIvarWithField(self, field, syntax); [resultDict addRawEntriesFromDictionary:otherDict]; } else { // The exact type doesn't matter, they all implement // -addEntriesFromDictionary:. GPBInt32Int32Dictionary *resultDict = GetOrCreateMapIvarWithField(self, field, syntax); [resultDict addEntriesFromDictionary:otherDict]; } } } // if (fieldType)..else if...else } // for(fields) // Unknown fields. if (!unknownFields_) { [self setUnknownFields:other.unknownFields]; } else { [unknownFields_ mergeUnknownFields:other.unknownFields]; } // Extensions if (other->extensionMap_.count == 0) { return; } if (extensionMap_ == nil) { extensionMap_ = CloneExtensionMap(other->extensionMap_, NSZoneFromPointer(self)); } else { for (GPBExtensionDescriptor *extension in other->extensionMap_) { id otherValue = [other->extensionMap_ objectForKey:extension]; id value = [extensionMap_ objectForKey:extension]; BOOL isMessageExtension = GPBExtensionIsMessage(extension); if (extension.repeated) { NSMutableArray *list = value; if (list == nil) { list = [[NSMutableArray alloc] init]; [extensionMap_ setObject:list forKey:extension]; [list release]; } if (isMessageExtension) { for (GPBMessage *otherListValue in otherValue) { GPBMessage *copiedValue = [otherListValue copy]; [list addObject:copiedValue]; [copiedValue release]; } } else { [list addObjectsFromArray:otherValue]; } } else { if (isMessageExtension) { if (value) { [(GPBMessage *)value mergeFrom:(GPBMessage *)otherValue]; } else { GPBMessage *copiedValue = [otherValue copy]; [extensionMap_ setObject:copiedValue forKey:extension]; [copiedValue release]; } } else { [extensionMap_ setObject:otherValue forKey:extension]; } } if (isMessageExtension && !extension.isRepeated) { GPBMessage *autocreatedValue = [[autocreatedExtensionMap_ objectForKey:extension] retain]; // Must remove from the map before calling GPBClearMessageAutocreator() // so that GPBClearMessageAutocreator() knows its safe to clear. [autocreatedExtensionMap_ removeObjectForKey:extension]; GPBClearMessageAutocreator(autocreatedValue); [autocreatedValue release]; } } } } #pragma mark - isEqual: & hash Support - (BOOL)isEqual:(id)other { if (other == self) { return YES; } if (![other isKindOfClass:[self class]] && ![self isKindOfClass:[other class]]) { return NO; } GPBMessage *otherMsg = other; GPBDescriptor *descriptor = [[self class] descriptor]; uint8_t *selfStorage = (uint8_t *)messageStorage_; uint8_t *otherStorage = (uint8_t *)otherMsg->messageStorage_; for (GPBFieldDescriptor *field in descriptor->fields_) { if (GPBFieldIsMapOrArray(field)) { // In the case of a list or map, there is no _hasIvar to worry about. // NOTE: These are NSArray/GPB*Array or NSDictionary/GPB*Dictionary, but // the type doesn't really matter as the objects all support -count and // -isEqual:. NSArray *resultMapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field); NSArray *otherMapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(other, field); // nil and empty are equal if (resultMapOrArray.count != 0 || otherMapOrArray.count != 0) { if (![resultMapOrArray isEqual:otherMapOrArray]) { return NO; } } } else { // Single field int32_t hasIndex = GPBFieldHasIndex(field); uint32_t fieldNum = GPBFieldNumber(field); BOOL selfHas = GPBGetHasIvar(self, hasIndex, fieldNum); BOOL otherHas = GPBGetHasIvar(other, hasIndex, fieldNum); if (selfHas != otherHas) { return NO; // Differing has values, not equal. } if (!selfHas) { // Same has values, was no, nothing else to check for this field. continue; } // Now compare the values. GPBDataType fieldDataType = GPBGetFieldDataType(field); size_t fieldOffset = field->description_->offset; switch (fieldDataType) { case GPBDataTypeBool: { // Bools are stored in has_bits to avoid needing explicit space in // the storage structure. // (the field number passed to the HasIvar helper doesn't really // matter since the offset is never negative) BOOL selfValue = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0); BOOL otherValue = GPBGetHasIvar(other, (int32_t)(fieldOffset), 0); if (selfValue != otherValue) { return NO; } break; } case GPBDataTypeSFixed32: case GPBDataTypeInt32: case GPBDataTypeSInt32: case GPBDataTypeEnum: case GPBDataTypeFixed32: case GPBDataTypeUInt32: case GPBDataTypeFloat: { GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits); // These are all 32bit, signed/unsigned doesn't matter for equality. uint32_t *selfValPtr = (uint32_t *)&selfStorage[fieldOffset]; uint32_t *otherValPtr = (uint32_t *)&otherStorage[fieldOffset]; if (*selfValPtr != *otherValPtr) { return NO; } break; } case GPBDataTypeSFixed64: case GPBDataTypeInt64: case GPBDataTypeSInt64: case GPBDataTypeFixed64: case GPBDataTypeUInt64: case GPBDataTypeDouble: { GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits); // These are all 64bit, signed/unsigned doesn't matter for equality. uint64_t *selfValPtr = (uint64_t *)&selfStorage[fieldOffset]; uint64_t *otherValPtr = (uint64_t *)&otherStorage[fieldOffset]; if (*selfValPtr != *otherValPtr) { return NO; } break; } case GPBDataTypeBytes: case GPBDataTypeString: case GPBDataTypeMessage: case GPBDataTypeGroup: { // Type doesn't matter here, they all implement -isEqual:. id *selfValPtr = (id *)&selfStorage[fieldOffset]; id *otherValPtr = (id *)&otherStorage[fieldOffset]; if (![*selfValPtr isEqual:*otherValPtr]) { return NO; } break; } } // switch() } // if(mapOrArray)...else } // for(fields) // nil and empty are equal if (extensionMap_.count != 0 || otherMsg->extensionMap_.count != 0) { if (![extensionMap_ isEqual:otherMsg->extensionMap_]) { return NO; } } // nil and empty are equal GPBUnknownFieldSet *otherUnknowns = otherMsg->unknownFields_; if ([unknownFields_ countOfFields] != 0 || [otherUnknowns countOfFields] != 0) { if (![unknownFields_ isEqual:otherUnknowns]) { return NO; } } return YES; } // It is very difficult to implement a generic hash for ProtoBuf messages that // will perform well. If you need hashing on your ProtoBufs (eg you are using // them as dictionary keys) you will probably want to implement a ProtoBuf // message specific hash as a category on your protobuf class. Do not make it a // category on GPBMessage as you will conflict with this hash, and will possibly // override hash for all generated protobufs. A good implementation of hash will // be really fast, so we would recommend only hashing protobufs that have an // identifier field of some kind that you can easily hash. If you implement // hash, we would strongly recommend overriding isEqual: in your category as // well, as the default implementation of isEqual: is extremely slow, and may // drastically affect performance in large sets. - (NSUInteger)hash { GPBDescriptor *descriptor = [[self class] descriptor]; const NSUInteger prime = 19; uint8_t *storage = (uint8_t *)messageStorage_; // Start with the descriptor and then mix it with some instance info. // Hopefully that will give a spread based on classes and what fields are set. NSUInteger result = (NSUInteger)descriptor; for (GPBFieldDescriptor *field in descriptor->fields_) { if (GPBFieldIsMapOrArray(field)) { // Exact type doesn't matter, just check if there are any elements. NSArray *mapOrArray = GPBGetObjectIvarWithFieldNoAutocreate(self, field); NSUInteger count = mapOrArray.count; if (count) { // NSArray/NSDictionary use count, use the field number and the count. result = prime * result + GPBFieldNumber(field); result = prime * result + count; } } else if (GPBGetHasIvarField(self, field)) { // Just using the field number seemed simple/fast, but then a small // message class where all the same fields are always set (to different // things would end up all with the same hash, so pull in some data). GPBDataType fieldDataType = GPBGetFieldDataType(field); size_t fieldOffset = field->description_->offset; switch (fieldDataType) { case GPBDataTypeBool: { // Bools are stored in has_bits to avoid needing explicit space in // the storage structure. // (the field number passed to the HasIvar helper doesn't really // matter since the offset is never negative) BOOL value = GPBGetHasIvar(self, (int32_t)(fieldOffset), 0); result = prime * result + value; break; } case GPBDataTypeSFixed32: case GPBDataTypeInt32: case GPBDataTypeSInt32: case GPBDataTypeEnum: case GPBDataTypeFixed32: case GPBDataTypeUInt32: case GPBDataTypeFloat: { GPBInternalCompileAssert(sizeof(float) == sizeof(uint32_t), float_not_32_bits); // These are all 32bit, just mix it in. uint32_t *valPtr = (uint32_t *)&storage[fieldOffset]; result = prime * result + *valPtr; break; } case GPBDataTypeSFixed64: case GPBDataTypeInt64: case GPBDataTypeSInt64: case GPBDataTypeFixed64: case GPBDataTypeUInt64: case GPBDataTypeDouble: { GPBInternalCompileAssert(sizeof(double) == sizeof(uint64_t), double_not_64_bits); // These are all 64bit, just mix what fits into an NSUInteger in. uint64_t *valPtr = (uint64_t *)&storage[fieldOffset]; result = prime * result + (NSUInteger)(*valPtr); break; } case GPBDataTypeBytes: case GPBDataTypeString: { // Type doesn't matter here, they both implement -hash:. id *valPtr = (id *)&storage[fieldOffset]; result = prime * result + [*valPtr hash]; break; } case GPBDataTypeMessage: case GPBDataTypeGroup: { GPBMessage **valPtr = (GPBMessage **)&storage[fieldOffset]; // Could call -hash on the sub message, but that could recurse pretty // deep; follow the lead of NSArray/NSDictionary and don't really // recurse for hash, instead use the field number and the descriptor // of the sub message. Yes, this could suck for a bunch of messages // where they all only differ in the sub messages, but if you are // using a message with sub messages for something that needs -hash, // odds are you are also copying them as keys, and that deep copy // will also suck. result = prime * result + GPBFieldNumber(field); result = prime * result + (NSUInteger)[[*valPtr class] descriptor]; break; } } // switch() } } // Unknowns and extensions are not included. return result; } #pragma mark - Description Support - (NSString *)description { NSString *textFormat = GPBTextFormatForMessage(self, @" "); NSString *description = [NSString stringWithFormat:@"<%@ %p>: {\n%@}", [self class], self, textFormat]; return description; } #if defined(DEBUG) && DEBUG // Xcode 5.1 added support for custom quick look info. // https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/CustomClassDisplay_in_QuickLook/CH01-quick_look_for_custom_objects/CH01-quick_look_for_custom_objects.html#//apple_ref/doc/uid/TP40014001-CH2-SW1 - (id)debugQuickLookObject { return GPBTextFormatForMessage(self, nil); } #endif // DEBUG #pragma mark - SerializedSize - (size_t)serializedSize { GPBDescriptor *descriptor = [[self class] descriptor]; size_t result = 0; // Has check is done explicitly, so GPBGetObjectIvarWithFieldNoAutocreate() // avoids doing the has check again. // Fields. for (GPBFieldDescriptor *fieldDescriptor in descriptor->fields_) { GPBFieldType fieldType = fieldDescriptor.fieldType; GPBDataType fieldDataType = GPBGetFieldDataType(fieldDescriptor); // Single Fields if (fieldType == GPBFieldTypeSingle) { BOOL selfHas = GPBGetHasIvarField(self, fieldDescriptor); if (!selfHas) { continue; // Nothing to do. } uint32_t fieldNumber = GPBFieldNumber(fieldDescriptor); switch (fieldDataType) { #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \ case GPBDataType##NAME: { \ TYPE fieldVal = GPBGetMessage##FUNC_TYPE##Field(self, fieldDescriptor); \ result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \ break; \ } #define CASE_SINGLE_OBJECT(NAME) \ case GPBDataType##NAME: { \ id fieldVal = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); \ result += GPBCompute##NAME##Size(fieldNumber, fieldVal); \ break; \ } CASE_SINGLE_POD(Bool, BOOL, Bool) CASE_SINGLE_POD(Fixed32, uint32_t, UInt32) CASE_SINGLE_POD(SFixed32, int32_t, Int32) CASE_SINGLE_POD(Float, float, Float) CASE_SINGLE_POD(Fixed64, uint64_t, UInt64) CASE_SINGLE_POD(SFixed64, int64_t, Int64) CASE_SINGLE_POD(Double, double, Double) CASE_SINGLE_POD(Int32, int32_t, Int32) CASE_SINGLE_POD(Int64, int64_t, Int64) CASE_SINGLE_POD(SInt32, int32_t, Int32) CASE_SINGLE_POD(SInt64, int64_t, Int64) CASE_SINGLE_POD(UInt32, uint32_t, UInt32) CASE_SINGLE_POD(UInt64, uint64_t, UInt64) CASE_SINGLE_OBJECT(Bytes) CASE_SINGLE_OBJECT(String) CASE_SINGLE_OBJECT(Message) CASE_SINGLE_OBJECT(Group) CASE_SINGLE_POD(Enum, int32_t, Int32) #undef CASE_SINGLE_POD #undef CASE_SINGLE_OBJECT } // Repeated Fields } else if (fieldType == GPBFieldTypeRepeated) { id genericArray = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); NSUInteger count = [genericArray count]; if (count == 0) { continue; // Nothing to add. } __block size_t dataSize = 0; switch (fieldDataType) { #define CASE_REPEATED_POD(NAME, TYPE, ARRAY_TYPE) \ CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ) #define CASE_REPEATED_POD_EXTRA(NAME, TYPE, ARRAY_TYPE, ARRAY_ACCESSOR_NAME) \ case GPBDataType##NAME: { \ GPB##ARRAY_TYPE##Array *array = genericArray; \ [array enumerate##ARRAY_ACCESSOR_NAME##ValuesWithBlock:^(TYPE value, NSUInteger idx, BOOL *stop) { \ _Pragma("unused(idx, stop)"); \ dataSize += GPBCompute##NAME##SizeNoTag(value); \ }]; \ break; \ } #define CASE_REPEATED_OBJECT(NAME) \ case GPBDataType##NAME: { \ for (id value in genericArray) { \ dataSize += GPBCompute##NAME##SizeNoTag(value); \ } \ break; \ } CASE_REPEATED_POD(Bool, BOOL, Bool) CASE_REPEATED_POD(Fixed32, uint32_t, UInt32) CASE_REPEATED_POD(SFixed32, int32_t, Int32) CASE_REPEATED_POD(Float, float, Float) CASE_REPEATED_POD(Fixed64, uint64_t, UInt64) CASE_REPEATED_POD(SFixed64, int64_t, Int64) CASE_REPEATED_POD(Double, double, Double) CASE_REPEATED_POD(Int32, int32_t, Int32) CASE_REPEATED_POD(Int64, int64_t, Int64) CASE_REPEATED_POD(SInt32, int32_t, Int32) CASE_REPEATED_POD(SInt64, int64_t, Int64) CASE_REPEATED_POD(UInt32, uint32_t, UInt32) CASE_REPEATED_POD(UInt64, uint64_t, UInt64) CASE_REPEATED_OBJECT(Bytes) CASE_REPEATED_OBJECT(String) CASE_REPEATED_OBJECT(Message) CASE_REPEATED_OBJECT(Group) CASE_REPEATED_POD_EXTRA(Enum, int32_t, Enum, Raw) #undef CASE_REPEATED_POD #undef CASE_REPEATED_POD_EXTRA #undef CASE_REPEATED_OBJECT } // switch result += dataSize; size_t tagSize = GPBComputeTagSize(GPBFieldNumber(fieldDescriptor)); if (fieldDataType == GPBDataTypeGroup) { // Groups have both a start and an end tag. tagSize *= 2; } if (fieldDescriptor.isPackable) { result += tagSize; result += GPBComputeSizeTSizeAsInt32NoTag(dataSize); } else { result += count * tagSize; } // Map<> Fields } else { // fieldType == GPBFieldTypeMap if (GPBDataTypeIsObject(fieldDataType) && (fieldDescriptor.mapKeyDataType == GPBDataTypeString)) { // If key type was string, then the map is an NSDictionary. NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); if (map) { result += GPBDictionaryComputeSizeInternalHelper(map, fieldDescriptor); } } else { // Type will be GPB*GroupDictionary, exact type doesn't matter. GPBInt32Int32Dictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, fieldDescriptor); result += [map computeSerializedSizeAsField:fieldDescriptor]; } } } // for(fields) // Add any unknown fields. if (descriptor.wireFormat) { result += [unknownFields_ serializedSizeAsMessageSet]; } else { result += [unknownFields_ serializedSize]; } // Add any extensions. for (GPBExtensionDescriptor *extension in extensionMap_) { id value = [extensionMap_ objectForKey:extension]; result += GPBComputeExtensionSerializedSizeIncludingTag(extension, value); } return result; } #pragma mark - Resolve Methods Support typedef struct ResolveIvarAccessorMethodResult { IMP impToAdd; SEL encodingSelector; } ResolveIvarAccessorMethodResult; static void ResolveIvarGet(GPBFieldDescriptor *field, ResolveIvarAccessorMethodResult *result) { GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { #define CASE_GET(NAME, TYPE, TRUE_NAME) \ case GPBDataType##NAME: { \ result->impToAdd = imp_implementationWithBlock(^(id obj) { \ return GPBGetMessage##TRUE_NAME##Field(obj, field); \ }); \ result->encodingSelector = @selector(get##NAME); \ break; \ } #define CASE_GET_OBJECT(NAME, TYPE, TRUE_NAME) \ case GPBDataType##NAME: { \ result->impToAdd = imp_implementationWithBlock(^(id obj) { \ return GPBGetObjectIvarWithField(obj, field); \ }); \ result->encodingSelector = @selector(get##NAME); \ break; \ } CASE_GET(Bool, BOOL, Bool) CASE_GET(Fixed32, uint32_t, UInt32) CASE_GET(SFixed32, int32_t, Int32) CASE_GET(Float, float, Float) CASE_GET(Fixed64, uint64_t, UInt64) CASE_GET(SFixed64, int64_t, Int64) CASE_GET(Double, double, Double) CASE_GET(Int32, int32_t, Int32) CASE_GET(Int64, int64_t, Int64) CASE_GET(SInt32, int32_t, Int32) CASE_GET(SInt64, int64_t, Int64) CASE_GET(UInt32, uint32_t, UInt32) CASE_GET(UInt64, uint64_t, UInt64) CASE_GET_OBJECT(Bytes, id, Object) CASE_GET_OBJECT(String, id, Object) CASE_GET_OBJECT(Message, id, Object) CASE_GET_OBJECT(Group, id, Object) CASE_GET(Enum, int32_t, Enum) #undef CASE_GET } } static void ResolveIvarSet(GPBFieldDescriptor *field, GPBFileSyntax syntax, ResolveIvarAccessorMethodResult *result) { GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { #define CASE_SET(NAME, TYPE, TRUE_NAME) \ case GPBDataType##NAME: { \ result->impToAdd = imp_implementationWithBlock(^(id obj, TYPE value) { \ return GPBSet##TRUE_NAME##IvarWithFieldInternal(obj, field, value, syntax); \ }); \ result->encodingSelector = @selector(set##NAME:); \ break; \ } CASE_SET(Bool, BOOL, Bool) CASE_SET(Fixed32, uint32_t, UInt32) CASE_SET(SFixed32, int32_t, Int32) CASE_SET(Float, float, Float) CASE_SET(Fixed64, uint64_t, UInt64) CASE_SET(SFixed64, int64_t, Int64) CASE_SET(Double, double, Double) CASE_SET(Int32, int32_t, Int32) CASE_SET(Int64, int64_t, Int64) CASE_SET(SInt32, int32_t, Int32) CASE_SET(SInt64, int64_t, Int64) CASE_SET(UInt32, uint32_t, UInt32) CASE_SET(UInt64, uint64_t, UInt64) CASE_SET(Bytes, id, Object) CASE_SET(String, id, Object) CASE_SET(Message, id, Object) CASE_SET(Group, id, Object) CASE_SET(Enum, int32_t, Enum) #undef CASE_SET } } + (BOOL)resolveInstanceMethod:(SEL)sel { const GPBDescriptor *descriptor = [self descriptor]; if (!descriptor) { return NO; } // NOTE: hasOrCountSel_/setHasSel_ will be NULL if the field for the given // message should not have has support (done in GPBDescriptor.m), so there is // no need for checks here to see if has*/setHas* are allowed. ResolveIvarAccessorMethodResult result = {NULL, NULL}; for (GPBFieldDescriptor *field in descriptor->fields_) { BOOL isMapOrArray = GPBFieldIsMapOrArray(field); if (!isMapOrArray) { // Single fields. if (sel == field->getSel_) { ResolveIvarGet(field, &result); break; } else if (sel == field->setSel_) { ResolveIvarSet(field, descriptor.file.syntax, &result); break; } else if (sel == field->hasOrCountSel_) { int32_t index = GPBFieldHasIndex(field); uint32_t fieldNum = GPBFieldNumber(field); result.impToAdd = imp_implementationWithBlock(^(id obj) { return GPBGetHasIvar(obj, index, fieldNum); }); result.encodingSelector = @selector(getBool); break; } else if (sel == field->setHasSel_) { result.impToAdd = imp_implementationWithBlock(^(id obj, BOOL value) { if (value) { [NSException raise:NSInvalidArgumentException format:@"%@: %@ can only be set to NO (to clear field).", [obj class], NSStringFromSelector(field->setHasSel_)]; } GPBClearMessageField(obj, field); }); result.encodingSelector = @selector(setBool:); break; } else { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof && (sel == oneof->caseSel_)) { int32_t index = GPBFieldHasIndex(field); result.impToAdd = imp_implementationWithBlock(^(id obj) { return GPBGetHasOneof(obj, index); }); result.encodingSelector = @selector(getEnum); break; } } } else { // map<>/repeated fields. if (sel == field->getSel_) { if (field.fieldType == GPBFieldTypeRepeated) { result.impToAdd = imp_implementationWithBlock(^(id obj) { return GetArrayIvarWithField(obj, field); }); } else { result.impToAdd = imp_implementationWithBlock(^(id obj) { return GetMapIvarWithField(obj, field); }); } result.encodingSelector = @selector(getArray); break; } else if (sel == field->setSel_) { // Local for syntax so the block can directly capture it and not the // full lookup. const GPBFileSyntax syntax = descriptor.file.syntax; result.impToAdd = imp_implementationWithBlock(^(id obj, id value) { return GPBSetObjectIvarWithFieldInternal(obj, field, value, syntax); }); result.encodingSelector = @selector(setArray:); break; } else if (sel == field->hasOrCountSel_) { result.impToAdd = imp_implementationWithBlock(^(id obj) { // Type doesn't matter, all *Array and *Dictionary types support // -count. NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(obj, field); return [arrayOrMap count]; }); result.encodingSelector = @selector(getArrayCount); break; } } } if (result.impToAdd) { const char *encoding = GPBMessageEncodingForSelector(result.encodingSelector, YES); BOOL methodAdded = class_addMethod(descriptor.messageClass, sel, result.impToAdd, encoding); return methodAdded; } return [super resolveInstanceMethod:sel]; } + (BOOL)resolveClassMethod:(SEL)sel { // Extensions scoped to a Message and looked up via class methods. if (GPBResolveExtensionClassMethod(self, sel)) { return YES; } return [super resolveClassMethod:sel]; } #pragma mark - NSCoding Support + (BOOL)supportsSecureCoding { return YES; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [self init]; if (self) { NSData *data = [aDecoder decodeObjectOfClass:[NSData class] forKey:kGPBDataCoderKey]; if (data.length) { [self mergeFromData:data extensionRegistry:nil]; } } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { NSData *data = [self data]; if (data.length) { [aCoder encodeObject:data forKey:kGPBDataCoderKey]; } } #pragma mark - KVC Support + (BOOL)accessInstanceVariablesDirectly { // Make sure KVC doesn't use instance variables. return NO; } @end #pragma mark - Messages from GPBUtilities.h but defined here for access to helpers. // Only exists for public api, no core code should use this. id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field) { #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeRepeated) { [NSException raise:NSInvalidArgumentException format:@"%@.%@ is not a repeated field.", [self class], field.name]; } #endif GPBDescriptor *descriptor = [[self class] descriptor]; GPBFileSyntax syntax = descriptor.file.syntax; return GetOrCreateArrayIvarWithField(self, field, syntax); } // Only exists for public api, no core code should use this. id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field) { #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeMap) { [NSException raise:NSInvalidArgumentException format:@"%@.%@ is not a map<> field.", [self class], field.name]; } #endif GPBDescriptor *descriptor = [[self class] descriptor]; GPBFileSyntax syntax = descriptor.file.syntax; return GetOrCreateMapIvarWithField(self, field, syntax); } #pragma clang diagnostic pop ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBMessage_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This header is private to the ProtobolBuffers library and must NOT be // included by any sources outside this library. The contents of this file are // subject to change at any time without notice. #import "GPBMessage.h" #import #import "GPBBootstrap.h" typedef struct GPBMessage_Storage { uint32_t _has_storage_[0]; } GPBMessage_Storage; typedef struct GPBMessage_Storage *GPBMessage_StoragePtr; @interface GPBMessage () { @package // NOTE: Because of the +allocWithZone code using NSAllocateObject(), // this structure should ideally always be kept pointer aligned where the // real storage starts is also pointer aligned. The compiler/runtime already // do this, but it may not be documented. // A pointer to the actual fields of the subclasses. The actual structure // pointed to by this pointer will depend on the subclass. // All of the actual structures will start the same as // GPBMessage_Storage with _has_storage__ as the first field. // Kept public because static functions need to access it. GPBMessage_StoragePtr messageStorage_; // A lock to provide mutual exclusion from internal data that can be modified // by *read* operations such as getters (autocreation of message fields and // message extensions, not setting of values). Used to guarantee thread safety // for concurrent reads on the message. // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have // pointed out that they are vulnerable to live locking on iOS in cases of // priority inversion: // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/ // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html // Use of readOnlySemaphore_ must be prefaced by a call to // GPBPrepareReadOnlySemaphore to ensure it has been created. This allows // readOnlySemaphore_ to be only created when actually needed. dispatch_once_t readOnlySemaphoreCreationOnce_; dispatch_semaphore_t readOnlySemaphore_; } // Gets an extension value without autocreating the result if not found. (i.e. // returns nil if the extension is not set) - (id)getExistingExtension:(GPBExtensionDescriptor *)extension; // Parses a message of this type from the input and merges it with this // message. // // Warning: This does not verify that all required fields are present in // the input message. // Note: The caller should call // -[CodedInputStream checkLastTagWas:] after calling this to // verify that the last tag seen was the appropriate end-group tag, // or zero for EOF. // NOTE: This will throw if there is an error while parsing. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; // Parses the next delimited message of this type from the input and merges it // with this message. - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: (GPBExtensionRegistry *)extensionRegistry; - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; @end CF_EXTERN_C_BEGIN // Call this before using the readOnlySemaphore_. This ensures it is created only once. NS_INLINE void GPBPrepareReadOnlySemaphore(GPBMessage *self) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" dispatch_once(&self->readOnlySemaphoreCreationOnce_, ^{ self->readOnlySemaphore_ = dispatch_semaphore_create(1); }); #pragma clang diagnostic pop } // Returns a new instance that was automatically created by |autocreator| for // its field |field|. GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator, GPBFieldDescriptor *field) __attribute__((ns_returns_retained)); // Returns whether |message| autocreated this message. This is NO if the message // was not autocreated by |message| or if it has been mutated since // autocreation. BOOL GPBWasMessageAutocreatedBy(GPBMessage *message, GPBMessage *parent); // Call this when you mutate a message. It will cause the message to become // visible to its autocreator. void GPBBecomeVisibleToAutocreator(GPBMessage *self); // Call this when an array/dictionary is mutated so the parent message that // autocreated it can react. void GPBAutocreatedArrayModified(GPBMessage *self, id array); void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary); // Clear the autocreator, if any. Asserts if the autocreator still has an // autocreated reference to this message. void GPBClearMessageAutocreator(GPBMessage *self); CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBProtocolBuffers.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBBootstrap.h" #import "GPBArray.h" #import "GPBCodedInputStream.h" #import "GPBCodedOutputStream.h" #import "GPBDescriptor.h" #import "GPBDictionary.h" #import "GPBExtensionRegistry.h" #import "GPBMessage.h" #import "GPBRootObject.h" #import "GPBUnknownField.h" #import "GPBUnknownFieldSet.h" #import "GPBUtilities.h" #import "GPBWellKnownTypes.h" #import "GPBWireFormat.h" // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif // Well-known proto types #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #import #import #import #import #import #import #import #import #import #else #import "google/protobuf/Any.pbobjc.h" #import "google/protobuf/Api.pbobjc.h" #import "google/protobuf/Duration.pbobjc.h" #import "google/protobuf/Empty.pbobjc.h" #import "google/protobuf/FieldMask.pbobjc.h" #import "google/protobuf/SourceContext.pbobjc.h" #import "google/protobuf/Struct.pbobjc.h" #import "google/protobuf/Timestamp.pbobjc.h" #import "google/protobuf/Type.pbobjc.h" #import "google/protobuf/Wrappers.pbobjc.h" #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBProtocolBuffers_RuntimeSupport.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This header is meant to only be used by the generated source, it should not // be included in code using protocol buffers. #import "GPBProtocolBuffers.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBExtensionInternals.h" #import "GPBMessage_PackagePrivate.h" #import "GPBRootObject_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBRootObject.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import @class GPBExtensionRegistry; NS_ASSUME_NONNULL_BEGIN /** * Every generated proto file defines a local "Root" class that exposes a * GPBExtensionRegistry for all the extensions defined by that file and * the files it depends on. **/ @interface GPBRootObject : NSObject /** * @return An extension registry for the given file and all the files it depends * on. **/ + (GPBExtensionRegistry *)extensionRegistry; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBRootObject.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBRootObject_PackagePrivate.h" #import #import #import "GPBDescriptor.h" #import "GPBExtensionRegistry.h" #import "GPBUtilities_PackagePrivate.h" @interface GPBExtensionDescriptor (GPBRootObject) // Get singletonName as a c string. - (const char *)singletonNameC; @end @implementation GPBRootObject // Taken from http://www.burtleburtle.net/bob/hash/doobs.html // Public Domain static uint32_t jenkins_one_at_a_time_hash(const char *key) { uint32_t hash = 0; for (uint32_t i = 0; key[i] != '\0'; ++i) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } // Key methods for our custom CFDictionary. // Note that the dictionary lasts for the lifetime of our app, so no need // to worry about deallocation. All of the items are added to it at // startup, and so the keys don't need to be retained/released. // Keys are NULL terminated char *. static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, const void *value) { #pragma unused(allocator) return value; } static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, const void *value) { #pragma unused(allocator) #pragma unused(value) } static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) { const char *key = (const char *)value; return CFStringCreateWithCString(kCFAllocatorDefault, key, kCFStringEncodingUTF8); } static Boolean GPBRootExtensionKeyEqual(const void *value1, const void *value2) { const char *key1 = (const char *)value1; const char *key2 = (const char *)value2; return strcmp(key1, key2) == 0; } static CFHashCode GPBRootExtensionKeyHash(const void *value) { const char *key = (const char *)value; return jenkins_one_at_a_time_hash(key); } // NOTE: OSSpinLock may seem like a good fit here but Apple engineers have // pointed out that they are vulnerable to live locking on iOS in cases of // priority inversion: // http://mjtsai.com/blog/2015/12/16/osspinlock-is-unsafe/ // https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000372.html static dispatch_semaphore_t gExtensionSingletonDictionarySemaphore; static CFMutableDictionaryRef gExtensionSingletonDictionary = NULL; static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL; + (void)initialize { // Ensure the global is started up. if (!gExtensionSingletonDictionary) { gExtensionSingletonDictionarySemaphore = dispatch_semaphore_create(1); CFDictionaryKeyCallBacks keyCallBacks = { // See description above for reason for using custom dictionary. 0, GPBRootExtensionKeyRetain, GPBRootExtensionKeyRelease, GPBRootExtensionCopyKeyDescription, GPBRootExtensionKeyEqual, GPBRootExtensionKeyHash, }; gExtensionSingletonDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks, &kCFTypeDictionaryValueCallBacks); gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init]; } if ([self superclass] == [GPBRootObject class]) { // This is here to start up all the per file "Root" subclasses. // This must be done in initialize to enforce thread safety of start up of // the protocol buffer library. [self extensionRegistry]; } } + (GPBExtensionRegistry *)extensionRegistry { // Is overridden in all the subclasses that provide extensions to provide the // per class one. return gDefaultExtensionRegistry; } + (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field { const char *key = [field singletonNameC]; dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER); CFDictionarySetValue(gExtensionSingletonDictionary, key, field); dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); } static id ExtensionForName(id self, SEL _cmd) { // Really fast way of doing "classname_selName". // This came up as a hotspot (creation of NSString *) when accessing a // lot of extensions. const char *selName = sel_getName(_cmd); if (selName[0] == '_') { return nil; // Apple internal selector. } size_t selNameLen = 0; while (1) { char c = selName[selNameLen]; if (c == '\0') { // String end. break; } if (c == ':') { return nil; // Selector took an arg, not one of the runtime methods. } ++selNameLen; } const char *className = class_getName(self); size_t classNameLen = strlen(className); char key[classNameLen + selNameLen + 2]; memcpy(key, className, classNameLen); key[classNameLen] = '_'; memcpy(&key[classNameLen + 1], selName, selNameLen); key[classNameLen + 1 + selNameLen] = '\0'; // NOTE: Even though this method is called from another C function, // gExtensionSingletonDictionarySemaphore and gExtensionSingletonDictionary // will always be initialized. This is because this call flow is just to // lookup the Extension, meaning the code is calling an Extension class // message on a Message or Root class. This guarantees that the class was // initialized and Message classes ensure their Root was also initialized. NSAssert(gExtensionSingletonDictionary, @"Startup order broken!"); dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER); id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key); if (extension) { // The method is getting wired in to the class, so no need to keep it in // the dictionary. CFDictionaryRemoveValue(gExtensionSingletonDictionary, key); } dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); return extension; } BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) { // Another option would be to register the extensions with the class at // globallyRegisterExtension: // Timing the two solutions, this solution turned out to be much faster // and reduced startup time, and runtime memory. // The advantage to globallyRegisterExtension is that it would reduce the // size of the protos somewhat because the singletonNameC wouldn't need // to include the class name. For a class with a lot of extensions it // can add up. You could also significantly reduce the code complexity of this // file. id extension = ExtensionForName(self, sel); if (extension != nil) { const char *encoding = GPBMessageEncodingForSelector(@selector(getClassValue), NO); Class metaClass = objc_getMetaClass(class_getName(self)); IMP imp = imp_implementationWithBlock(^(id obj) { #pragma unused(obj) return extension; }); if (class_addMethod(metaClass, sel, imp, encoding)) { return YES; } } return NO; } + (BOOL)resolveClassMethod:(SEL)sel { if (GPBResolveExtensionClassMethod(self, sel)) { return YES; } return [super resolveClassMethod:sel]; } @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBRootObject_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBRootObject.h" @class GPBExtensionDescriptor; @interface GPBRootObject () // Globally register. + (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field; @end // Returns YES if the selector was resolved and added to the class, // NO otherwise. BOOL GPBResolveExtensionClassMethod(Class self, SEL sel); ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBRuntimeTypes.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBBootstrap.h" @class GPBEnumDescriptor; @class GPBMessage; @class GPBInt32Array; /** * Verifies that a given value can be represented by an enum type. * */ typedef BOOL (*GPBEnumValidationFunc)(int32_t); /** * Fetches an EnumDescriptor. * */ typedef GPBEnumDescriptor *(*GPBEnumDescriptorFunc)(void); /** * Magic value used at runtime to indicate an enum value that wasn't know at * compile time. * */ enum { kGPBUnrecognizedEnumeratorValue = (int32_t)0xFBADBEEF, }; /** * A union for storing all possible Protobuf values. Note that owner is * responsible for memory management of object types. * */ typedef union { BOOL valueBool; int32_t valueInt32; int64_t valueInt64; uint32_t valueUInt32; uint64_t valueUInt64; float valueFloat; double valueDouble; GPB_UNSAFE_UNRETAINED NSData *valueData; GPB_UNSAFE_UNRETAINED NSString *valueString; GPB_UNSAFE_UNRETAINED GPBMessage *valueMessage; int32_t valueEnum; } GPBGenericValue; /** * Enum listing the possible data types that a field can contain. * * @note Do not change the order of this enum (or add things to it) without * thinking about it very carefully. There are several things that depend * on the order. * */ typedef NS_ENUM(uint8_t, GPBDataType) { /** Field contains boolean value(s). */ GPBDataTypeBool = 0, /** Field contains unsigned 4 byte value(s). */ GPBDataTypeFixed32, /** Field contains signed 4 byte value(s). */ GPBDataTypeSFixed32, /** Field contains float value(s). */ GPBDataTypeFloat, /** Field contains unsigned 8 byte value(s). */ GPBDataTypeFixed64, /** Field contains signed 8 byte value(s). */ GPBDataTypeSFixed64, /** Field contains double value(s). */ GPBDataTypeDouble, /** * Field contains variable length value(s). Inefficient for encoding negative * numbers – if your field is likely to have negative values, use * GPBDataTypeSInt32 instead. **/ GPBDataTypeInt32, /** * Field contains variable length value(s). Inefficient for encoding negative * numbers – if your field is likely to have negative values, use * GPBDataTypeSInt64 instead. **/ GPBDataTypeInt64, /** Field contains signed variable length integer value(s). */ GPBDataTypeSInt32, /** Field contains signed variable length integer value(s). */ GPBDataTypeSInt64, /** Field contains unsigned variable length integer value(s). */ GPBDataTypeUInt32, /** Field contains unsigned variable length integer value(s). */ GPBDataTypeUInt64, /** Field contains an arbitrary sequence of bytes. */ GPBDataTypeBytes, /** Field contains UTF-8 encoded or 7-bit ASCII text. */ GPBDataTypeString, /** Field contains message type(s). */ GPBDataTypeMessage, /** Field contains message type(s). */ GPBDataTypeGroup, /** Field contains enum value(s). */ GPBDataTypeEnum, }; enum { /** * A count of the number of types in GPBDataType. Separated out from the * GPBDataType enum to avoid warnings regarding not handling GPBDataType_Count * in switch statements. **/ GPBDataType_Count = GPBDataTypeEnum + 1 }; /** An extension range. */ typedef struct GPBExtensionRange { /** Inclusive. */ uint32_t start; /** Exclusive. */ uint32_t end; } GPBExtensionRange; ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownField.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import @class GPBCodedOutputStream; @class GPBUInt32Array; @class GPBUInt64Array; @class GPBUnknownFieldSet; NS_ASSUME_NONNULL_BEGIN /** * Store an unknown field. These are used in conjunction with * GPBUnknownFieldSet. **/ @interface GPBUnknownField : NSObject /** The field number the data is stored under. */ @property(nonatomic, readonly, assign) int32_t number; /** An array of varint values for this field. */ @property(nonatomic, readonly, strong) GPBUInt64Array *varintList; /** An array of fixed32 values for this field. */ @property(nonatomic, readonly, strong) GPBUInt32Array *fixed32List; /** An array of fixed64 values for this field. */ @property(nonatomic, readonly, strong) GPBUInt64Array *fixed64List; /** An array of data values for this field. */ @property(nonatomic, readonly, strong) NSArray *lengthDelimitedList; /** An array of groups of values for this field. */ @property(nonatomic, readonly, strong) NSArray *groupList; /** * Add a value to the varintList. * * @param value The value to add. **/ - (void)addVarint:(uint64_t)value; /** * Add a value to the fixed32List. * * @param value The value to add. **/ - (void)addFixed32:(uint32_t)value; /** * Add a value to the fixed64List. * * @param value The value to add. **/ - (void)addFixed64:(uint64_t)value; /** * Add a value to the lengthDelimitedList. * * @param value The value to add. **/ - (void)addLengthDelimited:(NSData *)value; /** * Add a value to the groupList. * * @param value The value to add. **/ - (void)addGroup:(GPBUnknownFieldSet *)value; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownField.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBUnknownField_PackagePrivate.h" #import "GPBArray.h" #import "GPBCodedOutputStream_PackagePrivate.h" @implementation GPBUnknownField { @protected int32_t number_; GPBUInt64Array *mutableVarintList_; GPBUInt32Array *mutableFixed32List_; GPBUInt64Array *mutableFixed64List_; NSMutableArray *mutableLengthDelimitedList_; NSMutableArray *mutableGroupList_; } @synthesize number = number_; @synthesize varintList = mutableVarintList_; @synthesize fixed32List = mutableFixed32List_; @synthesize fixed64List = mutableFixed64List_; @synthesize lengthDelimitedList = mutableLengthDelimitedList_; @synthesize groupList = mutableGroupList_; - (instancetype)initWithNumber:(int32_t)number { if ((self = [super init])) { number_ = number; } return self; } - (void)dealloc { [mutableVarintList_ release]; [mutableFixed32List_ release]; [mutableFixed64List_ release]; [mutableLengthDelimitedList_ release]; [mutableGroupList_ release]; [super dealloc]; } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (id)copyWithZone:(NSZone *)zone { GPBUnknownField *result = [[GPBUnknownField allocWithZone:zone] initWithNumber:number_]; result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone]; result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone]; result->mutableLengthDelimitedList_ = [mutableLengthDelimitedList_ copyWithZone:zone]; result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone]; if (mutableGroupList_.count) { result->mutableGroupList_ = [[NSMutableArray allocWithZone:zone] initWithCapacity:mutableGroupList_.count]; for (GPBUnknownFieldSet *group in mutableGroupList_) { GPBUnknownFieldSet *copied = [group copyWithZone:zone]; [result->mutableGroupList_ addObject:copied]; [copied release]; } } return result; } - (BOOL)isEqual:(id)object { if (self == object) return YES; if (![object isKindOfClass:[GPBUnknownField class]]) return NO; GPBUnknownField *field = (GPBUnknownField *)object; BOOL equalVarint = (mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) || [mutableVarintList_ isEqual:field->mutableVarintList_]; if (!equalVarint) return NO; BOOL equalFixed32 = (mutableFixed32List_.count == 0 && field->mutableFixed32List_.count == 0) || [mutableFixed32List_ isEqual:field->mutableFixed32List_]; if (!equalFixed32) return NO; BOOL equalFixed64 = (mutableFixed64List_.count == 0 && field->mutableFixed64List_.count == 0) || [mutableFixed64List_ isEqual:field->mutableFixed64List_]; if (!equalFixed64) return NO; BOOL equalLDList = (mutableLengthDelimitedList_.count == 0 && field->mutableLengthDelimitedList_.count == 0) || [mutableLengthDelimitedList_ isEqual:field->mutableLengthDelimitedList_]; if (!equalLDList) return NO; BOOL equalGroupList = (mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) || [mutableGroupList_ isEqual:field->mutableGroupList_]; if (!equalGroupList) return NO; return YES; } - (NSUInteger)hash { // Just mix the hashes of the possible sub arrays. const int prime = 31; NSUInteger result = prime + [mutableVarintList_ hash]; result = prime * result + [mutableFixed32List_ hash]; result = prime * result + [mutableFixed64List_ hash]; result = prime * result + [mutableLengthDelimitedList_ hash]; result = prime * result + [mutableGroupList_ hash]; return result; } - (void)writeToOutput:(GPBCodedOutputStream *)output { NSUInteger count = mutableVarintList_.count; if (count > 0) { [output writeUInt64Array:number_ values:mutableVarintList_ tag:0]; } count = mutableFixed32List_.count; if (count > 0) { [output writeFixed32Array:number_ values:mutableFixed32List_ tag:0]; } count = mutableFixed64List_.count; if (count > 0) { [output writeFixed64Array:number_ values:mutableFixed64List_ tag:0]; } count = mutableLengthDelimitedList_.count; if (count > 0) { [output writeBytesArray:number_ values:mutableLengthDelimitedList_]; } count = mutableGroupList_.count; if (count > 0) { [output writeUnknownGroupArray:number_ values:mutableGroupList_]; } } - (size_t)serializedSize { __block size_t result = 0; int32_t number = number_; [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) result += GPBComputeUInt64Size(number, value); }]; [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) result += GPBComputeFixed32Size(number, value); }]; [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) result += GPBComputeFixed64Size(number, value); }]; for (NSData *data in mutableLengthDelimitedList_) { result += GPBComputeBytesSize(number, data); } for (GPBUnknownFieldSet *set in mutableGroupList_) { result += GPBComputeUnknownGroupSize(number, set); } return result; } - (void)writeAsMessageSetExtensionToOutput:(GPBCodedOutputStream *)output { for (NSData *data in mutableLengthDelimitedList_) { [output writeRawMessageSetExtension:number_ value:data]; } } - (size_t)serializedSizeAsMessageSetExtension { size_t result = 0; for (NSData *data in mutableLengthDelimitedList_) { result += GPBComputeRawMessageSetExtensionSize(number_, data); } return result; } - (NSString *)description { NSMutableString *description = [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", [self class], self, number_]; [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [description appendFormat:@"\t%llu\n", value]; }]; [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [description appendFormat:@"\t%u\n", value]; }]; [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) [description appendFormat:@"\t%llu\n", value]; }]; for (NSData *data in mutableLengthDelimitedList_) { [description appendFormat:@"\t%@\n", data]; } for (GPBUnknownFieldSet *set in mutableGroupList_) { [description appendFormat:@"\t%@\n", set]; } [description appendString:@"}"]; return description; } - (void)mergeFromField:(GPBUnknownField *)other { GPBUInt64Array *otherVarintList = other.varintList; if (otherVarintList.count > 0) { if (mutableVarintList_ == nil) { mutableVarintList_ = [otherVarintList copy]; } else { [mutableVarintList_ addValuesFromArray:otherVarintList]; } } GPBUInt32Array *otherFixed32List = other.fixed32List; if (otherFixed32List.count > 0) { if (mutableFixed32List_ == nil) { mutableFixed32List_ = [otherFixed32List copy]; } else { [mutableFixed32List_ addValuesFromArray:otherFixed32List]; } } GPBUInt64Array *otherFixed64List = other.fixed64List; if (otherFixed64List.count > 0) { if (mutableFixed64List_ == nil) { mutableFixed64List_ = [otherFixed64List copy]; } else { [mutableFixed64List_ addValuesFromArray:otherFixed64List]; } } NSArray *otherLengthDelimitedList = other.lengthDelimitedList; if (otherLengthDelimitedList.count > 0) { if (mutableLengthDelimitedList_ == nil) { mutableLengthDelimitedList_ = [otherLengthDelimitedList mutableCopy]; } else { [mutableLengthDelimitedList_ addObjectsFromArray:otherLengthDelimitedList]; } } NSArray *otherGroupList = other.groupList; if (otherGroupList.count > 0) { if (mutableGroupList_ == nil) { mutableGroupList_ = [[NSMutableArray alloc] initWithCapacity:otherGroupList.count]; } // Make our own mutable copies. for (GPBUnknownFieldSet *group in otherGroupList) { GPBUnknownFieldSet *copied = [group copy]; [mutableGroupList_ addObject:copied]; [copied release]; } } } - (void)addVarint:(uint64_t)value { if (mutableVarintList_ == nil) { mutableVarintList_ = [[GPBUInt64Array alloc] initWithValues:&value count:1]; } else { [mutableVarintList_ addValue:value]; } } - (void)addFixed32:(uint32_t)value { if (mutableFixed32List_ == nil) { mutableFixed32List_ = [[GPBUInt32Array alloc] initWithValues:&value count:1]; } else { [mutableFixed32List_ addValue:value]; } } - (void)addFixed64:(uint64_t)value { if (mutableFixed64List_ == nil) { mutableFixed64List_ = [[GPBUInt64Array alloc] initWithValues:&value count:1]; } else { [mutableFixed64List_ addValue:value]; } } - (void)addLengthDelimited:(NSData *)value { if (mutableLengthDelimitedList_ == nil) { mutableLengthDelimitedList_ = [[NSMutableArray alloc] initWithObjects:&value count:1]; } else { [mutableLengthDelimitedList_ addObject:value]; } } - (void)addGroup:(GPBUnknownFieldSet *)value { if (mutableGroupList_ == nil) { mutableGroupList_ = [[NSMutableArray alloc] initWithObjects:&value count:1]; } else { [mutableGroupList_ addObject:value]; } } #pragma clang diagnostic pop @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownFieldSet.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import @class GPBUnknownField; NS_ASSUME_NONNULL_BEGIN /** * A collection of unknown fields. Fields parsed from the binary representation * of a message that are unknown end up in an instance of this set. This only * applies for files declared with the "proto2" syntax. Files declared with the * "proto3" syntax discard the unknown values. **/ @interface GPBUnknownFieldSet : NSObject /** * Tests to see if the given field number has a value. * * @param number The field number to check. * * @return YES if there is an unknown field for the given field number. **/ - (BOOL)hasField:(int32_t)number; /** * Fetches the GPBUnknownField for the given field number. * * @param number The field number to look up. * * @return The GPBUnknownField or nil if none found. **/ - (nullable GPBUnknownField *)getField:(int32_t)number; /** * @return The number of fields in this set. **/ - (NSUInteger)countOfFields; /** * Adds the given field to the set. * * @param field The field to add to the set. **/ - (void)addField:(GPBUnknownField *)field; /** * @return An array of the GPBUnknownFields sorted by the field numbers. **/ - (NSArray *)sortedFields; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownFieldSet.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBUnknownFieldSet_PackagePrivate.h" #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBCodedOutputStream.h" #import "GPBUnknownField_PackagePrivate.h" #import "GPBUtilities.h" #import "GPBWireFormat.h" #pragma mark Helpers static void checkNumber(int32_t number) { if (number == 0) { [NSException raise:NSInvalidArgumentException format:@"Zero is not a valid field number."]; } } @implementation GPBUnknownFieldSet { @package CFMutableDictionaryRef fields_; } static void CopyWorker(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; GPBUnknownFieldSet *result = context; GPBUnknownField *copied = [field copy]; [result addField:copied]; [copied release]; } // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (id)copyWithZone:(NSZone *)zone { GPBUnknownFieldSet *result = [[GPBUnknownFieldSet allocWithZone:zone] init]; if (fields_) { CFDictionaryApplyFunction(fields_, CopyWorker, result); } return result; } - (void)dealloc { if (fields_) { CFRelease(fields_); } [super dealloc]; } - (BOOL)isEqual:(id)object { BOOL equal = NO; if ([object isKindOfClass:[GPBUnknownFieldSet class]]) { GPBUnknownFieldSet *set = (GPBUnknownFieldSet *)object; if ((fields_ == NULL) && (set->fields_ == NULL)) { equal = YES; } else if ((fields_ != NULL) && (set->fields_ != NULL)) { equal = CFEqual(fields_, set->fields_); } } return equal; } - (NSUInteger)hash { // Return the hash of the fields dictionary (or just some value). if (fields_) { return CFHash(fields_); } return (NSUInteger)[GPBUnknownFieldSet class]; } #pragma mark - Public Methods - (BOOL)hasField:(int32_t)number { ssize_t key = number; return fields_ ? (CFDictionaryGetValue(fields_, (void *)key) != nil) : NO; } - (GPBUnknownField *)getField:(int32_t)number { ssize_t key = number; GPBUnknownField *result = fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil; return result; } - (NSUInteger)countOfFields { return fields_ ? CFDictionaryGetCount(fields_) : 0; } - (NSArray *)sortedFields { if (!fields_) return [NSArray array]; size_t count = CFDictionaryGetCount(fields_); ssize_t keys[count]; GPBUnknownField *values[count]; CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values); struct GPBFieldPair { ssize_t key; GPBUnknownField *value; } pairs[count]; for (size_t i = 0; i < count; ++i) { pairs[i].key = keys[i]; pairs[i].value = values[i]; }; qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) { const struct GPBFieldPair *a = first; const struct GPBFieldPair *b = second; return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); }); for (size_t i = 0; i < count; ++i) { values[i] = pairs[i].value; }; return [NSArray arrayWithObjects:values count:count]; } #pragma mark - Internal Methods - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output { if (!fields_) return; size_t count = CFDictionaryGetCount(fields_); ssize_t keys[count]; GPBUnknownField *values[count]; CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values); if (count > 1) { struct GPBFieldPair { ssize_t key; GPBUnknownField *value; } pairs[count]; for (size_t i = 0; i < count; ++i) { pairs[i].key = keys[i]; pairs[i].value = values[i]; }; qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) { const struct GPBFieldPair *a = first; const struct GPBFieldPair *b = second; return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); }); for (size_t i = 0; i < count; ++i) { GPBUnknownField *value = pairs[i].value; [value writeToOutput:output]; } } else { [values[0] writeToOutput:output]; } } - (NSString *)description { NSMutableString *description = [NSMutableString stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" "); [description appendString:textFormat]; [description appendString:@"}"]; return description; } static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; size_t *result = context; *result += [field serializedSize]; } - (size_t)serializedSize { size_t result = 0; if (fields_) { CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, &result); } return result; } static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; GPBCodedOutputStream *output = context; [field writeAsMessageSetExtensionToOutput:output]; } - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output { if (fields_) { CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, output); } } static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; size_t *result = context; *result += [field serializedSizeAsMessageSetExtension]; } - (size_t)serializedSizeAsMessageSet { size_t result = 0; if (fields_) { CFDictionaryApplyFunction( fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result); } return result; } - (NSData *)data { NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize]; GPBCodedOutputStream *output = [[GPBCodedOutputStream alloc] initWithData:data]; [self writeToCodedOutputStream:output]; [output release]; return data; } + (BOOL)isFieldTag:(int32_t)tag { return GPBWireFormatGetTagWireType(tag) != GPBWireFormatEndGroup; } - (void)addField:(GPBUnknownField *)field { int32_t number = [field number]; checkNumber(number); if (!fields_) { // Use a custom dictionary here because the keys are numbers and conversion // back and forth from NSNumber isn't worth the cost. fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); } ssize_t key = number; CFDictionarySetValue(fields_, (const void *)key, field); } - (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create { ssize_t key = number; GPBUnknownField *existing = fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil; if (!existing && create) { existing = [[GPBUnknownField alloc] initWithNumber:number]; // This retains existing. [self addField:existing]; [existing release]; } return existing; } static void GPBUnknownFieldSetMergeUnknownFields(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; GPBUnknownFieldSet *self = context; int32_t number = [field number]; checkNumber(number); GPBUnknownField *oldField = [self mutableFieldForNumber:number create:NO]; if (oldField) { [oldField mergeFromField:field]; } else { // Merge only comes from GPBMessage's mergeFrom:, so it means we are on // mutable message and are an mutable instance, so make sure we need // mutable fields. GPBUnknownField *fieldCopy = [field copy]; [self addField:fieldCopy]; [fieldCopy release]; } } - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other { if (other && other->fields_) { CFDictionaryApplyFunction(other->fields_, GPBUnknownFieldSetMergeUnknownFields, self); } } - (void)mergeFromData:(NSData *)data { GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; [self mergeFromCodedInputStream:input]; [input checkLastTagWas:0]; [input release]; } - (void)mergeVarintField:(int32_t)number value:(int32_t)value { checkNumber(number); [[self mutableFieldForNumber:number create:YES] addVarint:value]; } - (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input { NSAssert(GPBWireFormatIsValidTag(tag), @"Got passed an invalid tag"); int32_t number = GPBWireFormatGetTagFieldNumber(tag); GPBCodedInputStreamState *state = &input->state_; switch (GPBWireFormatGetTagWireType(tag)) { case GPBWireFormatVarint: { GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; [field addVarint:GPBCodedInputStreamReadInt64(state)]; return YES; } case GPBWireFormatFixed64: { GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; [field addFixed64:GPBCodedInputStreamReadFixed64(state)]; return YES; } case GPBWireFormatLengthDelimited: { NSData *data = GPBCodedInputStreamReadRetainedBytes(state); GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; [field addLengthDelimited:data]; [data release]; return YES; } case GPBWireFormatStartGroup: { GPBUnknownFieldSet *unknownFieldSet = [[GPBUnknownFieldSet alloc] init]; [input readUnknownGroup:number message:unknownFieldSet]; GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; [field addGroup:unknownFieldSet]; [unknownFieldSet release]; return YES; } case GPBWireFormatEndGroup: return NO; case GPBWireFormatFixed32: { GPBUnknownField *field = [self mutableFieldForNumber:number create:YES]; [field addFixed32:GPBCodedInputStreamReadFixed32(state)]; return YES; } } } - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData { [[self mutableFieldForNumber:number create:YES] addLengthDelimited:messageData]; } - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { GPBUnknownField *field = [self mutableFieldForNumber:fieldNum create:YES]; [field addLengthDelimited:data]; } - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input { while (YES) { int32_t tag = GPBCodedInputStreamReadTag(&input->state_); if (tag == 0 || ![self mergeFieldFrom:tag input:input]) { break; } } } - (void)getTags:(int32_t *)tags { if (!fields_) return; size_t count = CFDictionaryGetCount(fields_); ssize_t keys[count]; CFDictionaryGetKeysAndValues(fields_, (const void **)keys, NULL); for (size_t i = 0; i < count; ++i) { tags[i] = (int32_t)keys[i]; } } #pragma clang diagnostic pop @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownFieldSet_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBUnknownFieldSet.h" @class GPBCodedOutputStream; @class GPBCodedInputStream; @interface GPBUnknownFieldSet () + (BOOL)isFieldTag:(int32_t)tag; - (NSData *)data; - (size_t)serializedSize; - (size_t)serializedSizeAsMessageSet; - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output; - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output; - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other; - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input; - (void)mergeFromData:(NSData *)data; - (void)mergeVarintField:(int32_t)number value:(int32_t)value; - (BOOL)mergeFieldFrom:(int32_t)tag input:(GPBCodedInputStream *)input; - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData; - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUnknownField_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBUnknownField.h" @class GPBCodedOutputStream; @interface GPBUnknownField () - (instancetype)initWithNumber:(int32_t)number; - (void)writeToOutput:(GPBCodedOutputStream *)output; - (size_t)serializedSize; - (void)writeAsMessageSetExtensionToOutput:(GPBCodedOutputStream *)output; - (size_t)serializedSizeAsMessageSetExtension; - (void)mergeFromField:(GPBUnknownField *)other; @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUtilities.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBArray.h" #import "GPBMessage.h" #import "GPBRuntimeTypes.h" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN /** * Generates a string that should be a valid "TextFormat" for the C++ version * of Protocol Buffers. * * @param message The message to generate from. * @param lineIndent A string to use as the prefix for all lines generated. Can * be nil if no extra indent is needed. * * @return An NSString with the TextFormat of the message. **/ NSString *GPBTextFormatForMessage(GPBMessage *message, NSString * __nullable lineIndent); /** * Generates a string that should be a valid "TextFormat" for the C++ version * of Protocol Buffers. * * @param unknownSet The unknown field set to generate from. * @param lineIndent A string to use as the prefix for all lines generated. Can * be nil if no extra indent is needed. * * @return An NSString with the TextFormat of the unknown field set. **/ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet * __nullable unknownSet, NSString * __nullable lineIndent); /** * Checks if the given field number is set on a message. * * @param self The message to check. * @param fieldNumber The field number to check. * * @return YES if the field number is set on the given message. **/ BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber); /** * Checks if the given field is set on a message. * * @param self The message to check. * @param field The field to check. * * @return YES if the field is set on the given message. **/ BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field); /** * Clears the given field for the given message. * * @param self The message for which to clear the field. * @param field The field to clear. **/ void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field); //%PDDM-EXPAND GPB_ACCESSORS() // This block of code is generated, do not edit it directly. // // Get/Set a given field from/to a message. // // Single Fields /** * Gets the value of a bytes field. * * @param self The message from which to get the field. * @param field The field to get. **/ NSData *GPBGetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a bytes field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field, NSData *value); /** * Gets the value of a string field. * * @param self The message from which to get the field. * @param field The field to get. **/ NSString *GPBGetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a string field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field, NSString *value); /** * Gets the value of a message field. * * @param self The message from which to get the field. * @param field The field to get. **/ GPBMessage *GPBGetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a message field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value); /** * Gets the value of a group field. * * @param self The message from which to get the field. * @param field The field to get. **/ GPBMessage *GPBGetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a group field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value); /** * Gets the value of a bool field. * * @param self The message from which to get the field. * @param field The field to get. **/ BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a bool field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value); /** * Gets the value of an int32 field. * * @param self The message from which to get the field. * @param field The field to get. **/ int32_t GPBGetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of an int32 field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); /** * Gets the value of an uint32 field. * * @param self The message from which to get the field. * @param field The field to get. **/ uint32_t GPBGetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of an uint32 field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value); /** * Gets the value of an int64 field. * * @param self The message from which to get the field. * @param field The field to get. **/ int64_t GPBGetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of an int64 field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field, int64_t value); /** * Gets the value of an uint64 field. * * @param self The message from which to get the field. * @param field The field to get. **/ uint64_t GPBGetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of an uint64 field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value); /** * Gets the value of a float field. * * @param self The message from which to get the field. * @param field The field to get. **/ float GPBGetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a float field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field, float value); /** * Gets the value of a double field. * * @param self The message from which to get the field. * @param field The field to get. **/ double GPBGetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a double field. * * @param self The message into which to set the field. * @param field The field to set. * @param value The to set in the field. **/ void GPBSetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field, double value); /** * Gets the given enum field of a message. For proto3, if the value isn't a * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned. * GPBGetMessageRawEnumField will bypass the check and return whatever value * was set. * * @param self The message from which to get the field. * @param field The field to get. * * @return The enum value for the given field. **/ int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field); /** * Set the given enum field of a message. You can only set values that are * members of the enum. * * @param self The message into which to set the field. * @param field The field to set. * @param value The enum value to set in the field. **/ void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); /** * Get the given enum field of a message. No check is done to ensure the value * was defined in the enum. * * @param self The message from which to get the field. * @param field The field to get. * * @return The raw enum value for the given field. **/ int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field); /** * Set the given enum field of a message. You can set the value to anything, * even a value that is not a member of the enum. * * @param self The message into which to set the field. * @param field The field to set. * @param value The raw enum value to set in the field. **/ void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); // Repeated Fields /** * Gets the value of a repeated field. * * @param self The message from which to get the field. * @param field The repeated field to get. * * @return A GPB*Array or an NSMutableArray based on the field's type. **/ id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a repeated field. * * @param self The message into which to set the field. * @param field The field to set. * @param array A GPB*Array or NSMutableArray based on the field's type. **/ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array); // Map Fields /** * Gets the value of a map<> field. * * @param self The message from which to get the field. * @param field The repeated field to get. * * @return A GPB*Dictionary or NSMutableDictionary based on the field's type. **/ id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field); /** * Sets the value of a map<> field. * * @param self The message into which to set the field. * @param field The field to set. * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the * field's type. **/ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary); //%PDDM-EXPAND-END GPB_ACCESSORS() /** * Returns an empty NSData to assign to byte fields when you wish to assign them * to empty. Prevents allocating a lot of little [NSData data] objects. **/ NSData *GPBEmptyNSData(void) __attribute__((pure)); NS_ASSUME_NONNULL_END CF_EXTERN_C_END //%PDDM-DEFINE GPB_ACCESSORS() //% //%// //%// Get/Set a given field from/to a message. //%// //% //%// Single Fields //% //%GPB_ACCESSOR_SINGLE_FULL(Bytes, NSData, , *) //%GPB_ACCESSOR_SINGLE_FULL(String, NSString, , *) //%GPB_ACCESSOR_SINGLE_FULL(Message, GPBMessage, , *) //%GPB_ACCESSOR_SINGLE_FULL(Group, GPBMessage, , *) //%GPB_ACCESSOR_SINGLE(Bool, BOOL, ) //%GPB_ACCESSOR_SINGLE(Int32, int32_t, n) //%GPB_ACCESSOR_SINGLE(UInt32, uint32_t, n) //%GPB_ACCESSOR_SINGLE(Int64, int64_t, n) //%GPB_ACCESSOR_SINGLE(UInt64, uint64_t, n) //%GPB_ACCESSOR_SINGLE(Float, float, ) //%GPB_ACCESSOR_SINGLE(Double, double, ) //%/** //% * Gets the given enum field of a message. For proto3, if the value isn't a //% * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned. //% * GPBGetMessageRawEnumField will bypass the check and return whatever value //% * was set. //% * //% * @param self The message from which to get the field. //% * @param field The field to get. //% * //% * @return The enum value for the given field. //% **/ //%int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field); //% //%/** //% * Set the given enum field of a message. You can only set values that are //% * members of the enum. //% * //% * @param self The message into which to set the field. //% * @param field The field to set. //% * @param value The enum value to set in the field. //% **/ //%void GPBSetMessageEnumField(GPBMessage *self, //% GPBFieldDescriptor *field, //% int32_t value); //% //%/** //% * Get the given enum field of a message. No check is done to ensure the value //% * was defined in the enum. //% * //% * @param self The message from which to get the field. //% * @param field The field to get. //% * //% * @return The raw enum value for the given field. //% **/ //%int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field); //% //%/** //% * Set the given enum field of a message. You can set the value to anything, //% * even a value that is not a member of the enum. //% * //% * @param self The message into which to set the field. //% * @param field The field to set. //% * @param value The raw enum value to set in the field. //% **/ //%void GPBSetMessageRawEnumField(GPBMessage *self, //% GPBFieldDescriptor *field, //% int32_t value); //% //%// Repeated Fields //% //%/** //% * Gets the value of a repeated field. //% * //% * @param self The message from which to get the field. //% * @param field The repeated field to get. //% * //% * @return A GPB*Array or an NSMutableArray based on the field's type. //% **/ //%id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field); //% //%/** //% * Sets the value of a repeated field. //% * //% * @param self The message into which to set the field. //% * @param field The field to set. //% * @param array A GPB*Array or NSMutableArray based on the field's type. //% **/ //%void GPBSetMessageRepeatedField(GPBMessage *self, //% GPBFieldDescriptor *field, //% id array); //% //%// Map Fields //% //%/** //% * Gets the value of a map<> field. //% * //% * @param self The message from which to get the field. //% * @param field The repeated field to get. //% * //% * @return A GPB*Dictionary or NSMutableDictionary based on the field's type. //% **/ //%id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field); //% //%/** //% * Sets the value of a map<> field. //% * //% * @param self The message into which to set the field. //% * @param field The field to set. //% * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the //% * field's type. //% **/ //%void GPBSetMessageMapField(GPBMessage *self, //% GPBFieldDescriptor *field, //% id dictionary); //% //%PDDM-DEFINE GPB_ACCESSOR_SINGLE(NAME, TYPE, AN) //%GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, ) //%PDDM-DEFINE GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, TisP) //%/** //% * Gets the value of a##AN NAME$L field. //% * //% * @param self The message from which to get the field. //% * @param field The field to get. //% **/ //%TYPE TisP##GPBGetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field); //% //%/** //% * Sets the value of a##AN NAME$L field. //% * //% * @param self The message into which to set the field. //% * @param field The field to set. //% * @param value The to set in the field. //% **/ //%void GPBSetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field, TYPE TisP##value); //% ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUtilities.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBUtilities_PackagePrivate.h" #import #import "GPBArray_PackagePrivate.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBDictionary_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" #import "GPBUnknownField.h" #import "GPBUnknownFieldSet.h" // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling // protos can turn on -Wdirect-ivar-access without issues. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr, NSString *lineIndent); NSData *GPBEmptyNSData(void) { static dispatch_once_t onceToken; static NSData *defaultNSData = nil; dispatch_once(&onceToken, ^{ defaultNSData = [[NSData alloc] init]; }); return defaultNSData; } // -- About Version Checks -- // There's actually 3 places these checks all come into play: // 1. When the generated source is compile into .o files, the header check // happens. This is checking the protoc used matches the library being used // when making the .o. // 2. Every place a generated proto header is included in a developer's code, // the header check comes into play again. But this time it is checking that // the current library headers being used still support/match the ones for // the generated code. // 3. At runtime the final check here (GPBCheckRuntimeVersionsInternal), is // called from the generated code passing in values captured when the // generated code's .o was made. This checks that at runtime the generated // code and runtime library match. void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) { // NOTE: This is passing the value captured in the compiled code to check // against the values captured when the runtime support was compiled. This // ensures the library code isn't in a different framework/library that // was generated with a non matching version. if (GOOGLE_PROTOBUF_OBJC_VERSION < objcRuntimeVersion) { // Library is too old for headers. [NSException raise:NSInternalInconsistencyException format:@"Linked to ProtocolBuffer runtime version %d," @" but code compiled needing atleast %d!", GOOGLE_PROTOBUF_OBJC_VERSION, objcRuntimeVersion]; } if (objcRuntimeVersion < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) { // Headers are too old for library. [NSException raise:NSInternalInconsistencyException format:@"Proto generation source compiled against runtime" @" version %d, but this version of the runtime only" @" supports back to %d!", objcRuntimeVersion, GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION]; } } // This api is no longer used for version checks. 30001 is the last version // using this old versioning model. When that support is removed, this function // can be removed (along with the declaration in GPBUtilities_PackagePrivate.h). void GPBCheckRuntimeVersionInternal(int32_t version) { GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION == 30001, time_to_remove_this_old_version_shim); if (version != GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) { [NSException raise:NSInternalInconsistencyException format:@"Linked to ProtocolBuffer runtime version %d," @" but code compiled with version %d!", GOOGLE_PROTOBUF_OBJC_GEN_VERSION, version]; } } BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber) { GPBDescriptor *descriptor = [self descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:fieldNumber]; return GPBMessageHasFieldSet(self, field); } BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field) { if (self == nil || field == nil) return NO; // Repeated/Map don't use the bit, they check the count. if (GPBFieldIsMapOrArray(field)) { // Array/map type doesn't matter, since GPB*Array/NSArray and // GPB*Dictionary/NSDictionary all support -count; NSArray *arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(self, field); return (arrayOrMap.count > 0); } else { return GPBGetHasIvarField(self, field); } } void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) { // If not set, nothing to do. if (!GPBGetHasIvarField(self, field)) { return; } if (GPBFieldStoresObject(field)) { // Object types are handled slightly differently, they need to be released. uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; [*typePtr release]; *typePtr = nil; } else { // POD types just need to clear the has bit as the Get* method will // fetch the default when needed. } GPBSetHasIvarField(self, field, NO); } BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) { NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); if (idx < 0) { NSCAssert(fieldNumber != 0, @"Invalid field number."); BOOL hasIvar = (self->messageStorage_->_has_storage_[-idx] == fieldNumber); return hasIvar; } else { NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); uint32_t byteIndex = idx / 32; uint32_t bitMask = (1 << (idx % 32)); BOOL hasIvar = (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO; return hasIvar; } } uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) { NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", [self class], idx); uint32_t result = self->messageStorage_->_has_storage_[-idx]; return result; } void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, BOOL value) { if (idx < 0) { NSCAssert(fieldNumber != 0, @"Invalid field number."); uint32_t *has_storage = self->messageStorage_->_has_storage_; has_storage[-idx] = (value ? fieldNumber : 0); } else { NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); uint32_t *has_storage = self->messageStorage_->_has_storage_; uint32_t byte = idx / 32; uint32_t bitMask = (1 << (idx % 32)); if (value) { has_storage[byte] |= bitMask; } else { has_storage[byte] &= ~bitMask; } } } void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) { uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex); if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) { // Do nothing/nothing set in the oneof. return; } // Like GPBClearMessageField(), free the memory if an objecttype is set, // pod types don't need to do anything. GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet]; NSCAssert(fieldSet, @"%@: oneof set to something (%u) not in the oneof?", [self class], fieldNumberSet); if (fieldSet && GPBFieldStoresObject(fieldSet)) { uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[fieldSet->description_->offset]; [*typePtr release]; *typePtr = nil; } // Set to nothing stored in the oneof. // (field number doesn't matter since setting to nothing). GPBSetHasIvar(self, oneofHasIndex, 1, NO); } #pragma mark - IVar accessors //%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE) //%TYPE GPBGetMessage##NAME##Field(GPBMessage *self, //% TYPE$S NAME$S GPBFieldDescriptor *field) { //% if (GPBGetHasIvarField(self, field)) { //% uint8_t *storage = (uint8_t *)self->messageStorage_; //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset]; //% return *typePtr; //% } else { //% return field.defaultValue.value##NAME; //% } //%} //% //%// Only exists for public api, no core code should use this. //%void GPBSetMessage##NAME##Field(GPBMessage *self, //% NAME$S GPBFieldDescriptor *field, //% NAME$S TYPE value) { //% if (self == nil || field == nil) return; //% GPBFileSyntax syntax = [self descriptor].file.syntax; //% GPBSet##NAME##IvarWithFieldInternal(self, field, value, syntax); //%} //% //%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self, //% NAME$S GPBFieldDescriptor *field, //% NAME$S TYPE value, //% NAME$S GPBFileSyntax syntax) { //% GPBOneofDescriptor *oneof = field->containingOneof_; //% if (oneof) { //% GPBMessageFieldDescription *fieldDesc = field->description_; //% GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); //% } //% NSCAssert(self->messageStorage_ != NULL, //% @"%@: All messages should have storage (from init)", //% [self class]); //%#if defined(__clang_analyzer__) //% if (self->messageStorage_ == NULL) return; //%#endif //% uint8_t *storage = (uint8_t *)self->messageStorage_; //% TYPE *typePtr = (TYPE *)&storage[field->description_->offset]; //% *typePtr = value; //% // proto2: any value counts as having been set; proto3, it //% // has to be a non zero value or be in a oneof. //% BOOL hasValue = ((syntax == GPBFileSyntaxProto2) //% || (value != (TYPE)0) //% || (field->containingOneof_ != NULL)); //% GPBSetHasIvarField(self, field, hasValue); //% GPBBecomeVisibleToAutocreator(self); //%} //% //%PDDM-DEFINE IVAR_ALIAS_DEFN_OBJECT(NAME, TYPE) //%// Only exists for public api, no core code should use this. //%TYPE *GPBGetMessage##NAME##Field(GPBMessage *self, //% TYPE$S NAME$S GPBFieldDescriptor *field) { //% return (TYPE *)GPBGetObjectIvarWithField(self, field); //%} //% //%// Only exists for public api, no core code should use this. //%void GPBSetMessage##NAME##Field(GPBMessage *self, //% NAME$S GPBFieldDescriptor *field, //% NAME$S TYPE *value) { //% GPBSetObjectIvarWithField(self, field, (id)value); //%} //% // Object types are handled slightly differently, they need to be released // and retained. void GPBSetAutocreatedRetainedObjectIvarWithField( GPBMessage *self, GPBFieldDescriptor *field, id __attribute__((ns_consumed)) value) { uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; NSCAssert(*typePtr == NULL, @"Can't set autocreated object more than once."); *typePtr = value; } void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { return; } uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; GPBMessage *oldValue = *typePtr; *typePtr = NULL; GPBClearMessageAutocreator(oldValue); [oldValue release]; } // This exists only for briging some aliased types, nothing else should use it. static void GPBSetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain], syntax); } void GPBSetObjectIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, id value, GPBFileSyntax syntax) { GPBSetRetainedObjectIvarWithFieldInternal(self, field, [value retain], syntax); } void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, id value, GPBFileSyntax syntax) { NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif GPBDataType fieldType = GPBGetFieldDataType(field); BOOL isMapOrArray = GPBFieldIsMapOrArray(field); BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType); #ifdef DEBUG if (value == nil && !isMapOrArray && !fieldIsMessage && field.hasDefaultValue) { // Setting a message to nil is an obvious way to "clear" the value // as there is no way to set a non-empty default value for messages. // // For Strings and Bytes that have default values set it is not clear what // should be done when their value is set to nil. Is the intention just to // clear the set value and reset to default, or is the intention to set the // value to the empty string/data? Arguments can be made for both cases. // 'nil' has been abused as a replacement for an empty string/data in ObjC. // We decided to be consistent with all "object" types and clear the has // field, and fall back on the default value. The warning below will only // appear in debug, but the could should be changed so the intention is // clear. NSString *hasSel = NSStringFromSelector(field->hasOrCountSel_); NSString *propName = field.name; NSString *className = self.descriptor.name; NSLog(@"warning: '%@.%@ = nil;' is not clearly defined for fields with " @"default values. Please use '%@.%@ = %@' if you want to set it to " @"empty, or call '%@.%@ = NO' to reset it to it's default value of " @"'%@'. Defaulting to resetting default value.", className, propName, className, propName, (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", className, hasSel, field.defaultValue.valueString); // Note: valueString, depending on the type, it could easily be // valueData/valueMessage. } #endif // DEBUG if (!isMapOrArray) { // Non repeated/map can be in an oneof, clear any existing value from the // oneof. GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } // Clear "has" if they are being set to nil. BOOL setHasValue = (value != nil); // Under proto3, Bytes & String fields get cleared by resetting them to // their default (empty) values, so if they are set to something of length // zero, they are being cleared. if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage && ([value length] == 0)) { // Except, if the field was in a oneof, then it still gets recorded as // having been set so the state of the oneof can be serialized back out. if (!oneof) { setHasValue = NO; } if (setHasValue) { NSCAssert(value != nil, @"Should never be setting has for nil"); } else { // The value passed in was retained, it must be released since we // aren't saving anything in the field. [value release]; value = nil; } } GPBSetHasIvarField(self, field, setHasValue); } uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; id oldValue = *typePtr; *typePtr = value; if (oldValue) { if (isMapOrArray) { if (field.fieldType == GPBFieldTypeRepeated) { // If the old array was autocreated by us, then clear it. if (GPBDataTypeIsObject(fieldType)) { if ([oldValue isKindOfClass:[GPBAutocreatedArray class]]) { GPBAutocreatedArray *autoArray = oldValue; if (autoArray->_autocreator == self) { autoArray->_autocreator = nil; } } } else { // Type doesn't matter, it is a GPB*Array. GPBInt32Array *gpbArray = oldValue; if (gpbArray->_autocreator == self) { gpbArray->_autocreator = nil; } } } else { // GPBFieldTypeMap // If the old map was autocreated by us, then clear it. if ((field.mapKeyDataType == GPBDataTypeString) && GPBDataTypeIsObject(fieldType)) { if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) { GPBAutocreatedDictionary *autoDict = oldValue; if (autoDict->_autocreator == self) { autoDict->_autocreator = nil; } } } else { // Type doesn't matter, it is a GPB*Dictionary. GPBInt32Int32Dictionary *gpbDict = oldValue; if (gpbDict->_autocreator == self) { gpbDict->_autocreator = nil; } } } } else if (fieldIsMessage) { // If the old message value was autocreated by us, then clear it. GPBMessage *oldMessageValue = oldValue; if (GPBWasMessageAutocreatedBy(oldMessageValue, self)) { GPBClearMessageAutocreator(oldMessageValue); } } [oldValue release]; } GPBBecomeVisibleToAutocreator(self); } id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, GPBFieldDescriptor *field) { if (self->messageStorage_ == nil) { return nil; } uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; return *typePtr; } id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { NSCAssert(!GPBFieldIsMapOrArray(field), @"Shouldn't get here"); if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[field->description_->offset]; return *typePtr; } // Not set... // Non messages (string/data), get their default. if (!GPBFieldDataTypeIsMessage(field)) { return field.defaultValue.valueMessage; } GPBPrepareReadOnlySemaphore(self); dispatch_semaphore_wait(self->readOnlySemaphore_, DISPATCH_TIME_FOREVER); GPBMessage *result = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!result) { // For non repeated messages, create the object, set it and return it. // This object will not initially be visible via GPBGetHasIvar, so // we save its creator so it can become visible if it's mutated later. result = GPBCreateMessageWithAutocreator(field.msgClass, self, field); GPBSetAutocreatedRetainedObjectIvarWithField(self, field, result); } dispatch_semaphore_signal(self->readOnlySemaphore_); return result; } // Only exists for public api, no core code should use this. int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) { GPBFileSyntax syntax = [self descriptor].file.syntax; return GPBGetEnumIvarWithFieldInternal(self, field, syntax); } int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax) { int32_t result = GPBGetMessageInt32Field(self, field); // If this is presevering unknown enums, make sure the value is valid before // returning it. if (GPBHasPreservingUnknownEnumSemantics(syntax) && ![field isValidEnumValue:result]) { result = kGPBUnrecognizedEnumeratorValue; } return result; } // Only exists for public api, no core code should use this. void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); } void GPBSetEnumIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax) { // Don't allow in unknown values. Proto3 can use the Raw method. if (![field isValidEnumValue:value]) { [NSException raise:NSInvalidArgumentException format:@"%@.%@: Attempt to set an unknown enum value (%d)", [self class], field.name, value]; } GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); } // Only exists for public api, no core code should use this. int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field) { int32_t result = GPBGetMessageInt32Field(self, field); return result; } // Only exists for public api, no core code should use this. void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); } BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { // Bools are stored in the has bits to avoid needing explicit space in the // storage structure. // (the field number passed to the HasIvar helper doesn't really matter // since the offset is never negative) GPBMessageFieldDescription *fieldDesc = field->description_; return GPBGetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number); } else { return field.defaultValue.valueBool; } } // Only exists for public api, no core code should use this. void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetBoolIvarWithFieldInternal(self, field, value, syntax); } void GPBSetBoolIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, BOOL value, GPBFileSyntax syntax) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } // Bools are stored in the has bits to avoid needing explicit space in the // storage structure. // (the field number passed to the HasIvar helper doesn't really matter since // the offset is never negative) GPBSetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number, value); // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (BOOL)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t) // This block of code is generated, do not edit it directly. int32_t GPBGetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; int32_t *typePtr = (int32_t *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueInt32; } } // Only exists for public api, no core code should use this. void GPBSetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetInt32IvarWithFieldInternal(self, field, value, syntax); } void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; int32_t *typePtr = (int32_t *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (int32_t)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t) // This block of code is generated, do not edit it directly. uint32_t GPBGetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueUInt32; } } // Only exists for public api, no core code should use this. void GPBSetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetUInt32IvarWithFieldInternal(self, field, value, syntax); } void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (uint32_t)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t) // This block of code is generated, do not edit it directly. int64_t GPBGetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; int64_t *typePtr = (int64_t *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueInt64; } } // Only exists for public api, no core code should use this. void GPBSetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field, int64_t value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetInt64IvarWithFieldInternal(self, field, value, syntax); } void GPBSetInt64IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int64_t value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; int64_t *typePtr = (int64_t *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (int64_t)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t) // This block of code is generated, do not edit it directly. uint64_t GPBGetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueUInt64; } } // Only exists for public api, no core code should use this. void GPBSetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetUInt64IvarWithFieldInternal(self, field, value, syntax); } void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (uint64_t)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float) // This block of code is generated, do not edit it directly. float GPBGetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; float *typePtr = (float *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueFloat; } } // Only exists for public api, no core code should use this. void GPBSetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field, float value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetFloatIvarWithFieldInternal(self, field, value, syntax); } void GPBSetFloatIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, float value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; float *typePtr = (float *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (float)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double) // This block of code is generated, do not edit it directly. double GPBGetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { uint8_t *storage = (uint8_t *)self->messageStorage_; double *typePtr = (double *)&storage[field->description_->offset]; return *typePtr; } else { return field.defaultValue.valueDouble; } } // Only exists for public api, no core code should use this. void GPBSetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field, double value) { if (self == nil || field == nil) return; GPBFileSyntax syntax = [self descriptor].file.syntax; GPBSetDoubleIvarWithFieldInternal(self, field, value, syntax); } void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, double value, GPBFileSyntax syntax) { GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBMaybeClearOneof(self, oneof, fieldDesc->hasIndex, fieldDesc->number); } NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; #endif uint8_t *storage = (uint8_t *)self->messageStorage_; double *typePtr = (double *)&storage[field->description_->offset]; *typePtr = value; // proto2: any value counts as having been set; proto3, it // has to be a non zero value or be in a oneof. BOOL hasValue = ((syntax == GPBFileSyntaxProto2) || (value != (double)0) || (field->containingOneof_ != NULL)); GPBSetHasIvarField(self, field, hasValue); GPBBecomeVisibleToAutocreator(self); } //%PDDM-EXPAND-END (6 expansions) // Aliases are function calls that are virtually the same. //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(String, NSString) // This block of code is generated, do not edit it directly. // Only exists for public api, no core code should use this. NSString *GPBGetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field) { return (NSString *)GPBGetObjectIvarWithField(self, field); } // Only exists for public api, no core code should use this. void GPBSetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field, NSString *value) { GPBSetObjectIvarWithField(self, field, (id)value); } //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Bytes, NSData) // This block of code is generated, do not edit it directly. // Only exists for public api, no core code should use this. NSData *GPBGetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field) { return (NSData *)GPBGetObjectIvarWithField(self, field); } // Only exists for public api, no core code should use this. void GPBSetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field, NSData *value) { GPBSetObjectIvarWithField(self, field, (id)value); } //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage) // This block of code is generated, do not edit it directly. // Only exists for public api, no core code should use this. GPBMessage *GPBGetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field) { return (GPBMessage *)GPBGetObjectIvarWithField(self, field); } // Only exists for public api, no core code should use this. void GPBSetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value) { GPBSetObjectIvarWithField(self, field, (id)value); } //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage) // This block of code is generated, do not edit it directly. // Only exists for public api, no core code should use this. GPBMessage *GPBGetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field) { return (GPBMessage *)GPBGetObjectIvarWithField(self, field); } // Only exists for public api, no core code should use this. void GPBSetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value) { GPBSetObjectIvarWithField(self, field, (id)value); } //%PDDM-EXPAND-END (4 expansions) // GPBGetMessageRepeatedField is defined in GPBMessage.m // Only exists for public api, no core code should use this. void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array) { #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeRepeated) { [NSException raise:NSInvalidArgumentException format:@"%@.%@ is not a repeated field.", [self class], field.name]; } Class expectedClass = Nil; switch (GPBGetFieldDataType(field)) { case GPBDataTypeBool: expectedClass = [GPBBoolArray class]; break; case GPBDataTypeSFixed32: case GPBDataTypeInt32: case GPBDataTypeSInt32: expectedClass = [GPBInt32Array class]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: expectedClass = [GPBUInt32Array class]; break; case GPBDataTypeSFixed64: case GPBDataTypeInt64: case GPBDataTypeSInt64: expectedClass = [GPBInt64Array class]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: expectedClass = [GPBUInt64Array class]; break; case GPBDataTypeFloat: expectedClass = [GPBFloatArray class]; break; case GPBDataTypeDouble: expectedClass = [GPBDoubleArray class]; break; case GPBDataTypeBytes: case GPBDataTypeString: case GPBDataTypeMessage: case GPBDataTypeGroup: expectedClass = [NSMutableArray class]; break; case GPBDataTypeEnum: expectedClass = [GPBEnumArray class]; break; } if (array && ![array isKindOfClass:expectedClass]) { [NSException raise:NSInvalidArgumentException format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name, expectedClass, [array class]]; } #endif GPBSetObjectIvarWithField(self, field, array); } #if defined(DEBUG) && DEBUG static NSString *TypeToStr(GPBDataType dataType) { switch (dataType) { case GPBDataTypeBool: return @"Bool"; case GPBDataTypeSFixed32: case GPBDataTypeInt32: case GPBDataTypeSInt32: return @"Int32"; case GPBDataTypeFixed32: case GPBDataTypeUInt32: return @"UInt32"; case GPBDataTypeSFixed64: case GPBDataTypeInt64: case GPBDataTypeSInt64: return @"Int64"; case GPBDataTypeFixed64: case GPBDataTypeUInt64: return @"UInt64"; case GPBDataTypeFloat: return @"Float"; case GPBDataTypeDouble: return @"Double"; case GPBDataTypeBytes: case GPBDataTypeString: case GPBDataTypeMessage: case GPBDataTypeGroup: return @"Object"; case GPBDataTypeEnum: return @"Bool"; } } #endif // GPBGetMessageMapField is defined in GPBMessage.m // Only exists for public api, no core code should use this. void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary) { #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeMap) { [NSException raise:NSInvalidArgumentException format:@"%@.%@ is not a map<> field.", [self class], field.name]; } if (dictionary) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); NSString *keyStr = TypeToStr(keyDataType); NSString *valueStr = TypeToStr(valueDataType); if (keyDataType == GPBDataTypeString) { keyStr = @"String"; } Class expectedClass = Nil; if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { expectedClass = [NSMutableDictionary class]; } else { NSString *className = [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr]; expectedClass = NSClassFromString(className); NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass); } if (![dictionary isKindOfClass:expectedClass]) { [NSException raise:NSInvalidArgumentException format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name, expectedClass, [dictionary class]]; } } #endif GPBSetObjectIvarWithField(self, field, dictionary); } #pragma mark - Misc Dynamic Runtime Utils const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) { Protocol *protocol = objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol)); struct objc_method_description description = protocol_getMethodDescription(protocol, selector, NO, instanceSel); return description.types; } #pragma mark - Text Format Support static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) { [destStr appendString:@"\""]; NSUInteger len = [toPrint length]; for (NSUInteger i = 0; i < len; ++i) { unichar aChar = [toPrint characterAtIndex:i]; switch (aChar) { case '\n': [destStr appendString:@"\\n"]; break; case '\r': [destStr appendString:@"\\r"]; break; case '\t': [destStr appendString:@"\\t"]; break; case '\"': [destStr appendString:@"\\\""]; break; case '\'': [destStr appendString:@"\\\'"]; break; case '\\': [destStr appendString:@"\\\\"]; break; default: // This differs slightly from the C++ code in that the C++ doesn't // generate UTF8; it looks at the string in UTF8, but escapes every // byte > 0x7E. if (aChar < 0x20) { [destStr appendFormat:@"\\%d%d%d", (aChar / 64), ((aChar % 64) / 8), (aChar % 8)]; } else { [destStr appendFormat:@"%C", aChar]; } break; } } [destStr appendString:@"\""]; } static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) { const char *src = (const char *)[buffer bytes]; size_t srcLen = [buffer length]; [destStr appendString:@"\""]; for (const char *srcEnd = src + srcLen; src < srcEnd; src++) { switch (*src) { case '\n': [destStr appendString:@"\\n"]; break; case '\r': [destStr appendString:@"\\r"]; break; case '\t': [destStr appendString:@"\\t"]; break; case '\"': [destStr appendString:@"\\\""]; break; case '\'': [destStr appendString:@"\\\'"]; break; case '\\': [destStr appendString:@"\\\\"]; break; default: if (isprint(*src)) { [destStr appendFormat:@"%c", *src]; } else { // NOTE: doing hex means you have to worry about the letter after // the hex being another hex char and forcing that to be escaped, so // use octal to keep it simple. [destStr appendFormat:@"\\%03o", (uint8_t)(*src)]; } break; } } [destStr appendString:@"\""]; } static void AppendTextFormatForMapMessageField( id map, GPBFieldDescriptor *field, NSMutableString *toStr, NSString *lineIndent, NSString *fieldName, NSString *lineEnding) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType); NSString *msgStartFirst = [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding]; NSString *msgStart = [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName]; NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent]; NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent]; NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent, (isMessageValue ? "" : ":")]; __block BOOL isFirst = YES; if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { // map is an NSDictionary. NSDictionary *dict = map; [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { #pragma unused(stop) [toStr appendString:(isFirst ? msgStartFirst : msgStart)]; isFirst = NO; [toStr appendString:keyLine]; AppendStringEscaped(key, toStr); [toStr appendString:@"\n"]; [toStr appendString:valueLine]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" switch (valueDataType) { case GPBDataTypeString: AppendStringEscaped(value, toStr); break; case GPBDataTypeBytes: AppendBufferAsString(value, toStr); break; case GPBDataTypeMessage: [toStr appendString:@"{\n"]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; AppendTextFormatForMessage(value, toStr, subIndent); [toStr appendFormat:@"%@ }", lineIndent]; break; default: NSCAssert(NO, @"Can't happen"); break; } #pragma clang diagnostic pop [toStr appendString:@"\n"]; [toStr appendString:msgEnd]; }]; } else { // map is one of the GPB*Dictionary classes, type doesn't matter. GPBInt32Int32Dictionary *dict = map; [dict enumerateForTextFormat:^(id keyObj, id valueObj) { [toStr appendString:(isFirst ? msgStartFirst : msgStart)]; isFirst = NO; // Key always is a NSString. if (keyDataType == GPBDataTypeString) { [toStr appendString:keyLine]; AppendStringEscaped(keyObj, toStr); [toStr appendString:@"\n"]; } else { [toStr appendFormat:@"%@%@\n", keyLine, keyObj]; } [toStr appendString:valueLine]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" switch (valueDataType) { case GPBDataTypeString: AppendStringEscaped(valueObj, toStr); break; case GPBDataTypeBytes: AppendBufferAsString(valueObj, toStr); break; case GPBDataTypeMessage: [toStr appendString:@"{\n"]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; AppendTextFormatForMessage(valueObj, toStr, subIndent); [toStr appendFormat:@"%@ }", lineIndent]; break; case GPBDataTypeEnum: { int32_t enumValue = [valueObj intValue]; NSString *valueStr = nil; GPBEnumDescriptor *descriptor = field.enumDescriptor; if (descriptor) { valueStr = [descriptor textFormatNameForValue:enumValue]; } if (valueStr) { [toStr appendString:valueStr]; } else { [toStr appendFormat:@"%d", enumValue]; } break; } default: NSCAssert(valueDataType != GPBDataTypeGroup, @"Can't happen"); // Everything else is a NSString. [toStr appendString:valueObj]; break; } #pragma clang diagnostic pop [toStr appendString:@"\n"]; [toStr appendString:msgEnd]; }]; } } static void AppendTextFormatForMessageField(GPBMessage *message, GPBFieldDescriptor *field, NSMutableString *toStr, NSString *lineIndent) { id arrayOrMap; NSUInteger count; GPBFieldType fieldType = field.fieldType; switch (fieldType) { case GPBFieldTypeSingle: arrayOrMap = nil; count = (GPBGetHasIvarField(message, field) ? 1 : 0); break; case GPBFieldTypeRepeated: // Will be NSArray or GPB*Array, type doesn't matter, they both // implement count. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field); count = [(NSArray *)arrayOrMap count]; break; case GPBFieldTypeMap: { // Will be GPB*Dictionary or NSMutableDictionary, type doesn't matter, // they both implement count. arrayOrMap = GPBGetObjectIvarWithFieldNoAutocreate(message, field); count = [(NSDictionary *)arrayOrMap count]; break; } } if (count == 0) { // Nothing to print, out of here. return; } NSString *lineEnding = @""; // If the name can't be reversed or support for extra info was turned off, // this can return nil. NSString *fieldName = [field textFormatName]; if ([fieldName length] == 0) { fieldName = [NSString stringWithFormat:@"%u", GPBFieldNumber(field)]; // If there is only one entry, put the objc name as a comment, other wise // add it before the repeated values. if (count > 1) { [toStr appendFormat:@"%@# %@\n", lineIndent, field.name]; } else { lineEnding = [NSString stringWithFormat:@" # %@", field.name]; } } if (fieldType == GPBFieldTypeMap) { AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, fieldName, lineEnding); return; } id array = arrayOrMap; const BOOL isRepeated = (array != nil); GPBDataType fieldDataType = GPBGetFieldDataType(field); BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType); for (NSUInteger j = 0; j < count; ++j) { // Start the line. [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, (isMessageField ? "" : ":")]; // The value. switch (fieldDataType) { #define FIELD_CASE(GPBDATATYPE, CTYPE, REAL_TYPE, ...) \ case GPBDataType##GPBDATATYPE: { \ CTYPE v = (isRepeated ? [(GPB##REAL_TYPE##Array *)array valueAtIndex:j] \ : GPBGetMessage##REAL_TYPE##Field(message, field)); \ [toStr appendFormat:__VA_ARGS__, v]; \ break; \ } FIELD_CASE(Int32, int32_t, Int32, @"%d") FIELD_CASE(SInt32, int32_t, Int32, @"%d") FIELD_CASE(SFixed32, int32_t, Int32, @"%d") FIELD_CASE(UInt32, uint32_t, UInt32, @"%u") FIELD_CASE(Fixed32, uint32_t, UInt32, @"%u") FIELD_CASE(Int64, int64_t, Int64, @"%lld") FIELD_CASE(SInt64, int64_t, Int64, @"%lld") FIELD_CASE(SFixed64, int64_t, Int64, @"%lld") FIELD_CASE(UInt64, uint64_t, UInt64, @"%llu") FIELD_CASE(Fixed64, uint64_t, UInt64, @"%llu") FIELD_CASE(Float, float, Float, @"%.*g", FLT_DIG) FIELD_CASE(Double, double, Double, @"%.*lg", DBL_DIG) #undef FIELD_CASE case GPBDataTypeEnum: { int32_t v = (isRepeated ? [(GPBEnumArray *)array rawValueAtIndex:j] : GPBGetMessageInt32Field(message, field)); NSString *valueStr = nil; GPBEnumDescriptor *descriptor = field.enumDescriptor; if (descriptor) { valueStr = [descriptor textFormatNameForValue:v]; } if (valueStr) { [toStr appendString:valueStr]; } else { [toStr appendFormat:@"%d", v]; } break; } case GPBDataTypeBool: { BOOL v = (isRepeated ? [(GPBBoolArray *)array valueAtIndex:j] : GPBGetMessageBoolField(message, field)); [toStr appendString:(v ? @"true" : @"false")]; break; } case GPBDataTypeString: { NSString *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] : GPBGetMessageStringField(message, field)); AppendStringEscaped(v, toStr); break; } case GPBDataTypeBytes: { NSData *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] : GPBGetMessageBytesField(message, field)); AppendBufferAsString(v, toStr); break; } case GPBDataTypeGroup: case GPBDataTypeMessage: { GPBMessage *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] : GPBGetObjectIvarWithField(message, field)); [toStr appendFormat:@"{%@\n", lineEnding]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; AppendTextFormatForMessage(v, toStr, subIndent); [toStr appendFormat:@"%@}", lineIndent]; lineEnding = @""; break; } } // switch(fieldDataType) // End the line. [toStr appendFormat:@"%@\n", lineEnding]; } // for(count) } static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, NSArray *activeExtensions, GPBExtensionRange range, NSMutableString *toStr, NSString *lineIndent) { uint32_t start = range.start; uint32_t end = range.end; for (GPBExtensionDescriptor *extension in activeExtensions) { uint32_t fieldNumber = extension.fieldNumber; if (fieldNumber < start) { // Not there yet. continue; } if (fieldNumber > end) { // Done. break; } id rawExtValue = [message getExtension:extension]; BOOL isRepeated = extension.isRepeated; NSUInteger numValues = 1; NSString *lineEnding = @""; if (isRepeated) { numValues = [(NSArray *)rawExtValue count]; } NSString *singletonName = extension.singletonName; if (numValues == 1) { lineEnding = [NSString stringWithFormat:@" # [%@]", singletonName]; } else { [toStr appendFormat:@"%@# [%@]\n", lineIndent, singletonName]; } GPBDataType extDataType = extension.dataType; for (NSUInteger j = 0; j < numValues; ++j) { id curValue = (isRepeated ? [rawExtValue objectAtIndex:j] : rawExtValue); // Start the line. [toStr appendFormat:@"%@%u%s ", lineIndent, fieldNumber, (GPBDataTypeIsMessage(extDataType) ? "" : ":")]; // The value. switch (extDataType) { #define FIELD_CASE(GPBDATATYPE, CTYPE, NUMSELECTOR, ...) \ case GPBDataType##GPBDATATYPE: { \ CTYPE v = [(NSNumber *)curValue NUMSELECTOR]; \ [toStr appendFormat:__VA_ARGS__, v]; \ break; \ } FIELD_CASE(Int32, int32_t, intValue, @"%d") FIELD_CASE(SInt32, int32_t, intValue, @"%d") FIELD_CASE(SFixed32, int32_t, unsignedIntValue, @"%d") FIELD_CASE(UInt32, uint32_t, unsignedIntValue, @"%u") FIELD_CASE(Fixed32, uint32_t, unsignedIntValue, @"%u") FIELD_CASE(Int64, int64_t, longLongValue, @"%lld") FIELD_CASE(SInt64, int64_t, longLongValue, @"%lld") FIELD_CASE(SFixed64, int64_t, longLongValue, @"%lld") FIELD_CASE(UInt64, uint64_t, unsignedLongLongValue, @"%llu") FIELD_CASE(Fixed64, uint64_t, unsignedLongLongValue, @"%llu") FIELD_CASE(Float, float, floatValue, @"%.*g", FLT_DIG) FIELD_CASE(Double, double, doubleValue, @"%.*lg", DBL_DIG) // TODO: Add a comment with the enum name from enum descriptors // (might not be real value, so leave it as a comment, ObjC compiler // name mangles differently). Doesn't look like we actually generate // an enum descriptor reference like we do for normal fields, so this // will take a compiler change. FIELD_CASE(Enum, int32_t, intValue, @"%d") #undef FIELD_CASE case GPBDataTypeBool: [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" : @"false")]; break; case GPBDataTypeString: AppendStringEscaped(curValue, toStr); break; case GPBDataTypeBytes: AppendBufferAsString((NSData *)curValue, toStr); break; case GPBDataTypeGroup: case GPBDataTypeMessage: { [toStr appendFormat:@"{%@\n", lineEnding]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; AppendTextFormatForMessage(curValue, toStr, subIndent); [toStr appendFormat:@"%@}", lineIndent]; lineEnding = @""; break; } } // switch(extDataType) } // for(numValues) // End the line. [toStr appendFormat:@"%@\n", lineEnding]; } // for..in(activeExtensions) } static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr, NSString *lineIndent) { GPBDescriptor *descriptor = [message descriptor]; NSArray *fieldsArray = descriptor->fields_; NSUInteger fieldCount = fieldsArray.count; const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; NSUInteger extensionRangesCount = descriptor.extensionRangesCount; NSArray *activeExtensions = [[message extensionsCurrentlySet] sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { if (i == fieldCount) { AppendTextFormatForMessageExtensionRange( message, activeExtensions, extensionRanges[j++], toStr, lineIndent); } else if (j == extensionRangesCount || GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, lineIndent); } else { AppendTextFormatForMessageExtensionRange( message, activeExtensions, extensionRanges[j++], toStr, lineIndent); } } NSString *unknownFieldsStr = GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent); if ([unknownFieldsStr length] > 0) { [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent]; [toStr appendString:unknownFieldsStr]; } } NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) { if (message == nil) return @""; if (lineIndent == nil) lineIndent = @""; NSMutableString *buildString = [NSMutableString string]; AppendTextFormatForMessage(message, buildString, lineIndent); return buildString; } NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, NSString *lineIndent) { if (unknownSet == nil) return @""; if (lineIndent == nil) lineIndent = @""; NSMutableString *result = [NSMutableString string]; for (GPBUnknownField *field in [unknownSet sortedFields]) { int32_t fieldNumber = [field number]; #define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \ [field.PROPNAME \ enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \ _Pragma("unused(idx, stop)"); \ [result \ appendFormat:@"%@%d: " #FORMAT "\n", lineIndent, fieldNumber, value]; \ }]; PRINT_LOOP(varintList, uint64_t, %llu); PRINT_LOOP(fixed32List, uint32_t, 0x%X); PRINT_LOOP(fixed64List, uint64_t, 0x%llX); #undef PRINT_LOOP // NOTE: C++ version of TextFormat tries to parse this as a message // and print that if it succeeds. for (NSData *data in field.lengthDelimitedList) { [result appendFormat:@"%@%d: ", lineIndent, fieldNumber]; AppendBufferAsString(data, result); [result appendString:@"\n"]; } for (GPBUnknownFieldSet *subUnknownSet in field.groupList) { [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; NSString *subUnknwonSetStr = GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent); [result appendString:subUnknwonSetStr]; [result appendFormat:@"%@}\n", lineIndent]; } } return result; } // Helpers to decode a varint. Not using GPBCodedInputStream version because // that needs a state object, and we don't want to create an input stream out // of the data. GPB_INLINE int8_t ReadRawByteFromData(const uint8_t **data) { int8_t result = *((int8_t *)(*data)); ++(*data); return result; } static int32_t ReadRawVarint32FromData(const uint8_t **data) { int8_t tmp = ReadRawByteFromData(data); if (tmp >= 0) { return tmp; } int32_t result = tmp & 0x7f; if ((tmp = ReadRawByteFromData(data)) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = ReadRawByteFromData(data)) >= 0) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = ReadRawByteFromData(data)) >= 0) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = ReadRawByteFromData(data)) << 28; if (tmp < 0) { // Discard upper 32 bits. for (int i = 0; i < 5; i++) { if (ReadRawByteFromData(data) >= 0) { return result; } } [NSException raise:NSParseErrorException format:@"Unable to read varint32"]; } } } } return result; } NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *inputStr) { // decodData form: // varint32: num entries // for each entry: // varint32: key // bytes*: decode data // // decode data one of two forms: // 1: a \0 followed by the string followed by an \0 // 2: bytecodes to transform an input into the right thing, ending with \0 // // the bytes codes are of the form: // 0xabbccccc // 0x0 (all zeros), end. // a - if set, add an underscore // bb - 00 ccccc bytes as is // bb - 10 ccccc upper first, as is on rest, ccccc byte total // bb - 01 ccccc lower first, as is on rest, ccccc byte total // bb - 11 ccccc all upper, ccccc byte total if (!decodeData || !inputStr) { return nil; } // Find key const uint8_t *scan = decodeData; int32_t numEntries = ReadRawVarint32FromData(&scan); BOOL foundKey = NO; while (!foundKey && (numEntries > 0)) { --numEntries; int32_t dataKey = ReadRawVarint32FromData(&scan); if (dataKey == key) { foundKey = YES; } else { // If it is a inlined string, it will start with \0; if it is bytecode it // will start with a code. So advance one (skipping the inline string // marker), and then loop until reaching the end marker (\0). ++scan; while (*scan != 0) ++scan; // Now move past the end marker. ++scan; } } if (!foundKey) { return nil; } // Decode if (*scan == 0) { // Inline string. Move over the marker, and NSString can take it as // UTF8. ++scan; NSString *result = [NSString stringWithUTF8String:(const char *)scan]; return result; } NSMutableString *result = [NSMutableString stringWithCapacity:[inputStr length]]; const uint8_t kAddUnderscore = 0b10000000; const uint8_t kOpMask = 0b01100000; // const uint8_t kOpAsIs = 0b00000000; const uint8_t kOpFirstUpper = 0b01000000; const uint8_t kOpFirstLower = 0b00100000; const uint8_t kOpAllUpper = 0b01100000; const uint8_t kSegmentLenMask = 0b00011111; NSInteger i = 0; for (; *scan != 0; ++scan) { if (*scan & kAddUnderscore) { [result appendString:@"_"]; } int segmentLen = *scan & kSegmentLenMask; uint8_t decodeOp = *scan & kOpMask; // Do op specific handling of the first character. if (decodeOp == kOpFirstUpper) { unichar c = [inputStr characterAtIndex:i]; [result appendFormat:@"%c", toupper((char)c)]; ++i; --segmentLen; } else if (decodeOp == kOpFirstLower) { unichar c = [inputStr characterAtIndex:i]; [result appendFormat:@"%c", tolower((char)c)]; ++i; --segmentLen; } // else op == kOpAsIs || op == kOpAllUpper // Now pull over the rest of the length for this segment. for (int x = 0; x < segmentLen; ++x) { unichar c = [inputStr characterAtIndex:(i + x)]; if (decodeOp == kOpAllUpper) { [result appendFormat:@"%c", toupper((char)c)]; } else { [result appendFormat:@"%C", c]; } } i += segmentLen; } return result; } #pragma clang diagnostic pop #pragma mark - GPBMessageSignatureProtocol // A series of selectors that are used solely to get @encoding values // for them by the dynamic protobuf runtime code. An object using the protocol // needs to be declared for the protocol to be valid at runtime. @interface GPBMessageSignatureProtocol : NSObject @end @implementation GPBMessageSignatureProtocol @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBUtilities_PackagePrivate.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import #import "GPBUtilities.h" #import "GPBDescriptor_PackagePrivate.h" // Macros for stringifying library symbols. These are used in the generated // PB descriptor classes wherever a library symbol name is represented as a // string. See README.google for more information. #define GPBStringify(S) #S #define GPBStringifySymbol(S) GPBStringify(S) #define GPBNSStringify(S) @#S #define GPBNSStringifySymbol(S) GPBNSStringify(S) // Constant to internally mark when there is no has bit. #define GPBNoHasBit INT32_MAX CF_EXTERN_C_BEGIN // These two are used to inject a runtime check for version mismatch into the // generated sources to make sure they are linked with a supporting runtime. void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion); GPB_INLINE void GPB_DEBUG_CHECK_RUNTIME_VERSIONS() { // NOTE: By being inline here, this captures the value from the library's // headers at the time the generated code was compiled. #if defined(DEBUG) && DEBUG GPBCheckRuntimeVersionSupport(GOOGLE_PROTOBUF_OBJC_VERSION); #endif } // Legacy version of the checks, remove when GOOGLE_PROTOBUF_OBJC_GEN_VERSION // goes away (see more info in GPBBootstrap.h). void GPBCheckRuntimeVersionInternal(int32_t version); GPB_INLINE void GPBDebugCheckRuntimeVersion() { #if defined(DEBUG) && DEBUG GPBCheckRuntimeVersionInternal(GOOGLE_PROTOBUF_OBJC_GEN_VERSION); #endif } // Conversion functions for de/serializing floating point types. GPB_INLINE int64_t GPBConvertDoubleToInt64(double v) { union { double f; int64_t i; } u; u.f = v; return u.i; } GPB_INLINE int32_t GPBConvertFloatToInt32(float v) { union { float f; int32_t i; } u; u.f = v; return u.i; } GPB_INLINE double GPBConvertInt64ToDouble(int64_t v) { union { double f; int64_t i; } u; u.i = v; return u.f; } GPB_INLINE float GPBConvertInt32ToFloat(int32_t v) { union { float f; int32_t i; } u; u.i = v; return u.f; } GPB_INLINE int32_t GPBLogicalRightShift32(int32_t value, int32_t spaces) { return (int32_t)((uint32_t)(value) >> spaces); } GPB_INLINE int64_t GPBLogicalRightShift64(int64_t value, int32_t spaces) { return (int64_t)((uint64_t)(value) >> spaces); } // Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers // into values that can be efficiently encoded with varint. (Otherwise, // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) { return (int32_t)(GPBLogicalRightShift32((int32_t)n, 1) ^ -((int32_t)(n) & 1)); } // Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers // into values that can be efficiently encoded with varint. (Otherwise, // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE int64_t GPBDecodeZigZag64(uint64_t n) { return (int64_t)(GPBLogicalRightShift64((int64_t)n, 1) ^ -((int64_t)(n) & 1)); } // Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers // into values that can be efficiently encoded with varint. (Otherwise, // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE uint32_t GPBEncodeZigZag32(int32_t n) { // Note: the right-shift must be arithmetic return (uint32_t)((n << 1) ^ (n >> 31)); } // Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers // into values that can be efficiently encoded with varint. (Otherwise, // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE uint64_t GPBEncodeZigZag64(int64_t n) { // Note: the right-shift must be arithmetic return (uint64_t)((n << 1) ^ (n >> 63)); } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" #pragma clang diagnostic ignored "-Wdirect-ivar-access" GPB_INLINE BOOL GPBDataTypeIsObject(GPBDataType type) { switch (type) { case GPBDataTypeBytes: case GPBDataTypeString: case GPBDataTypeMessage: case GPBDataTypeGroup: return YES; default: return NO; } } GPB_INLINE BOOL GPBDataTypeIsMessage(GPBDataType type) { switch (type) { case GPBDataTypeMessage: case GPBDataTypeGroup: return YES; default: return NO; } } GPB_INLINE BOOL GPBFieldDataTypeIsMessage(GPBFieldDescriptor *field) { return GPBDataTypeIsMessage(field->description_->dataType); } GPB_INLINE BOOL GPBFieldDataTypeIsObject(GPBFieldDescriptor *field) { return GPBDataTypeIsObject(field->description_->dataType); } GPB_INLINE BOOL GPBExtensionIsMessage(GPBExtensionDescriptor *ext) { return GPBDataTypeIsMessage(ext->description_->dataType); } // The field is an array/map or it has an object value. GPB_INLINE BOOL GPBFieldStoresObject(GPBFieldDescriptor *field) { GPBMessageFieldDescription *desc = field->description_; if ((desc->flags & (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0) { return YES; } return GPBDataTypeIsObject(desc->dataType); } BOOL GPBGetHasIvar(GPBMessage *self, int32_t index, uint32_t fieldNumber); void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, BOOL value); uint32_t GPBGetHasOneof(GPBMessage *self, int32_t index); GPB_INLINE BOOL GPBGetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field) { GPBMessageFieldDescription *fieldDesc = field->description_; return GPBGetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number); } GPB_INLINE void GPBSetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, value); } void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, int32_t oneofHasIndex, uint32_t fieldNumberNotToClear); #pragma clang diagnostic pop //%PDDM-DEFINE GPB_IVAR_SET_DECL(NAME, TYPE) //%void GPBSet##NAME##IvarWithFieldInternal(GPBMessage *self, //% NAME$S GPBFieldDescriptor *field, //% NAME$S TYPE value, //% NAME$S GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Bool, BOOL) // This block of code is generated, do not edit it directly. void GPBSetBoolIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, BOOL value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Int32, int32_t) // This block of code is generated, do not edit it directly. void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt32, uint32_t) // This block of code is generated, do not edit it directly. void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Int64, int64_t) // This block of code is generated, do not edit it directly. void GPBSetInt64IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int64_t value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt64, uint64_t) // This block of code is generated, do not edit it directly. void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Float, float) // This block of code is generated, do not edit it directly. void GPBSetFloatIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, float value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Double, double) // This block of code is generated, do not edit it directly. void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, double value, GPBFileSyntax syntax); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Enum, int32_t) // This block of code is generated, do not edit it directly. void GPBSetEnumIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax); //%PDDM-EXPAND-END (8 expansions) int32_t GPBGetEnumIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax); id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); void GPBSetObjectIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, id value, GPBFileSyntax syntax); void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, id __attribute__((ns_consumed)) value, GPBFileSyntax syntax); // GPBGetObjectIvarWithField will automatically create the field (message) if // it doesn't exist. GPBGetObjectIvarWithFieldNoAutocreate will return nil. id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, GPBFieldDescriptor *field); void GPBSetAutocreatedRetainedObjectIvarWithField( GPBMessage *self, GPBFieldDescriptor *field, id __attribute__((ns_consumed)) value); // Clears and releases the autocreated message ivar, if it's autocreated. If // it's not set as autocreated, this method does nothing. void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); // Returns an Objective C encoding for |selector|. |instanceSel| should be // YES if it's an instance selector (as opposed to a class selector). // |selector| must be a selector from MessageSignatureProtocol. const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel); // Helper for text format name encoding. // decodeData is the data describing the sepecial decodes. // key and inputString are the input that needs decoding. NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *inputString); // A series of selectors that are used solely to get @encoding values // for them by the dynamic protobuf runtime code. See // GPBMessageEncodingForSelector for details. @protocol GPBMessageSignatureProtocol @optional #define GPB_MESSAGE_SIGNATURE_ENTRY(TYPE, NAME) \ -(TYPE)get##NAME; \ -(void)set##NAME : (TYPE)value; \ -(TYPE)get##NAME##AtIndex : (NSUInteger)index; GPB_MESSAGE_SIGNATURE_ENTRY(BOOL, Bool) GPB_MESSAGE_SIGNATURE_ENTRY(uint32_t, Fixed32) GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, SFixed32) GPB_MESSAGE_SIGNATURE_ENTRY(float, Float) GPB_MESSAGE_SIGNATURE_ENTRY(uint64_t, Fixed64) GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, SFixed64) GPB_MESSAGE_SIGNATURE_ENTRY(double, Double) GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, Int32) GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, Int64) GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, SInt32) GPB_MESSAGE_SIGNATURE_ENTRY(int64_t, SInt64) GPB_MESSAGE_SIGNATURE_ENTRY(uint32_t, UInt32) GPB_MESSAGE_SIGNATURE_ENTRY(uint64_t, UInt64) GPB_MESSAGE_SIGNATURE_ENTRY(NSData *, Bytes) GPB_MESSAGE_SIGNATURE_ENTRY(NSString *, String) GPB_MESSAGE_SIGNATURE_ENTRY(GPBMessage *, Message) GPB_MESSAGE_SIGNATURE_ENTRY(GPBMessage *, Group) GPB_MESSAGE_SIGNATURE_ENTRY(int32_t, Enum) #undef GPB_MESSAGE_SIGNATURE_ENTRY - (id)getArray; - (NSUInteger)getArrayCount; - (void)setArray:(NSArray *)array; + (id)getClassValue; @end CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBWellKnownTypes.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #import #import #else #import "google/protobuf/Any.pbobjc.h" #import "google/protobuf/Duration.pbobjc.h" #import "google/protobuf/Timestamp.pbobjc.h" #endif NS_ASSUME_NONNULL_BEGIN #pragma mark - Errors /** NSError domain used for errors. */ extern NSString *const GPBWellKnownTypesErrorDomain; /** Error code for NSError with GPBWellKnownTypesErrorDomain. */ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { /** The type_url could not be computed for the requested GPBMessage class. */ GPBWellKnownTypesErrorCodeFailedToComputeTypeURL = -100, /** type_url in a Any doesn’t match that of the requested GPBMessage class. */ GPBWellKnownTypesErrorCodeTypeURLMismatch = -101, }; #pragma mark - GPBTimestamp /** * Category for GPBTimestamp to work with standard Foundation time/date types. **/ @interface GPBTimestamp (GBPWellKnownTypes) /** The NSDate representation of this GPBTimestamp. */ @property(nonatomic, readwrite, strong) NSDate *date; /** * The NSTimeInterval representation of this GPBTimestamp. * * @note: Not all second/nanos combinations can be represented in a * NSTimeInterval, so getting this could be a lossy transform. **/ @property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970; /** * Initializes a GPBTimestamp with the given NSDate. * * @param date The date to configure the GPBTimestamp with. * * @return A newly initialized GPBTimestamp. **/ - (instancetype)initWithDate:(NSDate *)date; /** * Initializes a GPBTimestamp with the given NSTimeInterval. * * @param timeIntervalSince1970 Time interval to configure the GPBTimestamp with. * * @return A newly initialized GPBTimestamp. **/ - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970; @end #pragma mark - GPBDuration /** * Category for GPBDuration to work with standard Foundation time type. **/ @interface GPBDuration (GBPWellKnownTypes) /** * The NSTimeInterval representation of this GPBDuration. * * @note: Not all second/nanos combinations can be represented in a * NSTimeInterval, so getting this could be a lossy transform. **/ @property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970; /** * Initializes a GPBDuration with the given NSTimeInterval. * * @param timeIntervalSince1970 Time interval to configure the GPBDuration with. * * @return A newly initialized GPBDuration. **/ - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970; @end #pragma mark - GPBAny /** * Category for GPBAny to help work with the message within the object. **/ @interface GPBAny (GBPWellKnownTypes) /** * Convenience method to create a GPBAny containing the serialized message. * This uses type.googleapis.com/ as the type_url's prefix. * * @param message The message to be packed into the GPBAny. * @param errorPtr Pointer to an error that will be populated if something goes * wrong. * * @return A newly configured GPBAny with the given message, or nil on failure. */ + (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Convenience method to create a GPBAny containing the serialized message. * * @param message The message to be packed into the GPBAny. * @param typeURLPrefix The URL prefix to apply for type_url. * @param errorPtr Pointer to an error that will be populated if something * goes wrong. * * @return A newly configured GPBAny with the given message, or nil on failure. */ + (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message typeURLPrefix:(nonnull NSString *)typeURLPrefix error:(NSError **)errorPtr; /** * Initializes a GPBAny to contain the serialized message. This uses * type.googleapis.com/ as the type_url's prefix. * * @param message The message to be packed into the GPBAny. * @param errorPtr Pointer to an error that will be populated if something goes * wrong. * * @return A newly configured GPBAny with the given message, or nil on failure. */ - (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Initializes a GPBAny to contain the serialized message. * * @param message The message to be packed into the GPBAny. * @param typeURLPrefix The URL prefix to apply for type_url. * @param errorPtr Pointer to an error that will be populated if something * goes wrong. * * @return A newly configured GPBAny with the given message, or nil on failure. */ - (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message typeURLPrefix:(nonnull NSString *)typeURLPrefix error:(NSError **)errorPtr; /** * Packs the serialized message into this GPBAny. This uses * type.googleapis.com/ as the type_url's prefix. * * @param message The message to be packed into the GPBAny. * @param errorPtr Pointer to an error that will be populated if something goes * wrong. * * @return Whether the packing was successful or not. */ - (BOOL)packWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Packs the serialized message into this GPBAny. * * @param message The message to be packed into the GPBAny. * @param typeURLPrefix The URL prefix to apply for type_url. * @param errorPtr Pointer to an error that will be populated if something * goes wrong. * * @return Whether the packing was successful or not. */ - (BOOL)packWithMessage:(nonnull GPBMessage *)message typeURLPrefix:(nonnull NSString *)typeURLPrefix error:(NSError **)errorPtr; /** * Unpacks the serialized message as if it was an instance of the given class. * * @note When checking type_url, the base URL is not checked, only the fully * qualified name. * * @param messageClass The class to use to deserialize the contained message. * @param errorPtr Pointer to an error that will be populated if something * goes wrong. * * @return An instance of the given class populated with the contained data, or * nil on failure. */ - (nullable GPBMessage *)unpackMessageClass:(Class)messageClass error:(NSError **)errorPtr; @end NS_ASSUME_NONNULL_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBWellKnownTypes.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Importing sources here to force the linker to include our category methods in // the static library. If these were compiled separately, the category methods // below would be stripped by the linker. #import "GPBWellKnownTypes.h" #import "GPBUtilities_PackagePrivate.h" NSString *const GPBWellKnownTypesErrorDomain = GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain); static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/"; static NSTimeInterval TimeIntervalSince1970FromSecondsAndNanos(int64_t seconds, int32_t nanos) { return seconds + (NSTimeInterval)nanos / 1e9; } static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time, int64_t *outSeconds) { NSTimeInterval seconds; NSTimeInterval nanos = modf(time, &seconds); nanos *= 1e9; *outSeconds = (int64_t)seconds; return (int32_t)nanos; } static NSString *BuildTypeURL(NSString *typeURLPrefix, NSString *fullName) { if (typeURLPrefix.length == 0) { return fullName; } if ([typeURLPrefix hasSuffix:@"/"]) { return [typeURLPrefix stringByAppendingString:fullName]; } return [NSString stringWithFormat:@"%@/%@", typeURLPrefix, fullName]; } static NSString *ParseTypeFromURL(NSString *typeURLString) { NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch]; if ((range.location == NSNotFound) || (NSMaxRange(range) == typeURLString.length)) { return nil; } NSString *result = [typeURLString substringFromIndex:range.location + 1]; return result; } #pragma mark - GPBTimestamp @implementation GPBTimestamp (GBPWellKnownTypes) - (instancetype)initWithDate:(NSDate *)date { return [self initWithTimeIntervalSince1970:date.timeIntervalSince1970]; } - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { if ((self = [super init])) { int64_t seconds; int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970( timeIntervalSince1970, &seconds); self.seconds = seconds; self.nanos = nanos; } return self; } - (NSDate *)date { return [NSDate dateWithTimeIntervalSince1970:self.timeIntervalSince1970]; } - (void)setDate:(NSDate *)date { self.timeIntervalSince1970 = date.timeIntervalSince1970; } - (NSTimeInterval)timeIntervalSince1970 { return TimeIntervalSince1970FromSecondsAndNanos(self.seconds, self.nanos); } - (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { int64_t seconds; int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970(timeIntervalSince1970, &seconds); self.seconds = seconds; self.nanos = nanos; } @end #pragma mark - GPBDuration @implementation GPBDuration (GBPWellKnownTypes) - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { if ((self = [super init])) { int64_t seconds; int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970( timeIntervalSince1970, &seconds); self.seconds = seconds; self.nanos = nanos; } return self; } - (NSTimeInterval)timeIntervalSince1970 { return TimeIntervalSince1970FromSecondsAndNanos(self.seconds, self.nanos); } - (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { int64_t seconds; int32_t nanos = SecondsAndNanosFromTimeIntervalSince1970(timeIntervalSince1970, &seconds); self.seconds = seconds; self.nanos = nanos; } @end #pragma mark - GPBAny @implementation GPBAny (GBPWellKnownTypes) + (instancetype)anyWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { return [self anyWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } + (instancetype)anyWithMessage:(GPBMessage *)message typeURLPrefix:(NSString *)typeURLPrefix error:(NSError **)errorPtr { return [[[self alloc] initWithMessage:message typeURLPrefix:typeURLPrefix error:errorPtr] autorelease]; } - (instancetype)initWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { return [self initWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } - (instancetype)initWithMessage:(GPBMessage *)message typeURLPrefix:(NSString *)typeURLPrefix error:(NSError **)errorPtr { self = [self init]; if (self) { if (![self packWithMessage:message typeURLPrefix:typeURLPrefix error:errorPtr]) { [self release]; self = nil; } } return self; } - (BOOL)packWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { return [self packWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } - (BOOL)packWithMessage:(GPBMessage *)message typeURLPrefix:(NSString *)typeURLPrefix error:(NSError **)errorPtr { NSString *fullName = [message descriptor].fullName; if (fullName.length == 0) { if (errorPtr) { *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL userInfo:nil]; } return NO; } if (errorPtr) { *errorPtr = nil; } self.typeURL = BuildTypeURL(typeURLPrefix, fullName); self.value = message.data; return YES; } - (GPBMessage *)unpackMessageClass:(Class)messageClass error:(NSError **)errorPtr { NSString *fullName = [messageClass descriptor].fullName; if (fullName.length == 0) { if (errorPtr) { *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL userInfo:nil]; } return nil; } NSString *expectedFullName = ParseTypeFromURL(self.typeURL); if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) { if (errorPtr) { *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain code:GPBWellKnownTypesErrorCodeTypeURLMismatch userInfo:nil]; } return nil; } // Any is proto3, which means no extensions, so this assumes anything put // within an any also won't need extensions. A second helper could be added // if needed. return [messageClass parseFromData:self.value error:errorPtr]; } @end ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBWireFormat.h ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBRuntimeTypes.h" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN typedef enum { GPBWireFormatVarint = 0, GPBWireFormatFixed64 = 1, GPBWireFormatLengthDelimited = 2, GPBWireFormatStartGroup = 3, GPBWireFormatEndGroup = 4, GPBWireFormatFixed32 = 5, } GPBWireFormat; enum { GPBWireFormatMessageSetItem = 1, GPBWireFormatMessageSetTypeId = 2, GPBWireFormatMessageSetMessage = 3 }; uint32_t GPBWireFormatMakeTag(uint32_t fieldNumber, GPBWireFormat wireType) __attribute__((const)); GPBWireFormat GPBWireFormatGetTagWireType(uint32_t tag) __attribute__((const)); uint32_t GPBWireFormatGetTagFieldNumber(uint32_t tag) __attribute__((const)); BOOL GPBWireFormatIsValidTag(uint32_t tag) __attribute__((const)); GPBWireFormat GPBWireFormatForType(GPBDataType dataType, BOOL isPacked) __attribute__((const)); #define GPBWireFormatMessageSetItemTag \ (GPBWireFormatMakeTag(GPBWireFormatMessageSetItem, GPBWireFormatStartGroup)) #define GPBWireFormatMessageSetItemEndTag \ (GPBWireFormatMakeTag(GPBWireFormatMessageSetItem, GPBWireFormatEndGroup)) #define GPBWireFormatMessageSetTypeIdTag \ (GPBWireFormatMakeTag(GPBWireFormatMessageSetTypeId, GPBWireFormatVarint)) #define GPBWireFormatMessageSetMessageTag \ (GPBWireFormatMakeTag(GPBWireFormatMessageSetMessage, \ GPBWireFormatLengthDelimited)) NS_ASSUME_NONNULL_END CF_EXTERN_C_END ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/GPBWireFormat.m ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "GPBWireFormat.h" #import "GPBUtilities_PackagePrivate.h" enum { GPBWireFormatTagTypeBits = 3, GPBWireFormatTagTypeMask = 7 /* = (1 << GPBWireFormatTagTypeBits) - 1 */, }; uint32_t GPBWireFormatMakeTag(uint32_t fieldNumber, GPBWireFormat wireType) { return (fieldNumber << GPBWireFormatTagTypeBits) | wireType; } GPBWireFormat GPBWireFormatGetTagWireType(uint32_t tag) { return (GPBWireFormat)(tag & GPBWireFormatTagTypeMask); } uint32_t GPBWireFormatGetTagFieldNumber(uint32_t tag) { return GPBLogicalRightShift32(tag, GPBWireFormatTagTypeBits); } BOOL GPBWireFormatIsValidTag(uint32_t tag) { uint32_t formatBits = (tag & GPBWireFormatTagTypeMask); // The valid GPBWireFormat* values are 0-5, anything else is not a valid tag. BOOL result = (formatBits <= 5); return result; } GPBWireFormat GPBWireFormatForType(GPBDataType type, BOOL isPacked) { if (isPacked) { return GPBWireFormatLengthDelimited; } static const GPBWireFormat format[GPBDataType_Count] = { GPBWireFormatVarint, // GPBDataTypeBool GPBWireFormatFixed32, // GPBDataTypeFixed32 GPBWireFormatFixed32, // GPBDataTypeSFixed32 GPBWireFormatFixed32, // GPBDataTypeFloat GPBWireFormatFixed64, // GPBDataTypeFixed64 GPBWireFormatFixed64, // GPBDataTypeSFixed64 GPBWireFormatFixed64, // GPBDataTypeDouble GPBWireFormatVarint, // GPBDataTypeInt32 GPBWireFormatVarint, // GPBDataTypeInt64 GPBWireFormatVarint, // GPBDataTypeSInt32 GPBWireFormatVarint, // GPBDataTypeSInt64 GPBWireFormatVarint, // GPBDataTypeUInt32 GPBWireFormatVarint, // GPBDataTypeUInt64 GPBWireFormatLengthDelimited, // GPBDataTypeBytes GPBWireFormatLengthDelimited, // GPBDataTypeString GPBWireFormatLengthDelimited, // GPBDataTypeMessage GPBWireFormatStartGroup, // GPBDataTypeGroup GPBWireFormatVarint // GPBDataTypeEnum }; return format[type]; } ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBAnyRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBAnyRoot : GPBRootObject @end #pragma mark - GPBAny typedef GPB_ENUM(GPBAny_FieldNumber) { GPBAny_FieldNumber_TypeURL = 1, GPBAny_FieldNumber_Value = 2, }; /** * `Any` contains an arbitrary serialized protocol buffer message along with a * URL that describes the type of the serialized message. * * Protobuf library provides support to pack/unpack Any values in the form * of utility functions or additional generated methods of the Any type. * * Example 1: Pack and unpack a message in C++. * * Foo foo = ...; * Any any; * any.PackFrom(foo); * ... * if (any.UnpackTo(&foo)) { * ... * } * * Example 2: Pack and unpack a message in Java. * * Foo foo = ...; * Any any = Any.pack(foo); * ... * if (any.is(Foo.class)) { * foo = any.unpack(Foo.class); * } * * Example 3: Pack and unpack a message in Python. * * foo = Foo(...) * any = Any() * any.Pack(foo) * ... * if any.Is(Foo.DESCRIPTOR): * any.Unpack(foo) * ... * * The pack methods provided by protobuf library will by default use * 'type.googleapis.com/full.type.name' as the type URL and the unpack * methods only use the fully qualified type name after the last '/' * in the type URL, for example "foo.bar.com/x/y.z" will yield type * name "y.z". * * * JSON * ==== * The JSON representation of an `Any` value uses the regular * representation of the deserialized, embedded message, with an * additional field `\@type` which contains the type URL. Example: * * package google.profile; * message Person { * string first_name = 1; * string last_name = 2; * } * * { * "\@type": "type.googleapis.com/google.profile.Person", * "firstName": , * "lastName": * } * * If the embedded message type is well-known and has a custom JSON * representation, that representation will be embedded adding a field * `value` which holds the custom JSON in addition to the `\@type` * field. Example (for message [google.protobuf.Duration][]): * * { * "\@type": "type.googleapis.com/google.protobuf.Duration", * "value": "1.212s" * } **/ @interface GPBAny : GPBMessage /** * A URL/resource name whose content describes the type of the * serialized protocol buffer message. * * For URLs which use the scheme `http`, `https`, or no scheme, the * following restrictions and interpretations apply: * * * If no scheme is provided, `https` is assumed. * * The last segment of the URL's path must represent the fully * qualified name of the type (as in `path/google.protobuf.Duration`). * The name should be in a canonical form (e.g., leading "." is * not accepted). * * An HTTP GET on the URL must yield a [google.protobuf.Type][] * value in binary format, or produce an error. * * Applications are allowed to cache lookup results based on the * URL, or have them precompiled into a binary to avoid any * lookup. Therefore, binary compatibility needs to be preserved * on changes to types. (Use versioned type names to manage * breaking changes.) * * Schemes other than `http`, `https` (or the empty scheme) might be * used with implementation specific semantics. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL; /** Must be a valid serialized protocol buffer of the above specified type. */ @property(nonatomic, readwrite, copy, null_resettable) NSData *value; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Any.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Any.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBAnyRoot @implementation GPBAnyRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBAnyRoot_FileDescriptor static GPBFileDescriptor *GPBAnyRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBAny @implementation GPBAny @dynamic typeURL; @dynamic value; typedef struct GPBAny__storage_ { uint32_t _has_storage_[1]; NSString *typeURL; NSData *value; } GPBAny__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "typeURL", .dataTypeSpecific.className = NULL, .number = GPBAny_FieldNumber_TypeURL, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBAny__storage_, typeURL), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), .dataType = GPBDataTypeString, }, { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBAny_FieldNumber_Value, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBAny__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeBytes, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBAny class] rootClass:[GPBAnyRoot class] file:GPBAnyRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBAny__storage_) flags:GPBDescriptorInitializationFlag_None]; #if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS static const char *extraTextFormatInfo = "\001\001\004\241!!\000"; [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; #endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN @class GPBMethod; @class GPBMixin; @class GPBOption; @class GPBSourceContext; GPB_ENUM_FWD_DECLARE(GPBSyntax); NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBApiRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBApiRoot : GPBRootObject @end #pragma mark - GPBApi typedef GPB_ENUM(GPBApi_FieldNumber) { GPBApi_FieldNumber_Name = 1, GPBApi_FieldNumber_MethodsArray = 2, GPBApi_FieldNumber_OptionsArray = 3, GPBApi_FieldNumber_Version = 4, GPBApi_FieldNumber_SourceContext = 5, GPBApi_FieldNumber_MixinsArray = 6, GPBApi_FieldNumber_Syntax = 7, }; /** * Api is a light-weight descriptor for a protocol buffer service. **/ @interface GPBApi : GPBMessage /** * The fully qualified name of this api, including package name * followed by the api's simple name. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** The methods of this api, in unspecified order. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *methodsArray; /** The number of items in @c methodsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger methodsArray_Count; /** Any metadata attached to the API. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; /** * A version string for this api. If specified, must have the form * `major-version.minor-version`, as in `1.10`. If the minor version * is omitted, it defaults to zero. If the entire version field is * empty, the major version is derived from the package name, as * outlined below. If the field is not empty, the version in the * package name will be verified to be consistent with what is * provided here. * * The versioning schema uses [semantic * versioning](http://semver.org) where the major version number * indicates a breaking change and the minor version an additive, * non-breaking change. Both version numbers are signals to users * what to expect from different versions, and should be carefully * chosen based on the product plan. * * The major version is also reflected in the package name of the * API, which must end in `v`, as in * `google.feature.v1`. For major versions 0 and 1, the suffix can * be omitted. Zero major versions must only be used for * experimental, none-GA apis. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *version; /** * Source context for the protocol buffer service represented by this * message. **/ @property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; /** Test to see if @c sourceContext has been set. */ @property(nonatomic, readwrite) BOOL hasSourceContext; /** Included APIs. See [Mixin][]. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *mixinsArray; /** The number of items in @c mixinsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger mixinsArray_Count; /** The source syntax of the service. */ @property(nonatomic, readwrite) enum GPBSyntax syntax; @end /** * Fetches the raw value of a @c GPBApi's @c syntax property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBApi_Syntax_RawValue(GPBApi *message); /** * Sets the raw value of an @c GPBApi's @c syntax property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value); #pragma mark - GPBMethod typedef GPB_ENUM(GPBMethod_FieldNumber) { GPBMethod_FieldNumber_Name = 1, GPBMethod_FieldNumber_RequestTypeURL = 2, GPBMethod_FieldNumber_RequestStreaming = 3, GPBMethod_FieldNumber_ResponseTypeURL = 4, GPBMethod_FieldNumber_ResponseStreaming = 5, GPBMethod_FieldNumber_OptionsArray = 6, GPBMethod_FieldNumber_Syntax = 7, }; /** * Method represents a method of an api. **/ @interface GPBMethod : GPBMessage /** The simple name of this method. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** A URL of the input message type. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *requestTypeURL; /** If true, the request is streamed. */ @property(nonatomic, readwrite) BOOL requestStreaming; /** The URL of the output message type. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *responseTypeURL; /** If true, the response is streamed. */ @property(nonatomic, readwrite) BOOL responseStreaming; /** Any metadata attached to the method. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; /** The source syntax of this method. */ @property(nonatomic, readwrite) enum GPBSyntax syntax; @end /** * Fetches the raw value of a @c GPBMethod's @c syntax property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBMethod_Syntax_RawValue(GPBMethod *message); /** * Sets the raw value of an @c GPBMethod's @c syntax property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value); #pragma mark - GPBMixin typedef GPB_ENUM(GPBMixin_FieldNumber) { GPBMixin_FieldNumber_Name = 1, GPBMixin_FieldNumber_Root = 2, }; /** * Declares an API to be included in this API. The including API must * redeclare all the methods from the included API, but documentation * and options are inherited as follows: * * - If after comment and whitespace stripping, the documentation * string of the redeclared method is empty, it will be inherited * from the original method. * * - Each annotation belonging to the service config (http, * visibility) which is not set in the redeclared method will be * inherited. * * - If an http annotation is inherited, the path pattern will be * modified as follows. Any version prefix will be replaced by the * version of the including API plus the [root][] path if specified. * * Example of a simple mixin: * * package google.acl.v1; * service AccessControl { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v1/{resource=**}:getAcl"; * } * } * * package google.storage.v2; * service Storage { * rpc GetAcl(GetAclRequest) returns (Acl); * * // Get a data record. * rpc GetData(GetDataRequest) returns (Data) { * option (google.api.http).get = "/v2/{resource=**}"; * } * } * * Example of a mixin configuration: * * apis: * - name: google.storage.v2.Storage * mixins: * - name: google.acl.v1.AccessControl * * The mixin construct implies that all methods in `AccessControl` are * also declared with same name and request/response types in * `Storage`. A documentation generator or annotation processor will * see the effective `Storage.GetAcl` method after inherting * documentation and annotations as follows: * * service Storage { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v2/{resource=**}:getAcl"; * } * ... * } * * Note how the version in the path pattern changed from `v1` to `v2`. * * If the `root` field in the mixin is specified, it should be a * relative path under which inherited HTTP paths are placed. Example: * * apis: * - name: google.storage.v2.Storage * mixins: * - name: google.acl.v1.AccessControl * root: acls * * This implies the following inherited HTTP annotation: * * service Storage { * // Get the underlying ACL object. * rpc GetAcl(GetAclRequest) returns (Acl) { * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; * } * ... * } **/ @interface GPBMixin : GPBMessage /** The fully qualified name of the API which is included. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** * If non-empty specifies a path under which inherited HTTP paths * are rooted. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *root; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Api.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #import #import #else #import "google/protobuf/Api.pbobjc.h" #import "google/protobuf/SourceContext.pbobjc.h" #import "google/protobuf/Type.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBApiRoot @implementation GPBApiRoot // No extensions in the file and none of the imports (direct or indirect) // defined extensions, so no need to generate +extensionRegistry. @end #pragma mark - GPBApiRoot_FileDescriptor static GPBFileDescriptor *GPBApiRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBApi @implementation GPBApi @dynamic name; @dynamic methodsArray, methodsArray_Count; @dynamic optionsArray, optionsArray_Count; @dynamic version; @dynamic hasSourceContext, sourceContext; @dynamic mixinsArray, mixinsArray_Count; @dynamic syntax; typedef struct GPBApi__storage_ { uint32_t _has_storage_[1]; GPBSyntax syntax; NSString *name; NSMutableArray *methodsArray; NSMutableArray *optionsArray; NSString *version; GPBSourceContext *sourceContext; NSMutableArray *mixinsArray; } GPBApi__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBApi_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBApi__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "methodsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBMethod), .number = GPBApi_FieldNumber_MethodsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBApi__storage_, methodsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBApi_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBApi__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "version", .dataTypeSpecific.className = NULL, .number = GPBApi_FieldNumber_Version, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBApi__storage_, version), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "sourceContext", .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), .number = GPBApi_FieldNumber_SourceContext, .hasIndex = 2, .offset = (uint32_t)offsetof(GPBApi__storage_, sourceContext), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, { .name = "mixinsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBMixin), .number = GPBApi_FieldNumber_MixinsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBApi__storage_, mixinsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "syntax", .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, .number = GPBApi_FieldNumber_Syntax, .hasIndex = 3, .offset = (uint32_t)offsetof(GPBApi__storage_, syntax), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBApi class] rootClass:[GPBApiRoot class] file:GPBApiRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBApi__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBApi_Syntax_RawValue(GPBApi *message) { GPBDescriptor *descriptor = [GPBApi descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax]; return GPBGetMessageInt32Field(message, field); } void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value) { GPBDescriptor *descriptor = [GPBApi descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBApi_FieldNumber_Syntax]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } #pragma mark - GPBMethod @implementation GPBMethod @dynamic name; @dynamic requestTypeURL; @dynamic requestStreaming; @dynamic responseTypeURL; @dynamic responseStreaming; @dynamic optionsArray, optionsArray_Count; @dynamic syntax; typedef struct GPBMethod__storage_ { uint32_t _has_storage_[1]; GPBSyntax syntax; NSString *name; NSString *requestTypeURL; NSString *responseTypeURL; NSMutableArray *optionsArray; } GPBMethod__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBMethod_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBMethod__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "requestTypeURL", .dataTypeSpecific.className = NULL, .number = GPBMethod_FieldNumber_RequestTypeURL, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBMethod__storage_, requestTypeURL), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), .dataType = GPBDataTypeString, }, { .name = "requestStreaming", .dataTypeSpecific.className = NULL, .number = GPBMethod_FieldNumber_RequestStreaming, .hasIndex = 2, .offset = 3, // Stored in _has_storage_ to save space. .flags = GPBFieldOptional, .dataType = GPBDataTypeBool, }, { .name = "responseTypeURL", .dataTypeSpecific.className = NULL, .number = GPBMethod_FieldNumber_ResponseTypeURL, .hasIndex = 4, .offset = (uint32_t)offsetof(GPBMethod__storage_, responseTypeURL), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), .dataType = GPBDataTypeString, }, { .name = "responseStreaming", .dataTypeSpecific.className = NULL, .number = GPBMethod_FieldNumber_ResponseStreaming, .hasIndex = 5, .offset = 6, // Stored in _has_storage_ to save space. .flags = GPBFieldOptional, .dataType = GPBDataTypeBool, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBMethod_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBMethod__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "syntax", .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, .number = GPBMethod_FieldNumber_Syntax, .hasIndex = 7, .offset = (uint32_t)offsetof(GPBMethod__storage_, syntax), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBMethod class] rootClass:[GPBApiRoot class] file:GPBApiRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBMethod__storage_) flags:GPBDescriptorInitializationFlag_None]; #if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS static const char *extraTextFormatInfo = "\002\002\007\244\241!!\000\004\010\244\241!!\000"; [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; #endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBMethod_Syntax_RawValue(GPBMethod *message) { GPBDescriptor *descriptor = [GPBMethod descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax]; return GPBGetMessageInt32Field(message, field); } void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value) { GPBDescriptor *descriptor = [GPBMethod descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBMethod_FieldNumber_Syntax]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } #pragma mark - GPBMixin @implementation GPBMixin @dynamic name; @dynamic root; typedef struct GPBMixin__storage_ { uint32_t _has_storage_[1]; NSString *name; NSString *root; } GPBMixin__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBMixin_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBMixin__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "root", .dataTypeSpecific.className = NULL, .number = GPBMixin_FieldNumber_Root, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBMixin__storage_, root), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBMixin class] rootClass:[GPBApiRoot class] file:GPBApiRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBMixin__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBDurationRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBDurationRoot : GPBRootObject @end #pragma mark - GPBDuration typedef GPB_ENUM(GPBDuration_FieldNumber) { GPBDuration_FieldNumber_Seconds = 1, GPBDuration_FieldNumber_Nanos = 2, }; /** * A Duration represents a signed, fixed-length span of time represented * as a count of seconds and fractions of seconds at nanosecond * resolution. It is independent of any calendar and concepts like "day" * or "month". It is related to Timestamp in that the difference between * two Timestamp values is a Duration and it can be added or subtracted * from a Timestamp. Range is approximately +-10,000 years. * * Example 1: Compute Duration from two Timestamps in pseudo code. * * Timestamp start = ...; * Timestamp end = ...; * Duration duration = ...; * * duration.seconds = end.seconds - start.seconds; * duration.nanos = end.nanos - start.nanos; * * if (duration.seconds < 0 && duration.nanos > 0) { * duration.seconds += 1; * duration.nanos -= 1000000000; * } else if (durations.seconds > 0 && duration.nanos < 0) { * duration.seconds -= 1; * duration.nanos += 1000000000; * } * * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. * * Timestamp start = ...; * Duration duration = ...; * Timestamp end = ...; * * end.seconds = start.seconds + duration.seconds; * end.nanos = start.nanos + duration.nanos; * * if (end.nanos < 0) { * end.seconds -= 1; * end.nanos += 1000000000; * } else if (end.nanos >= 1000000000) { * end.seconds += 1; * end.nanos -= 1000000000; * } * * Example 3: Compute Duration from datetime.timedelta in Python. * * td = datetime.timedelta(days=3, minutes=10) * duration = Duration() * duration.FromTimedelta(td) **/ @interface GPBDuration : GPBMessage /** * Signed seconds of the span of time. Must be from -315,576,000,000 * to +315,576,000,000 inclusive. **/ @property(nonatomic, readwrite) int64_t seconds; /** * Signed fractions of a second at nanosecond resolution of the span * of time. Durations less than one second are represented with a 0 * `seconds` field and a positive or negative `nanos` field. For durations * of one second or more, a non-zero value for the `nanos` field must be * of the same sign as the `seconds` field. Must be from -999,999,999 * to +999,999,999 inclusive. **/ @property(nonatomic, readwrite) int32_t nanos; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Duration.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Duration.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBDurationRoot @implementation GPBDurationRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBDurationRoot_FileDescriptor static GPBFileDescriptor *GPBDurationRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBDuration @implementation GPBDuration @dynamic seconds; @dynamic nanos; typedef struct GPBDuration__storage_ { uint32_t _has_storage_[1]; int32_t nanos; int64_t seconds; } GPBDuration__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "seconds", .dataTypeSpecific.className = NULL, .number = GPBDuration_FieldNumber_Seconds, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBDuration__storage_, seconds), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt64, }, { .name = "nanos", .dataTypeSpecific.className = NULL, .number = GPBDuration_FieldNumber_Nanos, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBDuration__storage_, nanos), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBDuration class] rootClass:[GPBDurationRoot class] file:GPBDurationRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBDuration__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBEmptyRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBEmptyRoot : GPBRootObject @end #pragma mark - GPBEmpty /** * A generic empty message that you can re-use to avoid defining duplicated * empty messages in your APIs. A typical example is to use it as the request * or the response type of an API method. For instance: * * service Foo { * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); * } * * The JSON representation for `Empty` is empty JSON object `{}`. **/ @interface GPBEmpty : GPBMessage @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Empty.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Empty.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBEmptyRoot @implementation GPBEmptyRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBEmptyRoot_FileDescriptor static GPBFileDescriptor *GPBEmptyRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBEmpty @implementation GPBEmpty typedef struct GPBEmpty__storage_ { uint32_t _has_storage_[1]; } GPBEmpty__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBEmpty class] rootClass:[GPBEmptyRoot class] file:GPBEmptyRoot_FileDescriptor() fields:NULL fieldCount:0 storageSize:sizeof(GPBEmpty__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBFieldMaskRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBFieldMaskRoot : GPBRootObject @end #pragma mark - GPBFieldMask typedef GPB_ENUM(GPBFieldMask_FieldNumber) { GPBFieldMask_FieldNumber_PathsArray = 1, }; /** * `FieldMask` represents a set of symbolic field paths, for example: * * paths: "f.a" * paths: "f.b.d" * * Here `f` represents a field in some root message, `a` and `b` * fields in the message found in `f`, and `d` a field found in the * message in `f.b`. * * Field masks are used to specify a subset of fields that should be * returned by a get operation or modified by an update operation. * Field masks also have a custom JSON encoding (see below). * * # Field Masks in Projections * * When used in the context of a projection, a response message or * sub-message is filtered by the API to only contain those fields as * specified in the mask. For example, if the mask in the previous * example is applied to a response message as follows: * * f { * a : 22 * b { * d : 1 * x : 2 * } * y : 13 * } * z: 8 * * The result will not contain specific values for fields x,y and z * (their value will be set to the default, and omitted in proto text * output): * * * f { * a : 22 * b { * d : 1 * } * } * * A repeated field is not allowed except at the last position of a * paths string. * * If a FieldMask object is not present in a get operation, the * operation applies to all fields (as if a FieldMask of all fields * had been specified). * * Note that a field mask does not necessarily apply to the * top-level response message. In case of a REST get operation, the * field mask applies directly to the response, but in case of a REST * list operation, the mask instead applies to each individual message * in the returned resource list. In case of a REST custom method, * other definitions may be used. Where the mask applies will be * clearly documented together with its declaration in the API. In * any case, the effect on the returned resource/resources is required * behavior for APIs. * * # Field Masks in Update Operations * * A field mask in update operations specifies which fields of the * targeted resource are going to be updated. The API is required * to only change the values of the fields as specified in the mask * and leave the others untouched. If a resource is passed in to * describe the updated values, the API ignores the values of all * fields not covered by the mask. * * If a repeated field is specified for an update operation, the existing * repeated values in the target resource will be overwritten by the new values. * Note that a repeated field is only allowed in the last position of a `paths` * string. * * If a sub-message is specified in the last position of the field mask for an * update operation, then the existing sub-message in the target resource is * overwritten. Given the target message: * * f { * b { * d : 1 * x : 2 * } * c : 1 * } * * And an update message: * * f { * b { * d : 10 * } * } * * then if the field mask is: * * paths: "f.b" * * then the result will be: * * f { * b { * d : 10 * } * c : 1 * } * * However, if the update mask was: * * paths: "f.b.d" * * then the result would be: * * f { * b { * d : 10 * x : 2 * } * c : 1 * } * * In order to reset a field's value to the default, the field must * be in the mask and set to the default value in the provided resource. * Hence, in order to reset all fields of a resource, provide a default * instance of the resource and set all fields in the mask, or do * not provide a mask as described below. * * If a field mask is not present on update, the operation applies to * all fields (as if a field mask of all fields has been specified). * Note that in the presence of schema evolution, this may mean that * fields the client does not know and has therefore not filled into * the request will be reset to their default. If this is unwanted * behavior, a specific service may require a client to always specify * a field mask, producing an error if not. * * As with get operations, the location of the resource which * describes the updated values in the request message depends on the * operation kind. In any case, the effect of the field mask is * required to be honored by the API. * * ## Considerations for HTTP REST * * The HTTP kind of an update operation which uses a field mask must * be set to PATCH instead of PUT in order to satisfy HTTP semantics * (PUT must only be used for full updates). * * # JSON Encoding of Field Masks * * In JSON, a field mask is encoded as a single string where paths are * separated by a comma. Fields name in each path are converted * to/from lower-camel naming conventions. * * As an example, consider the following message declarations: * * message Profile { * User user = 1; * Photo photo = 2; * } * message User { * string display_name = 1; * string address = 2; * } * * In proto a field mask for `Profile` may look as such: * * mask { * paths: "user.display_name" * paths: "photo" * } * * In JSON, the same mask is represented as below: * * { * mask: "user.displayName,photo" * } * * # Field Masks and Oneof Fields * * Field masks treat fields in oneofs just as regular fields. Consider the * following message: * * message SampleMessage { * oneof test_oneof { * string name = 4; * SubMessage sub_message = 9; * } * } * * The field mask can be: * * mask { * paths: "name" * } * * Or: * * mask { * paths: "sub_message" * } * * Note that oneof type names ("test_oneof" in this case) cannot be used in * paths. **/ @interface GPBFieldMask : GPBMessage /** The set of field mask paths. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *pathsArray; /** The number of items in @c pathsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger pathsArray_Count; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/FieldMask.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/FieldMask.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBFieldMaskRoot @implementation GPBFieldMaskRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBFieldMaskRoot_FileDescriptor static GPBFileDescriptor *GPBFieldMaskRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBFieldMask @implementation GPBFieldMask @dynamic pathsArray, pathsArray_Count; typedef struct GPBFieldMask__storage_ { uint32_t _has_storage_[1]; NSMutableArray *pathsArray; } GPBFieldMask__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "pathsArray", .dataTypeSpecific.className = NULL, .number = GPBFieldMask_FieldNumber_PathsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBFieldMask__storage_, pathsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeString, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBFieldMask class] rootClass:[GPBFieldMaskRoot class] file:GPBFieldMaskRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBFieldMask__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBSourceContextRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBSourceContextRoot : GPBRootObject @end #pragma mark - GPBSourceContext typedef GPB_ENUM(GPBSourceContext_FieldNumber) { GPBSourceContext_FieldNumber_FileName = 1, }; /** * `SourceContext` represents information about the source of a * protobuf element, like the file in which it is defined. **/ @interface GPBSourceContext : GPBMessage /** * The path-qualified name of the .proto file that contained the associated * protobuf element. For example: `"google/protobuf/source_context.proto"`. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *fileName; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/SourceContext.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/SourceContext.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBSourceContextRoot @implementation GPBSourceContextRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBSourceContextRoot_FileDescriptor static GPBFileDescriptor *GPBSourceContextRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBSourceContext @implementation GPBSourceContext @dynamic fileName; typedef struct GPBSourceContext__storage_ { uint32_t _has_storage_[1]; NSString *fileName; } GPBSourceContext__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "fileName", .dataTypeSpecific.className = NULL, .number = GPBSourceContext_FieldNumber_FileName, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBSourceContext__storage_, fileName), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBSourceContext class] rootClass:[GPBSourceContextRoot class] file:GPBSourceContextRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBSourceContext__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN @class GPBListValue; @class GPBStruct; @class GPBValue; NS_ASSUME_NONNULL_BEGIN #pragma mark - Enum GPBNullValue /** * `NullValue` is a singleton enumeration to represent the null value for the * `Value` type union. * * The JSON representation for `NullValue` is JSON `null`. **/ typedef GPB_ENUM(GPBNullValue) { /** * Value used if any message's field encounters a value that is not defined * by this enum. The message will also have C functions to get/set the rawValue * of the field. **/ GPBNullValue_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, /** Null value. */ GPBNullValue_NullValue = 0, }; GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void); /** * Checks to see if the given value is defined by the enum or was not known at * the time this source was generated. **/ BOOL GPBNullValue_IsValidValue(int32_t value); #pragma mark - GPBStructRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBStructRoot : GPBRootObject @end #pragma mark - GPBStruct typedef GPB_ENUM(GPBStruct_FieldNumber) { GPBStruct_FieldNumber_Fields = 1, }; /** * `Struct` represents a structured data value, consisting of fields * which map to dynamically typed values. In some languages, `Struct` * might be supported by a native representation. For example, in * scripting languages like JS a struct is represented as an * object. The details of that representation are described together * with the proto support for the language. * * The JSON representation for `Struct` is JSON object. **/ @interface GPBStruct : GPBMessage /** Unordered map of dynamically typed values. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableDictionary *fields; /** The number of items in @c fields without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger fields_Count; @end #pragma mark - GPBValue typedef GPB_ENUM(GPBValue_FieldNumber) { GPBValue_FieldNumber_NullValue = 1, GPBValue_FieldNumber_NumberValue = 2, GPBValue_FieldNumber_StringValue = 3, GPBValue_FieldNumber_BoolValue = 4, GPBValue_FieldNumber_StructValue = 5, GPBValue_FieldNumber_ListValue = 6, }; typedef GPB_ENUM(GPBValue_Kind_OneOfCase) { GPBValue_Kind_OneOfCase_GPBUnsetOneOfCase = 0, GPBValue_Kind_OneOfCase_NullValue = 1, GPBValue_Kind_OneOfCase_NumberValue = 2, GPBValue_Kind_OneOfCase_StringValue = 3, GPBValue_Kind_OneOfCase_BoolValue = 4, GPBValue_Kind_OneOfCase_StructValue = 5, GPBValue_Kind_OneOfCase_ListValue = 6, }; /** * `Value` represents a dynamically typed value which can be either * null, a number, a string, a boolean, a recursive struct value, or a * list of values. A producer of value is expected to set one of that * variants, absence of any variant indicates an error. * * The JSON representation for `Value` is JSON value. **/ @interface GPBValue : GPBMessage /** The kind of value. */ @property(nonatomic, readonly) GPBValue_Kind_OneOfCase kindOneOfCase; /** Represents a null value. */ @property(nonatomic, readwrite) GPBNullValue nullValue; /** Represents a double value. */ @property(nonatomic, readwrite) double numberValue; /** Represents a string value. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *stringValue; /** Represents a boolean value. */ @property(nonatomic, readwrite) BOOL boolValue; /** Represents a structured value. */ @property(nonatomic, readwrite, strong, null_resettable) GPBStruct *structValue; /** Represents a repeated `Value`. */ @property(nonatomic, readwrite, strong, null_resettable) GPBListValue *listValue; @end /** * Fetches the raw value of a @c GPBValue's @c nullValue property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBValue_NullValue_RawValue(GPBValue *message); /** * Sets the raw value of an @c GPBValue's @c nullValue property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value); /** * Clears whatever value was set for the oneof 'kind'. **/ void GPBValue_ClearKindOneOfCase(GPBValue *message); #pragma mark - GPBListValue typedef GPB_ENUM(GPBListValue_FieldNumber) { GPBListValue_FieldNumber_ValuesArray = 1, }; /** * `ListValue` is a wrapper around a repeated field of values. * * The JSON representation for `ListValue` is JSON array. **/ @interface GPBListValue : GPBMessage /** Repeated field of dynamically typed values. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *valuesArray; /** The number of items in @c valuesArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger valuesArray_Count; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Struct.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Struct.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma clang diagnostic ignored "-Wdirect-ivar-access" #pragma mark - GPBStructRoot @implementation GPBStructRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBStructRoot_FileDescriptor static GPBFileDescriptor *GPBStructRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - Enum GPBNullValue GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void) { static GPBEnumDescriptor *descriptor = NULL; if (!descriptor) { static const char *valueNames = "NullValue\000"; static const int32_t values[] = { GPBNullValue_NullValue, }; GPBEnumDescriptor *worker = [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBNullValue) valueNames:valueNames values:values count:(uint32_t)(sizeof(values) / sizeof(int32_t)) enumVerifier:GPBNullValue_IsValidValue]; if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { [worker release]; } } return descriptor; } BOOL GPBNullValue_IsValidValue(int32_t value__) { switch (value__) { case GPBNullValue_NullValue: return YES; default: return NO; } } #pragma mark - GPBStruct @implementation GPBStruct @dynamic fields, fields_Count; typedef struct GPBStruct__storage_ { uint32_t _has_storage_[1]; NSMutableDictionary *fields; } GPBStruct__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "fields", .dataTypeSpecific.className = GPBStringifySymbol(GPBValue), .number = GPBStruct_FieldNumber_Fields, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBStruct__storage_, fields), .flags = GPBFieldMapKeyString, .dataType = GPBDataTypeMessage, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBStruct class] rootClass:[GPBStructRoot class] file:GPBStructRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBStruct__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBValue @implementation GPBValue @dynamic kindOneOfCase; @dynamic nullValue; @dynamic numberValue; @dynamic stringValue; @dynamic boolValue; @dynamic structValue; @dynamic listValue; typedef struct GPBValue__storage_ { uint32_t _has_storage_[2]; GPBNullValue nullValue; NSString *stringValue; GPBStruct *structValue; GPBListValue *listValue; double numberValue; } GPBValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "nullValue", .dataTypeSpecific.enumDescFunc = GPBNullValue_EnumDescriptor, .number = GPBValue_FieldNumber_NullValue, .hasIndex = -1, .offset = (uint32_t)offsetof(GPBValue__storage_, nullValue), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, { .name = "numberValue", .dataTypeSpecific.className = NULL, .number = GPBValue_FieldNumber_NumberValue, .hasIndex = -1, .offset = (uint32_t)offsetof(GPBValue__storage_, numberValue), .flags = GPBFieldOptional, .dataType = GPBDataTypeDouble, }, { .name = "stringValue", .dataTypeSpecific.className = NULL, .number = GPBValue_FieldNumber_StringValue, .hasIndex = -1, .offset = (uint32_t)offsetof(GPBValue__storage_, stringValue), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "boolValue", .dataTypeSpecific.className = NULL, .number = GPBValue_FieldNumber_BoolValue, .hasIndex = -1, .offset = 0, // Stored in _has_storage_ to save space. .flags = GPBFieldOptional, .dataType = GPBDataTypeBool, }, { .name = "structValue", .dataTypeSpecific.className = GPBStringifySymbol(GPBStruct), .number = GPBValue_FieldNumber_StructValue, .hasIndex = -1, .offset = (uint32_t)offsetof(GPBValue__storage_, structValue), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, { .name = "listValue", .dataTypeSpecific.className = GPBStringifySymbol(GPBListValue), .number = GPBValue_FieldNumber_ListValue, .hasIndex = -1, .offset = (uint32_t)offsetof(GPBValue__storage_, listValue), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBValue class] rootClass:[GPBStructRoot class] file:GPBStructRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBValue__storage_) flags:GPBDescriptorInitializationFlag_None]; static const char *oneofs[] = { "kind", }; [localDescriptor setupOneofs:oneofs count:(uint32_t)(sizeof(oneofs) / sizeof(char*)) firstHasIndex:-1]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBValue_NullValue_RawValue(GPBValue *message) { GPBDescriptor *descriptor = [GPBValue descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue]; return GPBGetMessageInt32Field(message, field); } void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value) { GPBDescriptor *descriptor = [GPBValue descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBValue_FieldNumber_NullValue]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } void GPBValue_ClearKindOneOfCase(GPBValue *message) { GPBDescriptor *descriptor = [message descriptor]; GPBOneofDescriptor *oneof = [descriptor.oneofs objectAtIndex:0]; GPBMaybeClearOneof(message, oneof, -1, 0); } #pragma mark - GPBListValue @implementation GPBListValue @dynamic valuesArray, valuesArray_Count; typedef struct GPBListValue__storage_ { uint32_t _has_storage_[1]; NSMutableArray *valuesArray; } GPBListValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "valuesArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBValue), .number = GPBListValue_FieldNumber_ValuesArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBListValue__storage_, valuesArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBListValue class] rootClass:[GPBStructRoot class] file:GPBStructRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBListValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBTimestampRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBTimestampRoot : GPBRootObject @end #pragma mark - GPBTimestamp typedef GPB_ENUM(GPBTimestamp_FieldNumber) { GPBTimestamp_FieldNumber_Seconds = 1, GPBTimestamp_FieldNumber_Nanos = 2, }; /** * A Timestamp represents a point in time independent of any time zone * or calendar, represented as seconds and fractions of seconds at * nanosecond resolution in UTC Epoch time. It is encoded using the * Proleptic Gregorian Calendar which extends the Gregorian calendar * backwards to year one. It is encoded assuming all minutes are 60 * seconds long, i.e. leap seconds are "smeared" so that no leap second * table is needed for interpretation. Range is from * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. * By restricting to that range, we ensure that we can convert to * and from RFC 3339 date strings. * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). * * Example 1: Compute Timestamp from POSIX `time()`. * * Timestamp timestamp; * timestamp.set_seconds(time(NULL)); * timestamp.set_nanos(0); * * Example 2: Compute Timestamp from POSIX `gettimeofday()`. * * struct timeval tv; * gettimeofday(&tv, NULL); * * Timestamp timestamp; * timestamp.set_seconds(tv.tv_sec); * timestamp.set_nanos(tv.tv_usec * 1000); * * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. * * FILETIME ft; * GetSystemTimeAsFileTime(&ft); * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; * * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. * Timestamp timestamp; * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); * * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. * * long millis = System.currentTimeMillis(); * * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) * .setNanos((int) ((millis % 1000) * 1000000)).build(); * * * Example 5: Compute Timestamp from current time in Python. * * timestamp = Timestamp() * timestamp.GetCurrentTime() **/ @interface GPBTimestamp : GPBMessage /** * Represents seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. **/ @property(nonatomic, readwrite) int64_t seconds; /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. **/ @property(nonatomic, readwrite) int32_t nanos; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Timestamp.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Timestamp.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBTimestampRoot @implementation GPBTimestampRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBTimestampRoot_FileDescriptor static GPBFileDescriptor *GPBTimestampRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBTimestamp @implementation GPBTimestamp @dynamic seconds; @dynamic nanos; typedef struct GPBTimestamp__storage_ { uint32_t _has_storage_[1]; int32_t nanos; int64_t seconds; } GPBTimestamp__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "seconds", .dataTypeSpecific.className = NULL, .number = GPBTimestamp_FieldNumber_Seconds, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBTimestamp__storage_, seconds), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt64, }, { .name = "nanos", .dataTypeSpecific.className = NULL, .number = GPBTimestamp_FieldNumber_Nanos, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBTimestamp__storage_, nanos), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBTimestamp class] rootClass:[GPBTimestampRoot class] file:GPBTimestampRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBTimestamp__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN @class GPBAny; @class GPBEnumValue; @class GPBField; @class GPBOption; @class GPBSourceContext; NS_ASSUME_NONNULL_BEGIN #pragma mark - Enum GPBSyntax /** The syntax in which a protocol buffer element is defined. */ typedef GPB_ENUM(GPBSyntax) { /** * Value used if any message's field encounters a value that is not defined * by this enum. The message will also have C functions to get/set the rawValue * of the field. **/ GPBSyntax_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, /** Syntax `proto2`. */ GPBSyntax_SyntaxProto2 = 0, /** Syntax `proto3`. */ GPBSyntax_SyntaxProto3 = 1, }; GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void); /** * Checks to see if the given value is defined by the enum or was not known at * the time this source was generated. **/ BOOL GPBSyntax_IsValidValue(int32_t value); #pragma mark - Enum GPBField_Kind /** Basic field types. */ typedef GPB_ENUM(GPBField_Kind) { /** * Value used if any message's field encounters a value that is not defined * by this enum. The message will also have C functions to get/set the rawValue * of the field. **/ GPBField_Kind_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, /** Field type unknown. */ GPBField_Kind_TypeUnknown = 0, /** Field type double. */ GPBField_Kind_TypeDouble = 1, /** Field type float. */ GPBField_Kind_TypeFloat = 2, /** Field type int64. */ GPBField_Kind_TypeInt64 = 3, /** Field type uint64. */ GPBField_Kind_TypeUint64 = 4, /** Field type int32. */ GPBField_Kind_TypeInt32 = 5, /** Field type fixed64. */ GPBField_Kind_TypeFixed64 = 6, /** Field type fixed32. */ GPBField_Kind_TypeFixed32 = 7, /** Field type bool. */ GPBField_Kind_TypeBool = 8, /** Field type string. */ GPBField_Kind_TypeString = 9, /** Field type group. Proto2 syntax only, and deprecated. */ GPBField_Kind_TypeGroup = 10, /** Field type message. */ GPBField_Kind_TypeMessage = 11, /** Field type bytes. */ GPBField_Kind_TypeBytes = 12, /** Field type uint32. */ GPBField_Kind_TypeUint32 = 13, /** Field type enum. */ GPBField_Kind_TypeEnum = 14, /** Field type sfixed32. */ GPBField_Kind_TypeSfixed32 = 15, /** Field type sfixed64. */ GPBField_Kind_TypeSfixed64 = 16, /** Field type sint32. */ GPBField_Kind_TypeSint32 = 17, /** Field type sint64. */ GPBField_Kind_TypeSint64 = 18, }; GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void); /** * Checks to see if the given value is defined by the enum or was not known at * the time this source was generated. **/ BOOL GPBField_Kind_IsValidValue(int32_t value); #pragma mark - Enum GPBField_Cardinality /** Whether a field is optional, required, or repeated. */ typedef GPB_ENUM(GPBField_Cardinality) { /** * Value used if any message's field encounters a value that is not defined * by this enum. The message will also have C functions to get/set the rawValue * of the field. **/ GPBField_Cardinality_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue, /** For fields with unknown cardinality. */ GPBField_Cardinality_CardinalityUnknown = 0, /** For optional fields. */ GPBField_Cardinality_CardinalityOptional = 1, /** For required fields. Proto2 syntax only. */ GPBField_Cardinality_CardinalityRequired = 2, /** For repeated fields. */ GPBField_Cardinality_CardinalityRepeated = 3, }; GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void); /** * Checks to see if the given value is defined by the enum or was not known at * the time this source was generated. **/ BOOL GPBField_Cardinality_IsValidValue(int32_t value); #pragma mark - GPBTypeRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBTypeRoot : GPBRootObject @end #pragma mark - GPBType typedef GPB_ENUM(GPBType_FieldNumber) { GPBType_FieldNumber_Name = 1, GPBType_FieldNumber_FieldsArray = 2, GPBType_FieldNumber_OneofsArray = 3, GPBType_FieldNumber_OptionsArray = 4, GPBType_FieldNumber_SourceContext = 5, GPBType_FieldNumber_Syntax = 6, }; /** * A protocol buffer message type. **/ @interface GPBType : GPBMessage /** The fully qualified message name. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** The list of fields. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *fieldsArray; /** The number of items in @c fieldsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger fieldsArray_Count; /** The list of types appearing in `oneof` definitions in this type. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *oneofsArray; /** The number of items in @c oneofsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger oneofsArray_Count; /** The protocol buffer options. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; /** The source context. */ @property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; /** Test to see if @c sourceContext has been set. */ @property(nonatomic, readwrite) BOOL hasSourceContext; /** The source syntax. */ @property(nonatomic, readwrite) GPBSyntax syntax; @end /** * Fetches the raw value of a @c GPBType's @c syntax property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBType_Syntax_RawValue(GPBType *message); /** * Sets the raw value of an @c GPBType's @c syntax property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value); #pragma mark - GPBField typedef GPB_ENUM(GPBField_FieldNumber) { GPBField_FieldNumber_Kind = 1, GPBField_FieldNumber_Cardinality = 2, GPBField_FieldNumber_Number = 3, GPBField_FieldNumber_Name = 4, GPBField_FieldNumber_TypeURL = 6, GPBField_FieldNumber_OneofIndex = 7, GPBField_FieldNumber_Packed = 8, GPBField_FieldNumber_OptionsArray = 9, GPBField_FieldNumber_JsonName = 10, GPBField_FieldNumber_DefaultValue = 11, }; /** * A single field of a message type. **/ @interface GPBField : GPBMessage /** The field type. */ @property(nonatomic, readwrite) GPBField_Kind kind; /** The field cardinality. */ @property(nonatomic, readwrite) GPBField_Cardinality cardinality; /** The field number. */ @property(nonatomic, readwrite) int32_t number; /** The field name. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** * The field type URL, without the scheme, for message or enumeration * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL; /** * The index of the field type in `Type.oneofs`, for message or enumeration * types. The first type has index 1; zero means the type is not in the list. **/ @property(nonatomic, readwrite) int32_t oneofIndex; /** Whether to use alternative packed wire representation. */ @property(nonatomic, readwrite) BOOL packed; /** The protocol buffer options. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; /** The field JSON name. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *jsonName; /** The string value of the default value of this field. Proto2 syntax only. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *defaultValue; @end /** * Fetches the raw value of a @c GPBField's @c kind property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBField_Kind_RawValue(GPBField *message); /** * Sets the raw value of an @c GPBField's @c kind property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBField_Kind_RawValue(GPBField *message, int32_t value); /** * Fetches the raw value of a @c GPBField's @c cardinality property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBField_Cardinality_RawValue(GPBField *message); /** * Sets the raw value of an @c GPBField's @c cardinality property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value); #pragma mark - GPBEnum typedef GPB_ENUM(GPBEnum_FieldNumber) { GPBEnum_FieldNumber_Name = 1, GPBEnum_FieldNumber_EnumvalueArray = 2, GPBEnum_FieldNumber_OptionsArray = 3, GPBEnum_FieldNumber_SourceContext = 4, GPBEnum_FieldNumber_Syntax = 5, }; /** * Enum type definition. **/ @interface GPBEnum : GPBMessage /** Enum type name. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** Enum value definitions. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *enumvalueArray; /** The number of items in @c enumvalueArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger enumvalueArray_Count; /** Protocol buffer options. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; /** The source context. */ @property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext; /** Test to see if @c sourceContext has been set. */ @property(nonatomic, readwrite) BOOL hasSourceContext; /** The source syntax. */ @property(nonatomic, readwrite) GPBSyntax syntax; @end /** * Fetches the raw value of a @c GPBEnum's @c syntax property, even * if the value was not defined by the enum at the time the code was generated. **/ int32_t GPBEnum_Syntax_RawValue(GPBEnum *message); /** * Sets the raw value of an @c GPBEnum's @c syntax property, allowing * it to be set to a value that was not defined by the enum at the time the code * was generated. **/ void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value); #pragma mark - GPBEnumValue typedef GPB_ENUM(GPBEnumValue_FieldNumber) { GPBEnumValue_FieldNumber_Name = 1, GPBEnumValue_FieldNumber_Number = 2, GPBEnumValue_FieldNumber_OptionsArray = 3, }; /** * Enum value definition. **/ @interface GPBEnumValue : GPBMessage /** Enum value name. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** Enum value number. */ @property(nonatomic, readwrite) int32_t number; /** Protocol buffer options. */ @property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *optionsArray; /** The number of items in @c optionsArray without causing the array to be created. */ @property(nonatomic, readonly) NSUInteger optionsArray_Count; @end #pragma mark - GPBOption typedef GPB_ENUM(GPBOption_FieldNumber) { GPBOption_FieldNumber_Name = 1, GPBOption_FieldNumber_Value = 2, }; /** * A protocol buffer option, which can be attached to a message, field, * enumeration, etc. **/ @interface GPBOption : GPBMessage /** * The option's name. For protobuf built-in options (options defined in * descriptor.proto), this is the short name. For example, `"map_entry"`. * For custom options, it should be the fully-qualified name. For example, * `"google.api.http"`. **/ @property(nonatomic, readwrite, copy, null_resettable) NSString *name; /** * The option's value packed in an Any message. If the value is a primitive, * the corresponding wrapper type defined in google/protobuf/wrappers.proto * should be used. If the value is an enum, it should be stored as an int32 * value using the google.protobuf.Int32Value type. **/ @property(nonatomic, readwrite, strong, null_resettable) GPBAny *value; /** Test to see if @c value has been set. */ @property(nonatomic, readwrite) BOOL hasValue; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Type.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #import #import #else #import "google/protobuf/Type.pbobjc.h" #import "google/protobuf/Any.pbobjc.h" #import "google/protobuf/SourceContext.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBTypeRoot @implementation GPBTypeRoot // No extensions in the file and none of the imports (direct or indirect) // defined extensions, so no need to generate +extensionRegistry. @end #pragma mark - GPBTypeRoot_FileDescriptor static GPBFileDescriptor *GPBTypeRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - Enum GPBSyntax GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void) { static GPBEnumDescriptor *descriptor = NULL; if (!descriptor) { static const char *valueNames = "SyntaxProto2\000SyntaxProto3\000"; static const int32_t values[] = { GPBSyntax_SyntaxProto2, GPBSyntax_SyntaxProto3, }; GPBEnumDescriptor *worker = [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBSyntax) valueNames:valueNames values:values count:(uint32_t)(sizeof(values) / sizeof(int32_t)) enumVerifier:GPBSyntax_IsValidValue]; if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { [worker release]; } } return descriptor; } BOOL GPBSyntax_IsValidValue(int32_t value__) { switch (value__) { case GPBSyntax_SyntaxProto2: case GPBSyntax_SyntaxProto3: return YES; default: return NO; } } #pragma mark - GPBType @implementation GPBType @dynamic name; @dynamic fieldsArray, fieldsArray_Count; @dynamic oneofsArray, oneofsArray_Count; @dynamic optionsArray, optionsArray_Count; @dynamic hasSourceContext, sourceContext; @dynamic syntax; typedef struct GPBType__storage_ { uint32_t _has_storage_[1]; GPBSyntax syntax; NSString *name; NSMutableArray *fieldsArray; NSMutableArray *oneofsArray; NSMutableArray *optionsArray; GPBSourceContext *sourceContext; } GPBType__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBType_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBType__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "fieldsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBField), .number = GPBType_FieldNumber_FieldsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBType__storage_, fieldsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "oneofsArray", .dataTypeSpecific.className = NULL, .number = GPBType_FieldNumber_OneofsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBType__storage_, oneofsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeString, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBType_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBType__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "sourceContext", .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), .number = GPBType_FieldNumber_SourceContext, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBType__storage_, sourceContext), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, { .name = "syntax", .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, .number = GPBType_FieldNumber_Syntax, .hasIndex = 2, .offset = (uint32_t)offsetof(GPBType__storage_, syntax), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBType class] rootClass:[GPBTypeRoot class] file:GPBTypeRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBType__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBType_Syntax_RawValue(GPBType *message) { GPBDescriptor *descriptor = [GPBType descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; return GPBGetMessageInt32Field(message, field); } void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value) { GPBDescriptor *descriptor = [GPBType descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBType_FieldNumber_Syntax]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } #pragma mark - GPBField @implementation GPBField @dynamic kind; @dynamic cardinality; @dynamic number; @dynamic name; @dynamic typeURL; @dynamic oneofIndex; @dynamic packed; @dynamic optionsArray, optionsArray_Count; @dynamic jsonName; @dynamic defaultValue; typedef struct GPBField__storage_ { uint32_t _has_storage_[1]; GPBField_Kind kind; GPBField_Cardinality cardinality; int32_t number; int32_t oneofIndex; NSString *name; NSString *typeURL; NSMutableArray *optionsArray; NSString *jsonName; NSString *defaultValue; } GPBField__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "kind", .dataTypeSpecific.enumDescFunc = GPBField_Kind_EnumDescriptor, .number = GPBField_FieldNumber_Kind, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBField__storage_, kind), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, { .name = "cardinality", .dataTypeSpecific.enumDescFunc = GPBField_Cardinality_EnumDescriptor, .number = GPBField_FieldNumber_Cardinality, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBField__storage_, cardinality), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, { .name = "number", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_Number, .hasIndex = 2, .offset = (uint32_t)offsetof(GPBField__storage_, number), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_Name, .hasIndex = 3, .offset = (uint32_t)offsetof(GPBField__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "typeURL", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_TypeURL, .hasIndex = 4, .offset = (uint32_t)offsetof(GPBField__storage_, typeURL), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom), .dataType = GPBDataTypeString, }, { .name = "oneofIndex", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_OneofIndex, .hasIndex = 5, .offset = (uint32_t)offsetof(GPBField__storage_, oneofIndex), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, { .name = "packed", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_Packed, .hasIndex = 6, .offset = 7, // Stored in _has_storage_ to save space. .flags = GPBFieldOptional, .dataType = GPBDataTypeBool, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBField_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBField__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "jsonName", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_JsonName, .hasIndex = 8, .offset = (uint32_t)offsetof(GPBField__storage_, jsonName), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "defaultValue", .dataTypeSpecific.className = NULL, .number = GPBField_FieldNumber_DefaultValue, .hasIndex = 9, .offset = (uint32_t)offsetof(GPBField__storage_, defaultValue), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBField class] rootClass:[GPBTypeRoot class] file:GPBTypeRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBField__storage_) flags:GPBDescriptorInitializationFlag_None]; #if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS static const char *extraTextFormatInfo = "\001\006\004\241!!\000"; [localDescriptor setupExtraTextInfo:extraTextFormatInfo]; #endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBField_Kind_RawValue(GPBField *message) { GPBDescriptor *descriptor = [GPBField descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; return GPBGetMessageInt32Field(message, field); } void SetGPBField_Kind_RawValue(GPBField *message, int32_t value) { GPBDescriptor *descriptor = [GPBField descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Kind]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } int32_t GPBField_Cardinality_RawValue(GPBField *message) { GPBDescriptor *descriptor = [GPBField descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; return GPBGetMessageInt32Field(message, field); } void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value) { GPBDescriptor *descriptor = [GPBField descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBField_FieldNumber_Cardinality]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } #pragma mark - Enum GPBField_Kind GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void) { static GPBEnumDescriptor *descriptor = NULL; if (!descriptor) { static const char *valueNames = "TypeUnknown\000TypeDouble\000TypeFloat\000TypeInt" "64\000TypeUint64\000TypeInt32\000TypeFixed64\000Type" "Fixed32\000TypeBool\000TypeString\000TypeGroup\000Ty" "peMessage\000TypeBytes\000TypeUint32\000TypeEnum\000" "TypeSfixed32\000TypeSfixed64\000TypeSint32\000Typ" "eSint64\000"; static const int32_t values[] = { GPBField_Kind_TypeUnknown, GPBField_Kind_TypeDouble, GPBField_Kind_TypeFloat, GPBField_Kind_TypeInt64, GPBField_Kind_TypeUint64, GPBField_Kind_TypeInt32, GPBField_Kind_TypeFixed64, GPBField_Kind_TypeFixed32, GPBField_Kind_TypeBool, GPBField_Kind_TypeString, GPBField_Kind_TypeGroup, GPBField_Kind_TypeMessage, GPBField_Kind_TypeBytes, GPBField_Kind_TypeUint32, GPBField_Kind_TypeEnum, GPBField_Kind_TypeSfixed32, GPBField_Kind_TypeSfixed64, GPBField_Kind_TypeSint32, GPBField_Kind_TypeSint64, }; GPBEnumDescriptor *worker = [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Kind) valueNames:valueNames values:values count:(uint32_t)(sizeof(values) / sizeof(int32_t)) enumVerifier:GPBField_Kind_IsValidValue]; if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { [worker release]; } } return descriptor; } BOOL GPBField_Kind_IsValidValue(int32_t value__) { switch (value__) { case GPBField_Kind_TypeUnknown: case GPBField_Kind_TypeDouble: case GPBField_Kind_TypeFloat: case GPBField_Kind_TypeInt64: case GPBField_Kind_TypeUint64: case GPBField_Kind_TypeInt32: case GPBField_Kind_TypeFixed64: case GPBField_Kind_TypeFixed32: case GPBField_Kind_TypeBool: case GPBField_Kind_TypeString: case GPBField_Kind_TypeGroup: case GPBField_Kind_TypeMessage: case GPBField_Kind_TypeBytes: case GPBField_Kind_TypeUint32: case GPBField_Kind_TypeEnum: case GPBField_Kind_TypeSfixed32: case GPBField_Kind_TypeSfixed64: case GPBField_Kind_TypeSint32: case GPBField_Kind_TypeSint64: return YES; default: return NO; } } #pragma mark - Enum GPBField_Cardinality GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void) { static GPBEnumDescriptor *descriptor = NULL; if (!descriptor) { static const char *valueNames = "CardinalityUnknown\000CardinalityOptional\000C" "ardinalityRequired\000CardinalityRepeated\000"; static const int32_t values[] = { GPBField_Cardinality_CardinalityUnknown, GPBField_Cardinality_CardinalityOptional, GPBField_Cardinality_CardinalityRequired, GPBField_Cardinality_CardinalityRepeated, }; GPBEnumDescriptor *worker = [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol(GPBField_Cardinality) valueNames:valueNames values:values count:(uint32_t)(sizeof(values) / sizeof(int32_t)) enumVerifier:GPBField_Cardinality_IsValidValue]; if (!OSAtomicCompareAndSwapPtrBarrier(nil, worker, (void * volatile *)&descriptor)) { [worker release]; } } return descriptor; } BOOL GPBField_Cardinality_IsValidValue(int32_t value__) { switch (value__) { case GPBField_Cardinality_CardinalityUnknown: case GPBField_Cardinality_CardinalityOptional: case GPBField_Cardinality_CardinalityRequired: case GPBField_Cardinality_CardinalityRepeated: return YES; default: return NO; } } #pragma mark - GPBEnum @implementation GPBEnum @dynamic name; @dynamic enumvalueArray, enumvalueArray_Count; @dynamic optionsArray, optionsArray_Count; @dynamic hasSourceContext, sourceContext; @dynamic syntax; typedef struct GPBEnum__storage_ { uint32_t _has_storage_[1]; GPBSyntax syntax; NSString *name; NSMutableArray *enumvalueArray; NSMutableArray *optionsArray; GPBSourceContext *sourceContext; } GPBEnum__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBEnum_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBEnum__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "enumvalueArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBEnumValue), .number = GPBEnum_FieldNumber_EnumvalueArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBEnum__storage_, enumvalueArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBEnum_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBEnum__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, { .name = "sourceContext", .dataTypeSpecific.className = GPBStringifySymbol(GPBSourceContext), .number = GPBEnum_FieldNumber_SourceContext, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBEnum__storage_, sourceContext), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, { .name = "syntax", .dataTypeSpecific.enumDescFunc = GPBSyntax_EnumDescriptor, .number = GPBEnum_FieldNumber_Syntax, .hasIndex = 2, .offset = (uint32_t)offsetof(GPBEnum__storage_, syntax), .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor), .dataType = GPBDataTypeEnum, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBEnum class] rootClass:[GPBTypeRoot class] file:GPBTypeRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBEnum__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end int32_t GPBEnum_Syntax_RawValue(GPBEnum *message) { GPBDescriptor *descriptor = [GPBEnum descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; return GPBGetMessageInt32Field(message, field); } void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value) { GPBDescriptor *descriptor = [GPBEnum descriptor]; GPBFieldDescriptor *field = [descriptor fieldWithNumber:GPBEnum_FieldNumber_Syntax]; GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax); } #pragma mark - GPBEnumValue @implementation GPBEnumValue @dynamic name; @dynamic number; @dynamic optionsArray, optionsArray_Count; typedef struct GPBEnumValue__storage_ { uint32_t _has_storage_[1]; int32_t number; NSString *name; NSMutableArray *optionsArray; } GPBEnumValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBEnumValue_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBEnumValue__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "number", .dataTypeSpecific.className = NULL, .number = GPBEnumValue_FieldNumber_Number, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBEnumValue__storage_, number), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, { .name = "optionsArray", .dataTypeSpecific.className = GPBStringifySymbol(GPBOption), .number = GPBEnumValue_FieldNumber_OptionsArray, .hasIndex = GPBNoHasBit, .offset = (uint32_t)offsetof(GPBEnumValue__storage_, optionsArray), .flags = GPBFieldRepeated, .dataType = GPBDataTypeMessage, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBEnumValue class] rootClass:[GPBTypeRoot class] file:GPBTypeRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBEnumValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBOption @implementation GPBOption @dynamic name; @dynamic hasValue, value; typedef struct GPBOption__storage_ { uint32_t _has_storage_[1]; NSString *name; GPBAny *value; } GPBOption__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "name", .dataTypeSpecific.className = NULL, .number = GPBOption_FieldNumber_Name, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBOption__storage_, name), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, { .name = "value", .dataTypeSpecific.className = GPBStringifySymbol(GPBAny), .number = GPBOption_FieldNumber_Value, .hasIndex = 1, .offset = (uint32_t)offsetof(GPBOption__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeMessage, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBOption class] rootClass:[GPBTypeRoot class] file:GPBTypeRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBOption__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers.h" #endif #if GOOGLE_PROTOBUF_OBJC_VERSION < 30002 #error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources. #endif #if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION #error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources. #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" CF_EXTERN_C_BEGIN NS_ASSUME_NONNULL_BEGIN #pragma mark - GPBWrappersRoot /** * Exposes the extension registry for this file. * * The base class provides: * @code * + (GPBExtensionRegistry *)extensionRegistry; * @endcode * which is a @c GPBExtensionRegistry that includes all the extensions defined by * this file and all files that it depends on. **/ @interface GPBWrappersRoot : GPBRootObject @end #pragma mark - GPBDoubleValue typedef GPB_ENUM(GPBDoubleValue_FieldNumber) { GPBDoubleValue_FieldNumber_Value = 1, }; /** * Wrapper message for `double`. * * The JSON representation for `DoubleValue` is JSON number. **/ @interface GPBDoubleValue : GPBMessage /** The double value. */ @property(nonatomic, readwrite) double value; @end #pragma mark - GPBFloatValue typedef GPB_ENUM(GPBFloatValue_FieldNumber) { GPBFloatValue_FieldNumber_Value = 1, }; /** * Wrapper message for `float`. * * The JSON representation for `FloatValue` is JSON number. **/ @interface GPBFloatValue : GPBMessage /** The float value. */ @property(nonatomic, readwrite) float value; @end #pragma mark - GPBInt64Value typedef GPB_ENUM(GPBInt64Value_FieldNumber) { GPBInt64Value_FieldNumber_Value = 1, }; /** * Wrapper message for `int64`. * * The JSON representation for `Int64Value` is JSON string. **/ @interface GPBInt64Value : GPBMessage /** The int64 value. */ @property(nonatomic, readwrite) int64_t value; @end #pragma mark - GPBUInt64Value typedef GPB_ENUM(GPBUInt64Value_FieldNumber) { GPBUInt64Value_FieldNumber_Value = 1, }; /** * Wrapper message for `uint64`. * * The JSON representation for `UInt64Value` is JSON string. **/ @interface GPBUInt64Value : GPBMessage /** The uint64 value. */ @property(nonatomic, readwrite) uint64_t value; @end #pragma mark - GPBInt32Value typedef GPB_ENUM(GPBInt32Value_FieldNumber) { GPBInt32Value_FieldNumber_Value = 1, }; /** * Wrapper message for `int32`. * * The JSON representation for `Int32Value` is JSON number. **/ @interface GPBInt32Value : GPBMessage /** The int32 value. */ @property(nonatomic, readwrite) int32_t value; @end #pragma mark - GPBUInt32Value typedef GPB_ENUM(GPBUInt32Value_FieldNumber) { GPBUInt32Value_FieldNumber_Value = 1, }; /** * Wrapper message for `uint32`. * * The JSON representation for `UInt32Value` is JSON number. **/ @interface GPBUInt32Value : GPBMessage /** The uint32 value. */ @property(nonatomic, readwrite) uint32_t value; @end #pragma mark - GPBBoolValue typedef GPB_ENUM(GPBBoolValue_FieldNumber) { GPBBoolValue_FieldNumber_Value = 1, }; /** * Wrapper message for `bool`. * * The JSON representation for `BoolValue` is JSON `true` and `false`. **/ @interface GPBBoolValue : GPBMessage /** The bool value. */ @property(nonatomic, readwrite) BOOL value; @end #pragma mark - GPBStringValue typedef GPB_ENUM(GPBStringValue_FieldNumber) { GPBStringValue_FieldNumber_Value = 1, }; /** * Wrapper message for `string`. * * The JSON representation for `StringValue` is JSON string. **/ @interface GPBStringValue : GPBMessage /** The string value. */ @property(nonatomic, readwrite, copy, null_resettable) NSString *value; @end #pragma mark - GPBBytesValue typedef GPB_ENUM(GPBBytesValue_FieldNumber) { GPBBytesValue_FieldNumber_Value = 1, }; /** * Wrapper message for `bytes`. * * The JSON representation for `BytesValue` is JSON string. **/ @interface GPBBytesValue : GPBMessage /** The bytes value. */ @property(nonatomic, readwrite, copy, null_resettable) NSData *value; @end NS_ASSUME_NONNULL_END CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/Protobuf/objectivec/google/protobuf/Wrappers.pbobjc.m ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto // This CPP symbol can be defined to use imports that match up to the framework // imports needed when using CocoaPods. #if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS) #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0 #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "GPBProtocolBuffers_RuntimeSupport.h" #endif #if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS #import #else #import "google/protobuf/Wrappers.pbobjc.h" #endif // @@protoc_insertion_point(imports) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #pragma mark - GPBWrappersRoot @implementation GPBWrappersRoot // No extensions in the file and no imports, so no need to generate // +extensionRegistry. @end #pragma mark - GPBWrappersRoot_FileDescriptor static GPBFileDescriptor *GPBWrappersRoot_FileDescriptor(void) { // This is called by +initialize so there is no need to worry // about thread safety of the singleton. static GPBFileDescriptor *descriptor = NULL; if (!descriptor) { GPB_DEBUG_CHECK_RUNTIME_VERSIONS(); descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf" objcPrefix:@"GPB" syntax:GPBFileSyntaxProto3]; } return descriptor; } #pragma mark - GPBDoubleValue @implementation GPBDoubleValue @dynamic value; typedef struct GPBDoubleValue__storage_ { uint32_t _has_storage_[1]; double value; } GPBDoubleValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBDoubleValue_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBDoubleValue__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeDouble, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBDoubleValue class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBDoubleValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBFloatValue @implementation GPBFloatValue @dynamic value; typedef struct GPBFloatValue__storage_ { uint32_t _has_storage_[1]; float value; } GPBFloatValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBFloatValue_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBFloatValue__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeFloat, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBFloatValue class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBFloatValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBInt64Value @implementation GPBInt64Value @dynamic value; typedef struct GPBInt64Value__storage_ { uint32_t _has_storage_[1]; int64_t value; } GPBInt64Value__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBInt64Value_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBInt64Value__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt64, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBInt64Value class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBInt64Value__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBUInt64Value @implementation GPBUInt64Value @dynamic value; typedef struct GPBUInt64Value__storage_ { uint32_t _has_storage_[1]; uint64_t value; } GPBUInt64Value__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBUInt64Value_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBUInt64Value__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeUInt64, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBUInt64Value class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBUInt64Value__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBInt32Value @implementation GPBInt32Value @dynamic value; typedef struct GPBInt32Value__storage_ { uint32_t _has_storage_[1]; int32_t value; } GPBInt32Value__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBInt32Value_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBInt32Value__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeInt32, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBInt32Value class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBInt32Value__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBUInt32Value @implementation GPBUInt32Value @dynamic value; typedef struct GPBUInt32Value__storage_ { uint32_t _has_storage_[1]; uint32_t value; } GPBUInt32Value__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBUInt32Value_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBUInt32Value__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeUInt32, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBUInt32Value class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBUInt32Value__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBBoolValue @implementation GPBBoolValue @dynamic value; typedef struct GPBBoolValue__storage_ { uint32_t _has_storage_[1]; } GPBBoolValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBBoolValue_FieldNumber_Value, .hasIndex = 0, .offset = 1, // Stored in _has_storage_ to save space. .flags = GPBFieldOptional, .dataType = GPBDataTypeBool, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBBoolValue class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBBoolValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBStringValue @implementation GPBStringValue @dynamic value; typedef struct GPBStringValue__storage_ { uint32_t _has_storage_[1]; NSString *value; } GPBStringValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBStringValue_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBStringValue__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeString, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBStringValue class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBStringValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma mark - GPBBytesValue @implementation GPBBytesValue @dynamic value; typedef struct GPBBytesValue__storage_ { uint32_t _has_storage_[1]; NSData *value; } GPBBytesValue__storage_; // This method is threadsafe because it is initially called // in +initialize for each subclass. + (GPBDescriptor *)descriptor { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { { .name = "value", .dataTypeSpecific.className = NULL, .number = GPBBytesValue_FieldNumber_Value, .hasIndex = 0, .offset = (uint32_t)offsetof(GPBBytesValue__storage_, value), .flags = GPBFieldOptional, .dataType = GPBDataTypeBytes, }, }; GPBDescriptor *localDescriptor = [GPBDescriptor allocDescriptorForClass:[GPBBytesValue class] rootClass:[GPBWrappersRoot class] file:GPBWrappersRoot_FileDescriptor() fields:fields fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) storageSize:sizeof(GPBBytesValue__storage_) flags:GPBDescriptorInitializationFlag_None]; NSAssert(descriptor == nil, @"Startup recursed!"); descriptor = localDescriptor; } return descriptor; } @end #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) ================================================ FILE: iOS/User/ezshopUser/Pods/SwiftyJSON/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: iOS/User/ezshopUser/Pods/SwiftyJSON/README.md ================================================ # SwiftyJSON [![Travis CI](https://travis-ci.org/SwiftyJSON/SwiftyJSON.svg?branch=master)](https://travis-ci.org/SwiftyJSON/SwiftyJSON) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/SwiftyJSON.svg) ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+%20%7C%20macOS%2010.10+%20%7C%20tvOS%209.0+%20%7C%20watchOS%202.0+-333333.svg) SwiftyJSON makes it easy to deal with JSON data in Swift. 1. [Why is the typical JSON handling in Swift NOT good](#why-is-the-typical-json-handling-in-swift-not-good) 2. [Requirements](#requirements) 3. [Integration](#integration) 4. [Usage](#usage) - [Initialization](#initialization) - [Subscript](#subscript) - [Loop](#loop) - [Error](#error) - [Optional getter](#optional-getter) - [Non-optional getter](#non-optional-getter) - [Setter](#setter) - [Raw object](#raw-object) - [Literal convertibles](#literal-convertibles) - [Merging](#merging) 5. [Work with Alamofire](#work-with-alamofire) > For Legacy Swift support, take a look at the [swift2 branch](https://github.com/SwiftyJSON/SwiftyJSON/tree/swift2) > [中文介绍](http://tangplin.github.io/swiftyjson/) ## Why is the typical JSON handling in Swift NOT good? Swift is very strict about types. But although explicit typing is good for saving us from mistakes, it becomes painful when dealing with JSON and other areas that are, by nature, implicit about types. Take the Twitter API for example. Say we want to retrieve a user's "name" value of some tweet in Swift (according to Twitter's API https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline). The code would look like this: ```swift if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], let user = statusesArray[0]["user"] as? [String: Any], let username = user["name"] as? String { // Finally we got the username } ``` It's not good. Even if we use optional chaining, it would be messy: ```swift if let JSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]], let username = (JSONObject[0]["user"] as? [String: Any])?["name"] as? String { // There's our username } ``` An unreadable mess--for something that should really be simple! With SwiftyJSON all you have to do is: ```swift let json = JSON(data: dataFromNetworking) if let userName = json[0]["user"]["name"].string { //Now you got your value } ``` And don't worry about the Optional Wrapping thing. It's done for you automatically. ```swift let json = JSON(data: dataFromNetworking) if let userName = json[999999]["wrong_key"]["wrong_name"].string { //Calm down, take it easy, the ".string" property still produces the correct Optional String type with safety } else { //Print the error print(json[999999]["wrong_key"]["wrong_name"]) } ``` ## Requirements - iOS 8.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+ - Xcode 8 ## Integration #### CocoaPods (iOS 8+, OS X 10.9+) You can use [CocoaPods](http://cocoapods.org/) to install `SwiftyJSON`by adding it to your `Podfile`: ```ruby platform :ios, '8.0' use_frameworks! target 'MyApp' do pod 'SwiftyJSON' end ``` Note that this requires CocoaPods version 36, and your iOS deployment target to be at least 8.0: #### Carthage (iOS 8+, OS X 10.9+) You can use [Carthage](https://github.com/Carthage/Carthage) to install `SwiftyJSON` by adding it to your `Cartfile`: ``` github "SwiftyJSON/SwiftyJSON" ``` #### Swift Package Manager You can use [The Swift Package Manager](https://swift.org/package-manager) to install `SwiftyJSON` by adding the proper description to your `Package.swift` file: ```swift import PackageDescription let package = Package( name: "YOUR_PROJECT_NAME", targets: [], dependencies: [ .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1,0,0).. = json["list"].arrayValue ``` ```swift //If not a Dictionary or nil, return [:] let user: Dictionary = json["user"].dictionaryValue ``` #### Setter ```swift json["name"] = JSON("new-name") json[0] = JSON(1) ``` ```swift json["id"].int = 1234567890 json["coordinate"].double = 8766.766 json["name"].string = "Jack" json.arrayObject = [1,2,3,4] json.dictionaryObject = ["name":"Jack", "age":25] ``` #### Raw object ```swift let jsonObject: Any = json.object ``` ```swift if let jsonObject: Any = json.rawValue ``` ```swift //convert the JSON to raw NSData if let data = json.rawData() { //Do something you want } ``` ```swift //convert the JSON to a raw String if let string = json.rawString() { //Do something you want } ``` #### Existence ```swift //shows you whether value specified in JSON or not if json["name"].exists() ``` #### Literal convertibles For more info about literal convertibles: [Swift Literal Convertibles](http://nshipster.com/swift-literal-convertible/) ```swift //StringLiteralConvertible let json: JSON = "I'm a json" ``` ```swift //IntegerLiteralConvertible let json: JSON = 12345 ``` ```swift //BooleanLiteralConvertible let json: JSON = true ``` ```swift //FloatLiteralConvertible let json: JSON = 2.8765 ``` ```swift //DictionaryLiteralConvertible let json: JSON = ["I":"am", "a":"json"] ``` ```swift //ArrayLiteralConvertible let json: JSON = ["I", "am", "a", "json"] ``` ```swift //NilLiteralConvertible let json: JSON = nil ``` ```swift //With subscript in array var json: JSON = [1,2,3] json[0] = 100 json[1] = 200 json[2] = 300 json[999] = 300 //Don't worry, nothing will happen ``` ```swift //With subscript in dictionary var json: JSON = ["name": "Jack", "age": 25] json["name"] = "Mike" json["age"] = "25" //It's OK to set String json["address"] = "L.A." // Add the "address": "L.A." in json ``` ```swift //Array & Dictionary var json: JSON = ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]] json["list"][3]["what"] = "that" json["list",3,"what"] = "that" let path: [JSONSubscriptType] = ["list",3,"what"] json[path] = "that" ``` ```swift //With other JSON objects let user: JSON = ["username" : "Steve", "password": "supersecurepassword"] let auth: JSON = [ "user": user.object //use user.object instead of just user "apikey": "supersecretapitoken" ] ``` #### Merging It is possible to merge one JSON into another JSON. Merging a JSON into another JSON adds all non existing values to the original JSON which are only present in the `other` JSON. If both JSONs contain a value for the same key, _mostly_ this value gets overwritten in the original JSON, but there are two cases where it provides some special treatment: - In case of both values being a `JSON.Type.array` the values form the array found in the `other` JSON getting appended to the original JSON's array value. - In case of both values being a `JSON.Type.dictionary` both JSON-values are getting merged the same way the encapsulating JSON is merged. In case, where two fields in a JSON have a different types, the value will get always overwritten. There are two different fashions for merging: `merge` modifies the original JSON, whereas `merged` works non-destructively on a copy. ```swift let original: JSON = [ "first_name": "John", "age": 20, "skills": ["Coding", "Reading"], "address": [ "street": "Front St", "zip": "12345", ] ] let update: JSON = [ "last_name": "Doe", "age": 21, "skills": ["Writing"], "address": [ "zip": "12342", "city": "New York City" ] ] let updated = original.merge(with: update) // [ // "first_name": "John", // "last_name": "Doe", // "age": 21, // "skills": ["Coding", "Reading", "Writing"], // "address": [ // "street": "Front St", // "zip": "12342", // "city": "New York City" // ] // ] ``` ## String representation There are two options available: - use the default Swift one - use a custom one that will handle optionals well and represent `nil` as `"null"`: ```swift let dict = ["1":2, "2":"two", "3": nil] as [String: Any?] let json = JSON(dict) let representation = json.rawString(options: [.castNilToNSNull: true]) // representation is "{\"1\":2,\"2\":\"two\",\"3\":null}", which represents {"1":2,"2":"two","3":null} ``` ## Work with Alamofire SwiftyJSON nicely wraps the result of the Alamofire JSON response handler: ```swift Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) print("JSON: \(json)") case .failure(let error): print(error) } } ``` ================================================ FILE: iOS/User/ezshopUser/Pods/SwiftyJSON/Source/SwiftyJSON.swift ================================================ // SwiftyJSON.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } catch let aError as NSError { if error != nil { error?.pointee = aError } self.init(jsonObject: NSNull()) } } /** Creates a JSON object - parameter object: the object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as [JSON] where object.count > 0: self.init(array: object) case let object as [String: JSON] where object.count > 0: self.init(dictionary: object) case let object as Data: self.init(data: object) default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ @available(*, deprecated: 3.2, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ fileprivate init(jsonObject: Any) { self.object = jsonObject } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ fileprivate init(array: [JSON]) { self.init(array.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ fileprivate init(dictionary: [String: JSON]) { var newDictionary = [String: Any](minimumCapacity: dictionary.count) for (key, json) in dictionary { newDictionary[key] = json.object } self.init(newDictionary) } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]) } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case _ as [JSON]: _type = .array case nil: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } public enum Index: Comparable { case array(Int) case dictionary(DictionaryIndex) case null static public func ==(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func <(lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index public typealias JSONRawIndex = Index extension JSON: Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): let (key, value) = self.rawDictionary[idx] return (key, JSON(value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let array = elements self.init(dictionaryLiteral: array) } public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in if let value = dictionary[key] { return (key, value) } return nil } return JSON(dictionaryLiteral: initializeElement) } var dict = [String : Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object } else if let jsonArray = element.1 as? [JSON] { elementToSet = JSON(jsonArray).object } else if let dictionary = element.1 as? [String : Any] { elementToSet = jsonFromDictionaryLiteral(dictionary).object } else if let dictArray = element.1 as? [[String : Any]] { let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } elementToSet = JSON(jsonArray).object } else { elementToSet = element.1 } dict[element.0] = elementToSet } self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writtingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } fileprivate func _rawString( _ encoding: String.Encoding = .utf8, options: [writtingOptionsKeys: Any], maxObjectDepth: Int = 10 ) throws -> String? { if (maxObjectDepth < 0) { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop"]) } switch self.type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = self.object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = self.object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "Could not serialize nested JSON"]) } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String : JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return ["true", "y", "t"].contains() { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { return false } return true } } //MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if let _ = self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writtingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Alamofire-dummy.m ================================================ #import @interface PodsDummy_Alamofire : NSObject @end @implementation PodsDummy_Alamofire @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double AlamofireVersionNumber; FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Alamofire.modulemap ================================================ framework module Alamofire { umbrella header "Alamofire-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Alamofire.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Alamofire GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Alamofire/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 4.3.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-dummy.m ================================================ #import @interface PodsDummy_AlamofireSwiftyJSON : NSObject @end @implementation PodsDummy_AlamofireSwiftyJSON @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double AlamofireSwiftyJSONVersionNumber; FOUNDATION_EXPORT const unsigned char AlamofireSwiftyJSONVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.modulemap ================================================ framework module AlamofireSwiftyJSON { umbrella header "AlamofireSwiftyJSON-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/AlamofireSwiftyJSON.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/AlamofireSwiftyJSON/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 0.2.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-dummy.m ================================================ #import @interface PodsDummy_GoogleToolboxForMac : NSObject @end @implementation PodsDummy_GoogleToolboxForMac @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "GTMDefines.h" #import "GTMLogger.h" #import "GTMNSData+zlib.h" FOUNDATION_EXPORT double GoogleToolboxForMacVersionNumber; FOUNDATION_EXPORT const unsigned char GoogleToolboxForMacVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.modulemap ================================================ framework module GoogleToolboxForMac { umbrella header "GoogleToolboxForMac-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/GoogleToolboxForMac.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_LDFLAGS = -l"z" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/GoogleToolboxForMac/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 2.1.1 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 3.4.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Kingfisher-dummy.m ================================================ #import @interface PodsDummy_Kingfisher : NSObject @end @implementation PodsDummy_Kingfisher @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Kingfisher-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Kingfisher-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "Kingfisher.h" FOUNDATION_EXPORT double KingfisherVersionNumber; FOUNDATION_EXPORT const unsigned char KingfisherVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Kingfisher.modulemap ================================================ framework module Kingfisher { umbrella header "Kingfisher-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Kingfisher/Kingfisher.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Kingfisher GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_LDFLAGS = -framework "CFNetwork" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES SWIFT_VERSION = 3.0 ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 1.0.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-acknowledgements.markdown ================================================ # Acknowledgements This application makes use of the following third party libraries: ## Alamofire Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## AlamofireSwiftyJSON Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Firebase Copyright 2017 Google ## FirebaseAnalytics Copyright 2017 Google ## FirebaseCore Copyright 2017 Google ## FirebaseDatabase Copyright 2017 Google ## FirebaseInstanceID Copyright 2017 Google ## FirebaseMessaging Copyright 2017 Google ## GoogleToolboxForMac Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ## Kingfisher The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Protobuf This license applies to all parts of Protocol Buffers except the following: - Atomicops support for generic gcc, located in src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. This file is copyrighted by Red Hat Inc. - Atomicops support for AIX/POWER, located in src/google/protobuf/stubs/atomicops_internals_power.h. This file is copyrighted by Bloomberg Finance LP. Copyright 2014, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Code generated by the Protocol Buffer compiler is owned by the owner of the input file used when generating it. This code is not standalone and requires a support library to be linked with it. This support library is itself covered by the above license. ## SwiftyJSON The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - https://cocoapods.org ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-acknowledgements.plist ================================================ PreferenceSpecifiers FooterText This application makes use of the following third party libraries: Title Acknowledgements Type PSGroupSpecifier FooterText Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title Alamofire Type PSGroupSpecifier FooterText Copyright (c) 2016 starboychina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title AlamofireSwiftyJSON Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title Firebase Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseAnalytics Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseCore Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseDatabase Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseInstanceID Type PSGroupSpecifier FooterText Copyright 2017 Google License Copyright Title FirebaseMessaging Type PSGroupSpecifier FooterText Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. License Apache Title GoogleToolboxForMac Type PSGroupSpecifier FooterText The MIT License (MIT) Copyright (c) 2017 Wei Wang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title Kingfisher Type PSGroupSpecifier FooterText This license applies to all parts of Protocol Buffers except the following: - Atomicops support for generic gcc, located in src/google/protobuf/stubs/atomicops_internals_generic_gcc.h. This file is copyrighted by Red Hat Inc. - Atomicops support for AIX/POWER, located in src/google/protobuf/stubs/atomicops_internals_power.h. This file is copyrighted by Bloomberg Finance LP. Copyright 2014, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Code generated by the Protocol Buffer compiler is owned by the owner of the input file used when generating it. This code is not standalone and requires a support library to be linked with it. This support library is itself covered by the above license. License New BSD Title Protobuf Type PSGroupSpecifier FooterText The MIT License (MIT) Copyright (c) 2016 Ruoyu Fu Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. License MIT Title SwiftyJSON Type PSGroupSpecifier FooterText Generated by CocoaPods - https://cocoapods.org Title Type PSGroupSpecifier StringsTable Acknowledgements Title Acknowledgements ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-dummy.m ================================================ #import @interface PodsDummy_Pods_ezshopUser : NSObject @end @implementation PodsDummy_Pods_ezshopUser @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-frameworks.sh ================================================ #!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\"" /usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" install_framework "$BUILT_PRODUCTS_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework" install_framework "$BUILT_PRODUCTS_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework" install_framework "$BUILT_PRODUCTS_DIR/Kingfisher/Kingfisher.framework" install_framework "$BUILT_PRODUCTS_DIR/Protobuf/Protobuf.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftyJSON/SwiftyJSON.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/Alamofire/Alamofire.framework" install_framework "$BUILT_PRODUCTS_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework" install_framework "$BUILT_PRODUCTS_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework" install_framework "$BUILT_PRODUCTS_DIR/Kingfisher/Kingfisher.framework" install_framework "$BUILT_PRODUCTS_DIR/Protobuf/Protobuf.framework" install_framework "$BUILT_PRODUCTS_DIR/SwiftyJSON/SwiftyJSON.framework" fi ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-resources.sh ================================================ #!/bin/sh set -e mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" XCASSET_FILES=() case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac install_resource() { if [[ "$1" = /* ]] ; then RESOURCE_PATH="$1" else RESOURCE_PATH="${PODS_ROOT}/$1" fi if [[ ! -e "$RESOURCE_PATH" ]] ; then cat << EOM error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. EOM exit 1 fi case $RESOURCE_PATH in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" ;; *.xcassets) ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") ;; *) echo "$RESOURCE_PATH" echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" ;; esac } mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] then # Find all other xcassets (this unfortunately includes those of path pods and other targets). OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) while read line; do if [[ $line != "${PODS_ROOT}*" ]]; then XCASSET_FILES+=("$line") fi done <<<"$OTHER_XCASSETS" printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double Pods_ezshopUserVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_ezshopUserVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser.debug.xcconfig ================================================ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES EMBEDDED_CONTENT_CONTAINS_SWIFT = YES FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON" "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac" "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher" "$PODS_CONFIGURATION_BUILD_DIR/Protobuf" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseCore/Frameworks" "${PODS_ROOT}/FirebaseDatabase/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/FirebaseMessaging/Frameworks" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/Core/Sources $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher/Kingfisher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Protobuf/Protobuf.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" -isystem "${PODS_ROOT}/Headers/Public/FirebaseCore" -isystem "${PODS_ROOT}/Headers/Public/FirebaseDatabase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" -isystem "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "AddressBook" -framework "Alamofire" -framework "AlamofireSwiftyJSON" -framework "CFNetwork" -framework "FirebaseAnalytics" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseMessaging" -framework "GoogleToolboxForMac" -framework "Kingfisher" -framework "Protobuf" -framework "Security" -framework "StoreKit" -framework "SwiftyJSON" -framework "SystemConfiguration" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT}/Pods ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser.modulemap ================================================ framework module Pods_ezshopUser { umbrella header "Pods-ezshopUser-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser.release.xcconfig ================================================ ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES EMBEDDED_CONTENT_CONTAINS_SWIFT = YES FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/Alamofire" "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON" "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac" "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher" "$PODS_CONFIGURATION_BUILD_DIR/Protobuf" "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON" "${PODS_ROOT}/FirebaseAnalytics/Frameworks" "${PODS_ROOT}/FirebaseCore/Frameworks" "${PODS_ROOT}/FirebaseDatabase/Frameworks" "${PODS_ROOT}/FirebaseInstanceID/Frameworks" "${PODS_ROOT}/FirebaseMessaging/Frameworks" GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 HEADER_SEARCH_PATHS = $(inherited) ${PODS_ROOT}/Firebase/Core/Sources $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/Alamofire/Alamofire.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/AlamofireSwiftyJSON/AlamofireSwiftyJSON.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GoogleToolboxForMac/GoogleToolboxForMac.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Kingfisher/Kingfisher.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/Protobuf/Protobuf.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON/SwiftyJSON.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/Firebase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" -isystem "${PODS_ROOT}/Headers/Public/FirebaseCore" -isystem "${PODS_ROOT}/Headers/Public/FirebaseDatabase" -isystem "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" -isystem "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_LDFLAGS = $(inherited) -ObjC -l"c++" -l"icucore" -l"sqlite3" -l"z" -framework "AddressBook" -framework "Alamofire" -framework "AlamofireSwiftyJSON" -framework "CFNetwork" -framework "FirebaseAnalytics" -framework "FirebaseCore" -framework "FirebaseDatabase" -framework "FirebaseInstanceID" -framework "FirebaseMessaging" -framework "GoogleToolboxForMac" -framework "Kingfisher" -framework "Protobuf" -framework "Security" -framework "StoreKit" -framework "SwiftyJSON" -framework "SystemConfiguration" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT}/Pods ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 3.2.0 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Protobuf-dummy.m ================================================ #import @interface PodsDummy_Protobuf : NSObject @end @implementation PodsDummy_Protobuf @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Protobuf-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Protobuf-umbrella.h ================================================ #ifdef __OBJC__ #import #endif #import "GPBArray.h" #import "GPBArray_PackagePrivate.h" #import "GPBBootstrap.h" #import "GPBCodedInputStream.h" #import "GPBCodedInputStream_PackagePrivate.h" #import "GPBCodedOutputStream.h" #import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBDescriptor.h" #import "GPBDescriptor_PackagePrivate.h" #import "GPBDictionary.h" #import "GPBDictionary_PackagePrivate.h" #import "GPBExtensionInternals.h" #import "GPBExtensionRegistry.h" #import "GPBMessage.h" #import "GPBMessage_PackagePrivate.h" #import "GPBProtocolBuffers.h" #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBRootObject.h" #import "GPBRootObject_PackagePrivate.h" #import "GPBRuntimeTypes.h" #import "GPBUnknownField.h" #import "GPBUnknownFieldSet.h" #import "GPBUnknownFieldSet_PackagePrivate.h" #import "GPBUnknownField_PackagePrivate.h" #import "GPBUtilities.h" #import "GPBUtilities_PackagePrivate.h" #import "GPBWellKnownTypes.h" #import "GPBWireFormat.h" #import "Any.pbobjc.h" #import "Api.pbobjc.h" #import "Duration.pbobjc.h" #import "Empty.pbobjc.h" #import "FieldMask.pbobjc.h" #import "SourceContext.pbobjc.h" #import "Struct.pbobjc.h" #import "Timestamp.pbobjc.h" #import "Type.pbobjc.h" #import "Wrappers.pbobjc.h" FOUNDATION_EXPORT double ProtobufVersionNumber; FOUNDATION_EXPORT const unsigned char ProtobufVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Protobuf.modulemap ================================================ framework module Protobuf { umbrella header "Protobuf-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/Protobuf/Protobuf.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/Protobuf GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 $(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier ${PRODUCT_BUNDLE_IDENTIFIER} CFBundleInfoDictionaryVersion 6.0 CFBundleName ${PRODUCT_NAME} CFBundlePackageType FMWK CFBundleShortVersionString 3.1.4 CFBundleSignature ???? CFBundleVersion ${CURRENT_PROJECT_VERSION} NSPrincipalClass ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-dummy.m ================================================ #import @interface PodsDummy_SwiftyJSON : NSObject @end @implementation PodsDummy_SwiftyJSON @end ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-prefix.pch ================================================ #ifdef __OBJC__ #import #endif ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/SwiftyJSON-umbrella.h ================================================ #ifdef __OBJC__ #import #endif FOUNDATION_EXPORT double SwiftyJSONVersionNumber; FOUNDATION_EXPORT const unsigned char SwiftyJSONVersionString[]; ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.modulemap ================================================ framework module SwiftyJSON { umbrella header "SwiftyJSON-umbrella.h" export * module * { export * } } ================================================ FILE: iOS/User/ezshopUser/Pods/Target Support Files/SwiftyJSON/SwiftyJSON.xcconfig ================================================ CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/SwiftyJSON GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/Firebase" "${PODS_ROOT}/Headers/Public/FirebaseAnalytics" "${PODS_ROOT}/Headers/Public/FirebaseCore" "${PODS_ROOT}/Headers/Public/FirebaseDatabase" "${PODS_ROOT}/Headers/Public/FirebaseInstanceID" "${PODS_ROOT}/Headers/Public/FirebaseMessaging" OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS" PODS_BUILD_DIR = $BUILD_DIR PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) PODS_ROOT = ${SRCROOT} PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} SKIP_INSTALL = YES SWIFT_VERSION = 3.0 ================================================ FILE: iOS/User/ezshopUser/ezshopUser/ActivitiyIndicator.swift ================================================ // // ActivitiyIndicator.swift // emii // // Created by Jung Geon Choi on 2017-03-04. // Copyright © 2017 Emanant Inc. All rights reserved. // import Foundation import UIKit class ActivityIndicator { static let shared = ActivityIndicator() var blurEffect = UIBlurEffect() var backgroundView = UIView() var blurEffectView = UIVisualEffectView() var loadingIndicator = UIActivityIndicatorView() var myCover = UIView() let labelText=UILabel() init () { // make background blur blurEffect = UIBlurEffect(style: UIBlurEffectStyle.extraLight) blurEffectView = UIVisualEffectView(effect: blurEffect) // make activity indicator // backgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) } func show(_ view: UIView) { blurEffectView.frame = view.bounds // backgroundView.frame = view.bounds loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge loadingIndicator.hidesWhenStopped = true loadingIndicator.startAnimating() loadingIndicator.center = view.center loadingIndicator.color = view.tintColor // view.addSubview(backgroundView) view.addSubview(blurEffectView) view.addSubview(loadingIndicator) // labelText.frame=CGRect(x: 0,y: loadingIndicator.center.y+40,width: view.frame.width,height: 20) // labelText.text="Loading..." // labelText.textAlignment=NSTextAlignment.center // labelText.textColor=UIColor.white // view.addSubview(labelText) blurEffectView.show() loadingIndicator.show() } func hide() { blurEffectView.hide() loadingIndicator.hide() blurEffectView.removeFromSuperview() loadingIndicator.removeFromSuperview() // myCover.removeFromSuperview() // backgroundView.removeFromSuperview() // labelText.removeFromSuperview() } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/AppDelegate.swift ================================================ // // AppDelegate.swift // ezshopUser // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import Firebase //import FirebaseMessaging import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate{ var window: UIWindow? func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { let token = FIRInstanceID.instanceID().token()! print(token) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FIRApp.configure() if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) // For iOS 10 data message (sent via FCM) FIRMessaging.messaging().remoteMessageDelegate = self } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() NotificationCenter.default.addObserver(forName: NSNotification.Name.firInstanceIDTokenRefresh, object: nil, queue: OperationQueue.main) { (n) in self.tokenRefreshNotification(n) } // Override point for customization after application launch. return true } func tokenRefreshNotification(_ notification: Notification) { if let refreshedToken = FIRInstanceID.instanceID().token() { print("InstanceID token: \(refreshedToken)") } // Connect to FCM since connection may have failed when attempted before having a token. connectToFcm() } func connectToFcm() { // Won't connect since there is no token guard FIRInstanceID.instanceID().token() != nil else { return } // Disconnect previous FCM connection if it exists. FIRMessaging.messaging().disconnect() FIRMessaging.messaging().connect { (error) in if error != nil { print("Unable to connect with FCM. \(error)") } else { print("Connected to FCM.") } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count) var tokenString = "" for i in 0.. Void) { // Let FCM know about the message for analytics etc. FIRMessaging.messaging().appDidReceiveMessage(userInfo) // handle your message } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // 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 // Print full message. print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@3x.png", "scale" : "3x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@3x.png", "scale" : "3x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@3x.png", "scale" : "3x" }, { "size" : "57x57", "idiom" : "iphone", "filename" : "Icon-App-57x57@1x.png", "scale" : "1x" }, { "size" : "57x57", "idiom" : "iphone", "filename" : "Icon-App-57x57@2x.png", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@2x.png", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@3x.png", "scale" : "3x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@1x.png", "scale" : "1x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@1x.png", "scale" : "1x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "50x50", "idiom" : "ipad", "filename" : "Icon-Small-50x50@1x.png", "scale" : "1x" }, { "size" : "50x50", "idiom" : "ipad", "filename" : "Icon-Small-50x50@2x.png", "scale" : "2x" }, { "size" : "72x72", "idiom" : "ipad", "filename" : "Icon-App-72x72@1x.png", "scale" : "1x" }, { "size" : "72x72", "idiom" : "ipad", "filename" : "Icon-App-72x72@2x.png", "scale" : "2x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@2x.png", "scale" : "2x" }, { "size" : "83.5x83.5", "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@1x.png", "scale" : "1x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "iphone", "filename" : "Icon-App-76x76@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@3x.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Assets.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Assets.xcassets/logo.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "Untitled-3.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "Untitled-2.png", "scale" : "2x" }, { "idiom" : "universal", "filename" : "Untitled-1.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Base.lproj/Main.storyboard ================================================ ================================================ FILE: iOS/User/ezshopUser/ezshopUser/CLFaceDetectionImagePicker.storyboard ================================================ ================================================ FILE: iOS/User/ezshopUser/ezshopUser/CLFaceDetectionImagePickerViewController.h ================================================ // // CLFaceDetectionViewController.h // // Created by caesar on 26/02/14. // #import typedef NS_ENUM(NSInteger, CLCaptureDevicePosition) { CLCaptureDevicePositionBack = 1, CLCaptureDevicePositionFront = 2 } NS_AVAILABLE(10_7, 4_0); // Keys for customize the pickerView behavior extern NSString *const CLTotalDetectCountDownSecond; //Total length of waiting period for face detection - Default: 10 extern NSString *const CLFaceDetectionSquareImageName; //Image name for the face detection square image - Default: CameraSquare extern NSString *const CLFaceDetectionTimes; //Continually detecting face times, this will be helpful to make sure the people are not shaking his head by purpose in order to give u a not-clear image - Default: 5 extern NSString *const CLCameraPosition; //Choose which camera you want to use, CLCaptureDevicePositionBack or CLCaptureDevicePositionFront -Default: CLCaptureDevicePositionFront @protocol CLFaceDetectionImagePickerDelegate -(void)CLFaceDetectionImagePickerDidDismiss: (NSData *)data blnSuccess:(BOOL)blnSuccess; @optional -(NSDictionary *)faceDetectionBehaviorAttributes; //Optional Function, Set the FaceDetectionPlugin behavior attributes by using above keys @end @interface CLFaceDetectionImagePickerViewController : UIViewController @property (nonatomic, weak) id delegate; @end ================================================ FILE: iOS/User/ezshopUser/ezshopUser/CLFaceDetectionImagePickerViewController.m ================================================ // // CLFaceDetectionImagePickerViewController.m // DeputyKiosk // // Created by caesar on 26/02/14. // Copyright (c) 2014 Caesar. All rights reserved. // #import "CLFaceDetectionImagePickerViewController.h" #import #import #import #import #import #import #import "UIImage+CL.h" #define TOTAL_TIMES_COUNT_DOWN 4 //This is initial waiting time when the imagePicker is firstly opened. //Attribute Keys NSString *const CLTotalDetectCountDownSecond = @"CLTotalDetectCountDownSecond"; NSString *const CLFaceDetectionSquareImageName = @"CLFaceDetectionSquareImageName"; NSString *const CLFaceDetectionTimes = @"CLFaceDetectionTimes"; NSString *const CLCameraPosition = @"CLCameraPosition"; //Default Values static NSInteger const CLTotalDetectCountDownSecondDefault = 10; static NSInteger const CLFaceDetectionTimesDefault = 5; static NSString* const CLFaceDetectionSquareImageNameDefault = @"CameraSquare"; static NSInteger const CLCameraPositionDefault = AVCaptureDevicePositionFront; @interface CLFaceDetectionImagePickerViewController () @property (nonatomic) NSInteger totalCountDownWaitingSecond; @property (nonatomic) NSInteger totalFaceDetectionTimes; @property (nonatomic) NSInteger cameraPosition; @property (nonatomic, strong) NSString *faceDetectionSquareImageName; @property (weak, nonatomic) IBOutlet UIView *preView; @property (nonatomic, strong) AVCaptureSession *session; @property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput; @property (nonatomic, strong) AVCaptureVideoDataOutput *videoDataOutput; @property (nonatomic) dispatch_queue_t videoDataOutputQueue; @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @property (nonatomic, strong) CIDetector *faceDetector; @property (nonatomic, strong) UIImage *square; @property (nonatomic) double timesDetectFace; @property (nonatomic) double timesCountDown; @property (nonatomic, strong) NSTimer *timerNoFaceDetect; @property (nonatomic, strong) NSNumber *blnDisableAutoFaceDetection; - (void)setupAVCapture; - (void)teardownAVCapture; - (void)drawFaceBoxesForFeatures:(NSArray *)features forVideoBox:(CGRect)videoBox orientation:(UIDeviceOrientation)orientation; @end @implementation CLFaceDetectionImagePickerViewController - (id) init { return [[UIStoryboard storyboardWithName:@"CLFaceDetectionImagePicker" bundle:nil] instantiateViewControllerWithIdentifier:@"CLFaceDetectionImagePickerViewController"]; } -(void)setDelegate:(id)delegate { _delegate = delegate; [self applyCustomDefaults]; } -(void)applyCustomDefaults { NSDictionary *attributes; if ([self.delegate respondsToSelector:@selector(faceDetectionBehaviorAttributes)]) { attributes = [self.delegate faceDetectionBehaviorAttributes]; } self.totalCountDownWaitingSecond = attributes[CLTotalDetectCountDownSecond] ? [attributes[CLTotalDetectCountDownSecond] integerValue] : CLTotalDetectCountDownSecondDefault; self.square = [UIImage imageNamed: attributes[CLFaceDetectionSquareImageName] ? attributes[CLFaceDetectionSquareImageName] : CLFaceDetectionSquareImageNameDefault]; self.cameraPosition = attributes[CLCameraPosition] ? [attributes[CLCameraPosition] integerValue ]: CLCameraPositionDefault; self.totalFaceDetectionTimes = attributes[CLFaceDetectionTimes] ? [attributes[CLFaceDetectionTimes] integerValue] : CLFaceDetectionTimesDefault; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [self setupAVCapture]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self teardownAVCapture]; self.faceDetector = nil; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(UIImage *)square { if(!_square){ _square = [UIImage imageNamed:CLFaceDetectionSquareImageNameDefault]; } return _square; } -(CIDetector *)faceDetector { if(!_faceDetector){ NSDictionary *detectorOptions = [[NSDictionary alloc] initWithObjectsAndKeys:CIDetectorAccuracyLow, CIDetectorAccuracy, nil]; _faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:detectorOptions]; } return _faceDetector; } - (void)setupAVCapture { self.timesDetectFace = 0; self.timesCountDown = TOTAL_TIMES_COUNT_DOWN; NSError *error = nil; self.session = [[AVCaptureSession alloc] init]; [self.session setSessionPreset:AVCaptureSessionPreset640x480]; //Do not set too high, otherwise face detection will be slow. // Select a video device, make an input AVCaptureDevice *device; AVCaptureDevicePosition desiredPosition = self.cameraPosition; // find the front facing camera for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if ([d position] == desiredPosition) { device = d; break; } } // fall back to the default camera. if( nil == device ) { error = [NSError errorWithDomain:NSOSStatusErrorDomain code:404 userInfo:@{@"message": @"No camera found."}]; } // get the input device AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if( !error ) { // add the input to the session if ( [self.session canAddInput:deviceInput] ){ [self.session addInput:deviceInput]; } // Make a still image output self.stillImageOutput = [AVCaptureStillImageOutput new]; // [stillImageOutput addObserver:self forKeyPath:@"capturingStillImage" options:NSKeyValueObservingOptionNew context:AVCaptureStillImageIsCapturingStillImageContext]; if ( [self.session canAddOutput:self.stillImageOutput] ) [self.session addOutput:self.stillImageOutput]; // Make a video data output self.videoDataOutput = [[AVCaptureVideoDataOutput alloc] init]; // we want BGRA, both CoreGraphics and OpenGL work well with 'BGRA' NSDictionary *rgbOutputSettings = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt:kCMPixelFormat_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; [self.videoDataOutput setVideoSettings:rgbOutputSettings]; [self.videoDataOutput setAlwaysDiscardsLateVideoFrames:YES]; // discard if the data output queue is blocked // create a serial dispatch queue used for the sample buffer delegate // a serial dispatch queue must be used to guarantee that video frames will be delivered in order // see the header doc for setSampleBufferDelegate:queue: for more information self.videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL); [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataOutputQueue]; if ( [self.session canAddOutput:self.videoDataOutput] ){ [self.session addOutput:self.videoDataOutput]; } // get the output for doing face detection. [[self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:YES]; self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session]; self.previewLayer.backgroundColor = [[UIColor blackColor] CGColor]; self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspect; if([self adjustOutputOrientation] == NO){ __weak typeof(self) weakSelf = self; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self dismissViewControllerAnimated:YES completion:^{ [self throwError:@"It seems your camera orientation is not set properly. Please make sure your iPad is in landscape position and try again." title:nil]; [weakSelf.delegate CLFaceDetectionImagePickerDidDismiss: nil blnSuccess:NO]; }]; }); return; } CALayer *rootLayer = [self.preView layer]; [rootLayer setMasksToBounds:YES]; [self.previewLayer setFrame:[rootLayer bounds]]; [rootLayer addSublayer:self.previewLayer]; [self.session startRunning]; self.timerNoFaceDetect = [NSTimer scheduledTimerWithTimeInterval:self.totalCountDownWaitingSecond target:self selector:@selector(noFaceDetected) userInfo:nil repeats:NO]; } if (error) { [self throwError:[error localizedDescription] title:[NSString stringWithFormat:@"Please make sure your front camera is allowed to be accessed. \nYou can check it in Settings. \nFailed with errorCode %d", (int)[error code]]]; [self teardownAVCapture]; } } // clean up capture setup - (void)teardownAVCapture { for(AVCaptureInput *input in self.session.inputs){ [self.session removeInput:input]; } for(AVCaptureOutput *output in self.session.outputs){ [self.session removeOutput:output]; } [self.session stopRunning]; self.videoDataOutput = nil; self.videoDataOutputQueue = nil; [self.previewLayer removeFromSuperlayer]; self.previewLayer = nil; } - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { // get the image CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CFDictionaryRef attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault, sampleBuffer, kCMAttachmentMode_ShouldPropagate); CIImage *ciImage = [[CIImage alloc] initWithCVPixelBuffer:pixelBuffer options:(__bridge NSDictionary *)attachments]; if (attachments) { CFRelease(attachments); } // make sure your device orientation is not locked. UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation]; if(!self.blnDisableAutoFaceDetection.intValue){ NSDictionary *imageOptions = nil; imageOptions = [NSDictionary dictionaryWithObject:[self exifOrientation:curDeviceOrientation] forKey:CIDetectorImageOrientation]; NSArray *features = [self.faceDetector featuresInImage:ciImage options:imageOptions]; if(!features.count){ self.timesDetectFace = 0; return; } if(self.timesDetectFace > self.totalFaceDetectionTimes){ return; } self.timesDetectFace++; // get the clean aperture // the clean aperture is a rectangle that defines the portion of the encoded pixel dimensions // that represents image data valid for display. CMFormatDescriptionRef fdesc = CMSampleBufferGetFormatDescription(sampleBuffer); CGRect clap = CMVideoFormatDescriptionGetCleanAperture(fdesc, false /*originIsTopLeft == false*/); dispatch_async(dispatch_get_main_queue(), ^(void) { [self drawFaceBoxesForFeatures:features forVideoBox:clap orientation:curDeviceOrientation]; }); }else{ if(self.timesCountDown < 0) return; self.timesCountDown -= 0.03; CMFormatDescriptionRef fdesc = CMSampleBufferGetFormatDescription(sampleBuffer); CGRect clap = CMVideoFormatDescriptionGetCleanAperture(fdesc, false /*originIsTopLeft == false*/); dispatch_async(dispatch_get_main_queue(), ^(void) { [self drawCountDownforVideoBox:clap orientation:curDeviceOrientation]; }); } if(self.timesDetectFace >= self.totalFaceDetectionTimes || self.timesCountDown <= 0){ [self.timerNoFaceDetect invalidate]; CIContext *temporaryContext = [CIContext contextWithOptions:nil]; CGImageRef videoImage = [temporaryContext createCGImage:ciImage fromRect:CGRectMake(0, 0, CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer))]; UIImage *picture = [[UIImage imageWithCGImage:videoImage] imageRotatedWithDeviceOrientation:YES]; NSData *compressedData = UIImageJPEGRepresentation(picture, 1.0); [self doCloseCaptureAndDelegateClientWithData:compressedData]; } } // utility routing used during image capture to set up capture orientation - (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation { AVCaptureVideoOrientation result = AVCaptureVideoOrientationLandscapeLeft; if ( deviceOrientation == UIDeviceOrientationLandscapeLeft ) result = AVCaptureVideoOrientationLandscapeRight; else if ( deviceOrientation == UIDeviceOrientationLandscapeRight ) result = AVCaptureVideoOrientationLandscapeLeft; return result; } -(BOOL)shouldAutorotate { return [self adjustOutputOrientation]; } -(BOOL)adjustOutputOrientation { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if(orientation != UIDeviceOrientationLandscapeLeft && orientation != UIDeviceOrientationLandscapeRight){ return NO; } [self.previewLayer.connection setVideoOrientation:[self avOrientationForDeviceOrientation:orientation]]; return YES; } - (NSNumber *) exifOrientation: (UIDeviceOrientation) orientation { int exifOrientation; /* kCGImagePropertyOrientation values The intended display orientation of the image. If present, this key is a CFNumber value with the same value as defined by the TIFF and EXIF specifications -- see enumeration of integer constants. The value specified where the origin (0,0) of the image is located. If not present, a value of 1 is assumed. used when calling featuresInImage: options: The value for this key is an integer NSNumber from 1..8 as found in kCGImagePropertyOrientation. If present, the detection will be done based on that orientation but the coordinates in the returned features will still be based on those of the image. */ enum { PHOTOS_EXIF_0ROW_TOP_0COL_LEFT = 1, // 1 = 0th row is at the top, and 0th column is on the left (THE DEFAULT). PHOTOS_EXIF_0ROW_TOP_0COL_RIGHT = 2, // 2 = 0th row is at the top, and 0th column is on the right. PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT = 3, // 3 = 0th row is at the bottom, and 0th column is on the right. PHOTOS_EXIF_0ROW_BOTTOM_0COL_LEFT = 4, // 4 = 0th row is at the bottom, and 0th column is on the left. PHOTOS_EXIF_0ROW_LEFT_0COL_TOP = 5, // 5 = 0th row is on the left, and 0th column is the top. PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP = 6, // 6 = 0th row is on the right, and 0th column is the top. PHOTOS_EXIF_0ROW_RIGHT_0COL_BOTTOM = 7, // 7 = 0th row is on the right, and 0th column is the bottom. PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM = 8 // 8 = 0th row is on the left, and 0th column is the bottom. }; switch (orientation) { case UIDeviceOrientationPortraitUpsideDown: // Device oriented vertically, home button on the top exifOrientation = PHOTOS_EXIF_0ROW_LEFT_0COL_BOTTOM; break; case UIDeviceOrientationLandscapeLeft: // Device oriented horizontally, home button on the right // if (self.isUsingFrontFacingCamera) exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT; // else // exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT; break; case UIDeviceOrientationLandscapeRight: // Device oriented horizontally, home button on the left // if (self.isUsingFrontFacingCamera) exifOrientation = PHOTOS_EXIF_0ROW_TOP_0COL_LEFT; // else // exifOrientation = PHOTOS_EXIF_0ROW_BOTTOM_0COL_RIGHT; break; case UIDeviceOrientationPortrait: // Device oriented vertically, home button on the bottom default: exifOrientation = PHOTOS_EXIF_0ROW_RIGHT_0COL_TOP; break; } return [NSNumber numberWithInt:exifOrientation]; } -(void)doCloseCaptureAndDelegateClientWithData: (NSData *)data { __weak typeof(self) weakSelf = self; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self dismissViewControllerAnimated:YES completion:^{ if(!data){ [self throwError:@"Sorry, we cannot detect your face." title:nil]; } [weakSelf.delegate CLFaceDetectionImagePickerDidDismiss: data blnSuccess:(data)?YES:NO]; }]; }); } -(void)noFaceDetected { [self doCloseCaptureAndDelegateClientWithData:nil]; } // find where the video box is positioned within the preview layer based on the video size and gravity + (CGRect)videoPreviewBoxForGravity:(NSString *)gravity frameSize:(CGSize)frameSize apertureSize:(CGSize)apertureSize { CGFloat apertureRatio = apertureSize.height / apertureSize.width; CGFloat viewRatio = frameSize.width / frameSize.height; CGSize size = CGSizeZero; if ([gravity isEqualToString:AVLayerVideoGravityResizeAspectFill]) { if (viewRatio > apertureRatio) { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } else { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } } else if ([gravity isEqualToString:AVLayerVideoGravityResizeAspect]) { if (viewRatio > apertureRatio) { size.width = apertureSize.height * (frameSize.height / apertureSize.width); size.height = frameSize.height; } else { size.width = frameSize.width; size.height = apertureSize.width * (frameSize.width / apertureSize.height); } } else if ([gravity isEqualToString:AVLayerVideoGravityResize]) { size.width = frameSize.width; size.height = frameSize.height; } CGRect videoBox; videoBox.size = size; if (size.width < frameSize.width) videoBox.origin.x = (frameSize.width - size.width) / 2; else videoBox.origin.x = (size.width - frameSize.width) / 2; if ( size.height < frameSize.height ) videoBox.origin.y = (frameSize.height - size.height) / 2; else videoBox.origin.y = (size.height - frameSize.height) / 2; return videoBox; } -(void)drawCountDownforVideoBox:(CGRect)clap orientation:(UIDeviceOrientation)orientation { NSArray *sublayers = [NSArray arrayWithArray:[self.previewLayer sublayers]]; NSInteger sublayersCount = [sublayers count], currentSublayer = 0; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; // hide all the CountDownLayer layers for ( CATextLayer *layer in sublayers ) { if ( [[layer name] isEqualToString:@"CountDownLayer"] ) [layer setHidden:YES]; } CGSize parentFrameSize = [self.preView frame].size; CATextLayer *featureLayer = nil; // re-use an existing layer if possible while ( !featureLayer && (currentSublayer < sublayersCount) ) { CATextLayer *currentLayer = [sublayers objectAtIndex:currentSublayer++]; if ( [[currentLayer name] isEqualToString:@"CountDownLayer"] ) { featureLayer = currentLayer; [currentLayer setHidden:NO]; } } // create a new one if necessary if ( !featureLayer ) { featureLayer = [CATextLayer new]; // [featureLayer setContents:(id)[self.square CGImage]]; [featureLayer setFont:@"Helvetica-Bold"]; [featureLayer setFontSize:90]; [featureLayer setAlignmentMode:kCAAlignmentCenter]; [featureLayer setForegroundColor:[[UIColor whiteColor] CGColor]]; [featureLayer setName:@"CountDownLayer"]; [self.previewLayer addSublayer:featureLayer]; } int countDown = @(self.timesCountDown).intValue; NSString *strCountDown = (countDown > 0)?[NSString stringWithFormat:@"%d", countDown]:@"Smile"; [featureLayer setString: strCountDown]; [featureLayer setFrame:CGRectMake( (parentFrameSize.width-300)/2, (parentFrameSize.height-300)/2, 300, 300)]; [CATransaction commit]; } // called asynchronously as the capture output is capturing sample buffers, this method asks the face detector (if on) // to detect features and for each draw the red square in a layer and set appropriate orientation - (void)drawFaceBoxesForFeatures:(NSArray *)features forVideoBox:(CGRect)clap orientation:(UIDeviceOrientation)orientation { NSArray *sublayers = [NSArray arrayWithArray:[self.previewLayer sublayers]]; NSInteger sublayersCount = [sublayers count], currentSublayer = 0; NSInteger featuresCount = [features count], currentFeature = 0; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; // hide all the face layers for ( CALayer *layer in sublayers ) { if ( [[layer name] isEqualToString:@"FaceLayer"] ) [layer setHidden:YES]; } if ( featuresCount == 0) { [CATransaction commit]; return; // early bail. } CGSize parentFrameSize = [self.preView frame].size; NSString *gravity = [self.previewLayer videoGravity]; CGRect previewBox = [CLFaceDetectionImagePickerViewController videoPreviewBoxForGravity:gravity frameSize:parentFrameSize apertureSize:clap.size]; for ( CIFaceFeature *ff in features ) { CGRect faceRect = [ff bounds]; // scale coordinates so they fit in the preview box, which may be scaled CGFloat widthScaleBy = previewBox.size.width / clap.size.width; CGFloat heightScaleBy = previewBox.size.height / clap.size.height; faceRect.origin.x *= widthScaleBy; faceRect.origin.y *= heightScaleBy; faceRect = CGRectOffset(faceRect, previewBox.origin.x, previewBox.origin.y); CALayer *featureLayer = nil; // re-use an existing layer if possible while ( !featureLayer && (currentSublayer < sublayersCount) ) { CALayer *currentLayer = [sublayers objectAtIndex:currentSublayer++]; if ( [[currentLayer name] isEqualToString:@"FaceLayer"] ) { featureLayer = currentLayer; [currentLayer setHidden:NO]; } } // create a new one if necessary if ( !featureLayer ) { featureLayer = [CALayer new]; [featureLayer setContents:(id)[self.square CGImage]]; [featureLayer setName:@"FaceLayer"]; [self.previewLayer addSublayer:featureLayer]; } [featureLayer setFrame:faceRect]; currentFeature++; } [CATransaction commit]; } //Throw Error -(void) throwError:(NSString *)error title:(NSString *)title { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: title message:error delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; [alertView show]; } @end ================================================ FILE: iOS/User/ezshopUser/ezshopUser/GoogleService-Info.plist ================================================ AD_UNIT_ID_FOR_BANNER_TEST ca-app-pub-3940256099942544/2934735716 AD_UNIT_ID_FOR_INTERSTITIAL_TEST ca-app-pub-3940256099942544/4411468910 CLIENT_ID 89251823040-okn0k3k9n4j5a0a5lacef55e7qh804gv.apps.googleusercontent.com REVERSED_CLIENT_ID com.googleusercontent.apps.89251823040-okn0k3k9n4j5a0a5lacef55e7qh804gv API_KEY AIzaSyBobTBUxfcSLf7pX1N9c0z3qlqtK3tpjSE GCM_SENDER_ID 89251823040 PLIST_VERSION 1 BUNDLE_ID ca.jgchoi.ezshopUser PROJECT_ID hackvalley-5be01 STORAGE_BUCKET hackvalley-5be01.appspot.com IS_ADS_ENABLED IS_ANALYTICS_ENABLED IS_APPINVITE_ENABLED IS_GCM_ENABLED IS_SIGNIN_ENABLED GOOGLE_APP_ID 1:89251823040:ios:cf467df61c13d17f DATABASE_URL https://hackvalley-5be01.firebaseio.com ================================================ FILE: iOS/User/ezshopUser/ezshopUser/HudView.swift ================================================ // // HudView.swift // MyLocations // // Created by Jung Geon Choi on 2017-03-05. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit class HudView: UIView { var text = "" class func hud(inView view: UIView, animated: Bool) -> HudView { let hudView = HudView(frame: view.bounds) hudView.isOpaque = false view.addSubview(hudView) view.isUserInteractionEnabled = false // hudView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) hudView.show(animated: animated) return hudView } override func draw(_ rect: CGRect) { let boxWidth: CGFloat = 96 let boxHeight: CGFloat = 96 let boxRect = CGRect(x: round(bounds.size.width - boxWidth) / 2, y: round(bounds.size.height - boxHeight) / 2, width: boxWidth, height: boxHeight) let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10) UIColor(white: 0.3, alpha: 0.8).setFill() roundedRect.fill() if let image = UIImage(named: "Checkmark") { let imagePoint = CGPoint(x: center.x - round(image.size.width / 2), y: center.y - round(image.size.height / 2) - boxHeight / 8) image.draw(at: imagePoint) } let attribs = [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.white] let textSize = text.size(attributes: attribs) let textPoint = CGPoint(x: center.x - round(textSize.width/2), y: center.y - round(textSize.height/2) + boxHeight/4) text.draw(at: textPoint, withAttributes: attribs) } func show(animated: Bool) { if animated { alpha = 0 transform = CGAffineTransform(scaleX: 1.3, y: 1.3) // UIView.animate(withDuration: 0.3, animations: { UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: { self.alpha = 1 self.transform = CGAffineTransform.identity }, completion: nil) } } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleVersion 1 LSRequiresIPhoneOS NSCameraUsageDescription Use camera to take photo of user to login UILaunchStoryboardName Main UIMainStoryboardFile Main UIRequiredDeviceCapabilities armv7 UIStatusBarStyle UIStatusBarStyleLightContent UISupportedInterfaceOrientations UIInterfaceOrientationPortrait ================================================ FILE: iOS/User/ezshopUser/ezshopUser/Item.swift ================================================ // // Item.swift // EZShopManager // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import Foundation class Item { var item_name = "" var item_id = 0 var item_price = 0.0 } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/JGUtils.swift ================================================ // // JGUtils.swift // emii // // Created by Jung Geon Choi on 2017-03-04. // Copyright © 2017 Emanant Inc. All rights reserved. // import Foundation import SwiftyJSON import UIKit class JGUtils { // MARK: - Variables static var vc: UIViewController { get { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } print("Failed to find first view controller @ JGUtils.getFrontViewController()") return UIViewController() } } static func alert(title: String, message: String?, buttonMessage: String = "OK", closure:@escaping (() -> ())) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: buttonMessage, style: .cancel, handler: { (_) in closure() })) vc.present(alert, animated: true, completion: nil) } // MARK: - Alert ONLY static func alert(title: String, message: String?, buttonMessage: String = "OK") { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: buttonMessage, style: .cancel, handler: nil)) vc.present(alert, animated: true, completion: nil) } // MARK: - Selection Alert } // MARK: - View Extension extension UIView { var animationDuration: TimeInterval { get { return 0.5 } } func hide() { self.alpha = 1.0 UIView.animate(withDuration: animationDuration) { self.alpha = 0.0 } } func show() { self.alpha = 0.0 UIView.animate(withDuration: animationDuration) { self.alpha = 1.0 } } } extension JSON { func hasError() -> Bool { let error = self["error"]["message"].stringValue return !error.isEmpty } var errorMessage: String { get { return self["error"]["message"].stringValue } } } // MARK: - Statusbard Indicator extension JGUtils { static func setNetworkIndicator(_ status: Bool) { UIApplication.shared.isNetworkActivityIndicatorVisible = status } } extension UIColor { static public var tint: UIColor { return UIColor( red: CGFloat(73.0/255.0), green: CGFloat(188.0/255.0), blue: CGFloat(167.0/255.0), alpha: CGFloat(1.0) ) } } // MARK: - String extension String { var formattedPhoneNumber: String { return "(" + self[0..<3] + ") " + self[3..<6] + "-" + self[6..<10] } var length: Int { return self.characters.count } subscript (i: Int) -> String { return self[Range(i ..< i + 1)] } func substring(from: Int) -> String { return self[Range(min(from, length) ..< length)] } func substring(to: Int) -> String { return self[Range(0 ..< max(0, to))] } subscript (r: Range) -> String { let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound)))) let start = index(startIndex, offsetBy: range.lowerBound) let end = index(start, offsetBy: range.upperBound - range.lowerBound) return self[Range(start ..< end)] } } // MARK: - Notification extension Notification.Name { static let tokenReceivedFromWeb = Notification.Name("ReceivedTokenFromWeb") } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/UIImage+CL.h ================================================ // // UIImage+CL.h // CLFaceDetectionImagePicker // // Created by Caesar on 10/12/2014. // Copyright (c) 2014 Caesar. All rights reserved. // #import @interface UIImage (CL) - (UIImage *)imageRotatedWithDeviceOrientation: (BOOL)isFrontFacing; @end ================================================ FILE: iOS/User/ezshopUser/ezshopUser/UIImage+CL.m ================================================ // // UIImage+CL.m // CLFaceDetectionImagePicker // // Created by Caesar on 10/12/2014. // Copyright (c) 2014 Caesar. All rights reserved. // #import "UIImage+CL.h" @implementation UIImage (CL) static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;}; - (UIImage *)imageRotatedWithDeviceOrientation: (BOOL)isFrontFacing { CGFloat degrees = 0.; UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; switch (orientation) { case UIDeviceOrientationPortrait: degrees = -90.; break; case UIDeviceOrientationPortraitUpsideDown: degrees = 90.; break; case UIDeviceOrientationLandscapeLeft: if (isFrontFacing) degrees = 180.; else degrees = 0.; break; case UIDeviceOrientationLandscapeRight: if (isFrontFacing) degrees = 0.; else degrees = 180.; break; case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: default: break; // leave the layer in its last known orientation } // calculate the size of the rotated view's containing box for our drawing space UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)]; CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees)); rotatedViewBox.transform = t; CGSize rotatedSize = rotatedViewBox.frame.size; // Create the bitmap context UIGraphicsBeginImageContext(rotatedSize); CGContextRef bitmap = UIGraphicsGetCurrentContext(); // Move the origin to the middle of the image so we will rotate and scale around the center. CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2); // // Rotate the image context CGContextRotateCTM(bitmap, DegreesToRadians(degrees)); // Now, draw the rotated/scaled image into the context CGContextScaleCTM(bitmap, 1.0, -1.0); CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; } @end ================================================ FILE: iOS/User/ezshopUser/ezshopUser/User.swift ================================================ import UIKit class User { static var instance = User() var name = "" var photo = "" var user_id = "" var isInStore = false var items: [Item] = [] static func setUserName(name: String) { UserDefaults.standard.set(name, forKey: "UserNameKey") UserDefaults.standard.synchronize() } static func getUserName() -> String { if UserDefaults.standard.string(forKey: "UserNameKey") == nil { return "" } return UserDefaults.standard.string(forKey: "UserNameKey")! } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/UserViewController.swift ================================================ // // UserViewController.swift // ezshopUser // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import FirebaseDatabase import Kingfisher import FirebaseMessaging import SwiftyJSON import Firebase //import FirebaseMessaging import UserNotifications class UserViewController: UIViewController { var ref: FIRDatabaseReference! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var totalLabel: UILabel! @IBAction func logout(_ sender: Any) { ref.child("users").child(User.instance.user_id).updateChildValues(["fcm_token":"invalid"]) User.instance = User() User.setUserName(name: "") performSegue(withIdentifier: "ShowLogin", sender: nil) } @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var circleView: UIView! @IBOutlet weak var nameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() imageView.layer.cornerRadius = imageView.frame.width/2 imageView.clipsToBounds = true circleView.layer.cornerRadius = circleView.frame.width/2 updateView() self.ref = FIRDatabase.database().reference() ref.child("users").child(User.instance.user_id).updateChildValues(["fcm_token":FIRInstanceID.instanceID().token()]) let refHandle = self.ref.observe(FIRDataEventType.value, with: { (snapshot) in let db = JSON(snapshot.value) //print(db["users"]) if let _users = db["users"].dictionary { _users.forEach({ (_, _userJSON) in if User.instance.user_id == _userJSON["user_id"].stringValue { let new = User() print(_userJSON["user_id"].stringValue) new.name = _userJSON["name"].stringValue new.photo = _userJSON["photo"].stringValue new.user_id = _userJSON["user_id"].stringValue new.isInStore = _userJSON["is_in_store"].boolValue if let store = db["store"].dictionary { if let _items = store[new.user_id]?["cart"].arrayObject as? [Int] { print(store[new.user_id]) print(_items) _items.forEach({ (_item_id) in if _item_id > 0 { let newItem = Item() newItem.item_id = _item_id let _itemDetails = db["inventories"][_item_id].dictionaryValue newItem.item_name = _itemDetails["item_name"]!.stringValue newItem.item_price = _itemDetails["item_price"]!.doubleValue new.items.append(newItem) } }) } } User.instance = new self.updateView() } }) } }) } func updateView() { tableView.reloadData() totalLabel.text = "" if User.instance.isInStore { var total = 0.00 User.instance.items.forEach({ (item) in total += item.item_price }) totalLabel.text = String(format: "$ %.2f", total) } nameLabel.text = User.instance.name statusLabel.text = User.instance.isInStore ? "Currently you are in store" : "Currently you are not in store" circleView.clipsToBounds = true var transform = CGAffineTransform(scaleX: 0.5, y: 0.5) // circleView.transform = CGAffineTransform.identity // imageView.transform = CGAffineTransform.identity UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: [], animations: { var transform = CGAffineTransform(scaleX: 0.5, y: 0.5) self.circleView.transform = transform self.imageView.transform = transform }) { (_) in UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: [], animations: { self.circleView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.circleView.backgroundColor = User.instance.isInStore ? UIColor.green : UIColor.red }, completion: nil) } tableView.tableFooterView = UIView() cartCover.removeFromSuperview() imageView.kf.setImage(with: URL(string: User.instance.photo)) if User.instance.items.count == 0 { cartCover = UIView(frame: tableView.frame) cartCover.backgroundColor = UIColor.white let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: tableView.frame.width, height: 20))) label.text = "Cart is Empty" label.textColor = UIColor.black.withAlphaComponent(0.5) label.textAlignment = .center label.frame = CGRect(x: 0, y: tableView.frame.height/2, width: tableView.frame.width, height: 30) label.font = UIFont.italicSystemFont(ofSize: 15) // label.center = cartCover.center cartCover.addSubview(label) view.addSubview(cartCover) } } var cartCover = UIView() /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension UserViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return User.instance.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) let item = User.instance.items[indexPath.row] cell.textLabel?.text = item.item_name cell.detailTextLabel?.text = "$ \(item.item_price)" return cell } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/ViewController.swift ================================================ // // ViewController.swift // ezshopUser // // Created by Jung Geon Choi on 2017-03-18. // Copyright © 2017 Jung Geon Choi. All rights reserved. // import UIKit import FirebaseDatabase import SwiftyJSON struct KairosConfig { static let app_id = "4724eb0e" static let app_key = "f5795e224117ac3393343c6bc14c841b" } class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var ref: FIRDatabaseReference! @IBAction func login() { let imagePicker = UIImagePickerController() imagePicker.view.tintColor = view.tintColor imagePicker.sourceType = .camera imagePicker.delegate = self imagePicker.cameraDevice = .front imagePicker.allowsEditing = true present(imagePicker, animated: true) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func clFaceDetectionImagePickerDidDismiss(_ data: Data!, blnSuccess: Bool) { if data != nil { if let image = UIImage(data: data) { let Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key) let imageData = UIImageJPEGRepresentation(image, 1) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop" ] Kairos.request(method: "recognize", data: jsonBody) { data in let json = JSON(data) print(json) } } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { dismiss(animated: true, completion: nil) ActivityIndicator.shared.show(self.view) if let image = info[UIImagePickerControllerEditedImage] as? UIImage { let Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key) let imageData = UIImageJPEGRepresentation(image, 1) let base64ImageData = imageData?.base64EncodedString(options:[]) // setup json request params, with base64 data let jsonBody = [ "image": base64ImageData, "gallery_name": "ezshop" ] Kairos.request(method: "recognize", data: jsonBody) { data in let json = JSON(data) // print(json) let images = json["images"].arrayValue let image = images.first?.dictionaryValue let candidates = image?["candidates"]?.arrayValue let candidate = candidates?.first print(candidate?["subject_id"]) print(candidate?["confidence"]) if let candidate = candidate { let subject_id = candidate["subject_id"].stringValue let confidence = Int(candidate["confidence"].doubleValue * 100.0) if confidence < 60 { ActivityIndicator.shared.hide() JGUtils.alert(title: "Error", message: "Too low confidence") } else { self.ref = FIRDatabase.database().reference() let refHandle = self.ref.observe(FIRDataEventType.value, with: { (snapshot) in let db = JSON(snapshot.value) self.ref.removeAllObservers() //print(db["users"]) if let _users = db["users"].dictionary { _users.forEach({ (_, _userJSON) in if subject_id == _userJSON["user_id"].stringValue { let new = User() print(_userJSON["user_id"].stringValue) new.name = _userJSON["name"].stringValue new.photo = _userJSON["photo"].stringValue new.user_id = _userJSON["user_id"].stringValue new.isInStore = _userJSON["is_in_store"].boolValue if let store = db["store"].dictionary { if let _items = store[new.user_id]?["cart"].arrayObject as? [Int] { print(store[new.user_id]) print(_items) _items.forEach({ (_item_id) in if _item_id > 0 { let newItem = Item() newItem.item_id = _item_id let _itemDetails = db["inventories"][_item_id].dictionaryValue newItem.item_name = _itemDetails["item_name"]!.stringValue newItem.item_price = _itemDetails["item_price"]!.doubleValue new.items.append(newItem) } }) } } User.instance = new } }) } if User.instance.name == "" { ActivityIndicator.shared.hide() JGUtils.alert(title: "ERROR", message: "This user is not registered") } else { // User.setUserName(name: self.userNameLabel.text!) JGUtils.alert(title: "WELCOME", message: "Hello, \(User.instance.name)!", closure: { ActivityIndicator.shared.hide() self.performSegue(withIdentifier: "ShowUser", sender: nil) }) User.setUserName(name: User.instance.user_id) // self.userNameLabel.text = "" } }) } } else { DispatchQueue.main.sync { JGUtils.alert(title: "ERROR", message: "Could not find the match") ActivityIndicator.shared.hide() } } } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.ref = FIRDatabase.database().reference() let refHandle = self.ref.observe(FIRDataEventType.value, with: { (snapshot) in let db = JSON(snapshot.value) //print(db["users"]) if let _users = db["users"].dictionary { _users.forEach({ (_, _userJSON) in if User.getUserName() == _userJSON["user_id"].stringValue { let new = User() print(_userJSON["user_id"].stringValue) new.name = _userJSON["name"].stringValue new.photo = _userJSON["photo"].stringValue new.user_id = _userJSON["user_id"].stringValue new.isInStore = _userJSON["is_in_store"].boolValue if let store = db["store"].dictionary { if let _items = store[new.user_id]?["cart"].arrayObject as? [Int] { print(store[new.user_id]) print(_items) _items.forEach({ (_item_id) in if _item_id > 0 { let newItem = Item() newItem.item_id = _item_id let _itemDetails = db["inventories"][_item_id].dictionaryValue newItem.item_name = _itemDetails["item_name"]!.stringValue newItem.item_price = _itemDetails["item_price"]!.doubleValue new.items.append(newItem) } }) } } User.instance = new } }) } if User.instance.name == "" { // JGUtils.alert(title: "ERROR", message: "This user is not registered") } else { // User.setUserName(name: self.userNameLabel.text!) // JGUtils.alert(title: "WELCOME", message: "Hello \(User.instance.name)\n\n\(confidence)% confidence", closure: { ActivityIndicator.shared.hide() self.performSegue(withIdentifier: "ShowUser", sender: nil) // }) // User.setUserName(name: User.instance.user_id) // self.userNameLabel.text = "" } }) } } // userNameLabel.text = User.getUserName() // ref = FIRDatabase.database().reference() // let refHandle = ref.observe(FIRDataEventType.value, with: { (snapshot) in // let db = JSON(snapshot.value) // //print(db["users"]) // // if let _users = db["users"].dictionary { // _users.forEach({ (_, _userJSON) in // if self.userNameLabel.text?.lowercased() == _userJSON["name"].stringValue.lowercased() { // let new = User() // print(_userJSON["user_id"].stringValue) // new.name = _userJSON["name"].stringValue // new.photo = _userJSON["photo"].stringValue // new.user_id = _userJSON["user_id"].stringValue // new.isInStore = _userJSON["is_in_store"].boolValue // // if let store = db["store"].dictionary { // if let _items = store[new.user_id]?["cart"].arrayObject as? [Int] { // print(store[new.user_id]) // print(_items) // _items.forEach({ (_item_id) in // let newItem = Item() // newItem.item_id = _item_id // // let _itemDetails = db["inventories"][_item_id].dictionaryValue // newItem.item_name = _itemDetails["item_name"]!.stringValue // newItem.item_price = _itemDetails["item_price"]!.doubleValue // new.items.append(newItem) // }) // } // } // // User.instance = new // } // }) // } // if User.instance.name == "" { // // JGUtils.alert(title: "ERROR", message: "This user is not registered") // } else { // self.performSegue(withIdentifier: "ShowUser", sender: nil) // self.userNameLabel.text = "" // } // }) // } ================================================ FILE: iOS/User/ezshopUser/ezshopUser/ezshopUser-Bridging-Header.h ================================================ // // Use this file to import your target's public headers that you would like to expose to Swift. // #import "CLFaceDetectionImagePickerViewController.h" #import "UIImage+CL.h" ================================================ FILE: iOS/User/ezshopUser/ezshopUser/ezshopUser.entitlements ================================================ aps-environment development ================================================ FILE: iOS/User/ezshopUser/ezshopUser/kairos.swift ================================================ /* * Copyright (c) 2017, Kairos AR, Inc. * All rights reserved. * * Api Docs: https://www.kairos.com/docs/api/ * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ import UIKit public class KairosAPI { let api_url: String = "https://api.kairos.com/" let app_id: String let app_key: String var headers: HTTPURLResponse? public init(app_id: String, app_key: String) { self.app_id = app_id self.app_key = app_key } public func convertImageToBase64String(file: String) -> String { let image = UIImage(named: file) let imageData = UIImageJPEGRepresentation(image!, 0) let base64String = imageData?.base64EncodedString(options:[]) return base64String! } // Kairos API - HTTP Request public func send(url:String, data: Dictionary? = [:], httpType: String, taskCallback: @escaping (Bool, AnyObject, AnyObject?) -> ()) -> Void { let jsonData = try? JSONSerialization.data(withJSONObject: data!) // create post request with headers let urlObject = URL(string: url)! var request = URLRequest(url: urlObject) request.httpMethod = httpType request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(self.app_id, forHTTPHeaderField: "app_id") request.addValue(self.app_key, forHTTPHeaderField: "app_key") // insert json data to the request request.httpBody = jsonData URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil) let session = URLSession(configuration: URLSessionConfiguration.default) let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if let data = data { let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: []) let jsonErrors = (jsonResponse as? [String : AnyObject])?["Errors"] self.headers = response as? HTTPURLResponse if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode, jsonErrors == nil { taskCallback(true, jsonResponse as AnyObject!, jsonErrors as AnyObject?) } else { self.getError(errors: jsonErrors as AnyObject?) } } }) task.resume() } public func getError(errors: AnyObject?) -> Void { let errorCode = self.headers!.statusCode let errorMessage = "Could not get response" if errors != nil { } DispatchQueue.main.sync { ActivityIndicator.shared.hide() JGUtils.alert(title: "ERROR", message: errorMessage + "\nERROR CODE(\(errorCode))") } print("Error (\(errorCode)): \(errorMessage)") } public func request(method: String, data: Dictionary? = [:], httpTypeOverride: Any? = nil, callback: @escaping (AnyObject) -> ()) -> Void { let url = (self.api_url + method).replacingOccurrences(of: "\\/{2,}", with: "/", options: .regularExpression, range: nil) var httpType: String = "POST" // default let matchMediaId = "/v2/(media|analytics)/[a-z0-9]+" let range = url.range(of: matchMediaId, options: .regularExpression) if range != nil { httpType = "GET" } if httpTypeOverride != nil { httpType = httpTypeOverride as! String } self.send(url: url, data: data, httpType: httpType) { (ok, data, errors) in // if http error then display it if ok == false { self.getError(errors: errors) return } // else pass the data along callback(data) } } } ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 9C43599ED3F692D8EA185E21 /* Pods_ezshopUser.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 46DBEF9CAFC2C0D784347B44 /* Pods_ezshopUser.framework */; }; D24519271E7D8488000ECC03 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24519261E7D8488000ECC03 /* AppDelegate.swift */; }; D24519291E7D8488000ECC03 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24519281E7D8488000ECC03 /* ViewController.swift */; }; D245192C1E7D8488000ECC03 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D245192A1E7D8488000ECC03 /* Main.storyboard */; }; D245192E1E7D8488000ECC03 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D245192D1E7D8488000ECC03 /* Assets.xcassets */; }; D24519391E7D8568000ECC03 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = D24519381E7D8568000ECC03 /* GoogleService-Info.plist */; }; D245193C1E7D86E1000ECC03 /* JGUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = D245193A1E7D86E1000ECC03 /* JGUtils.swift */; }; D245193D1E7D86E2000ECC03 /* ActivitiyIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D245193B1E7D86E1000ECC03 /* ActivitiyIndicator.swift */; }; D245193F1E7D8728000ECC03 /* User.swift in Sources */ = {isa = PBXBuildFile; fileRef = D245193E1E7D8728000ECC03 /* User.swift */; }; D24519411E7D872C000ECC03 /* Item.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24519401E7D872B000ECC03 /* Item.swift */; }; D24519431E7D8BB5000ECC03 /* UserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24519421E7D8BB5000ECC03 /* UserViewController.swift */; }; D245194A1E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = D24519461E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.m */; }; D245194B1E7D967A000ECC03 /* CLFaceDetectionImagePicker.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D24519471E7D967A000ECC03 /* CLFaceDetectionImagePicker.storyboard */; }; D245194C1E7D967A000ECC03 /* UIImage+CL.m in Sources */ = {isa = PBXBuildFile; fileRef = D24519491E7D967A000ECC03 /* UIImage+CL.m */; }; D245194E1E7D96E7000ECC03 /* kairos.swift in Sources */ = {isa = PBXBuildFile; fileRef = D245194D1E7D96E7000ECC03 /* kairos.swift */; }; D25E556A1E7E2542000B18D8 /* HudView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D25E55691E7E2542000B18D8 /* HudView.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 46DBEF9CAFC2C0D784347B44 /* Pods_ezshopUser.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_ezshopUser.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9DB79685D4C2A6A6E0AA60A0 /* Pods-ezshopUser.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ezshopUser.release.xcconfig"; path = "Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser.release.xcconfig"; sourceTree = ""; }; A1A2C175D85E21E953053C9F /* Pods-ezshopUser.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ezshopUser.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser.debug.xcconfig"; sourceTree = ""; }; D24519231E7D8488000ECC03 /* ezshopUser.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ezshopUser.app; sourceTree = BUILT_PRODUCTS_DIR; }; D24519261E7D8488000ECC03 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; D24519281E7D8488000ECC03 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; D245192B1E7D8488000ECC03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; D245192D1E7D8488000ECC03 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; D24519321E7D8488000ECC03 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; D24519381E7D8568000ECC03 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; D245193A1E7D86E1000ECC03 /* JGUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JGUtils.swift; sourceTree = ""; }; D245193B1E7D86E1000ECC03 /* ActivitiyIndicator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ActivitiyIndicator.swift; sourceTree = ""; }; D245193E1E7D8728000ECC03 /* User.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = User.swift; sourceTree = ""; }; D24519401E7D872B000ECC03 /* Item.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Item.swift; sourceTree = ""; }; D24519421E7D8BB5000ECC03 /* UserViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserViewController.swift; sourceTree = ""; }; D24519441E7D9679000ECC03 /* ezshopUser-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "ezshopUser-Bridging-Header.h"; sourceTree = ""; }; D24519451E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CLFaceDetectionImagePickerViewController.h; sourceTree = ""; }; D24519461E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CLFaceDetectionImagePickerViewController.m; sourceTree = ""; }; D24519471E7D967A000ECC03 /* CLFaceDetectionImagePicker.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = CLFaceDetectionImagePicker.storyboard; sourceTree = ""; }; D24519481E7D967A000ECC03 /* UIImage+CL.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+CL.h"; sourceTree = ""; }; D24519491E7D967A000ECC03 /* UIImage+CL.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+CL.m"; sourceTree = ""; }; D245194D1E7D96E7000ECC03 /* kairos.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = kairos.swift; sourceTree = ""; }; D25E55661E7DB939000B18D8 /* ezshopUser.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ezshopUser.entitlements; sourceTree = ""; }; D25E55691E7E2542000B18D8 /* HudView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HudView.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ D24519201E7D8488000ECC03 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 9C43599ED3F692D8EA185E21 /* Pods_ezshopUser.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 46A7531CE6AD3C575B28D8F9 /* Frameworks */ = { isa = PBXGroup; children = ( 46DBEF9CAFC2C0D784347B44 /* Pods_ezshopUser.framework */, ); name = Frameworks; sourceTree = ""; }; 93DD57EF27D561F811E3E7B9 /* Pods */ = { isa = PBXGroup; children = ( A1A2C175D85E21E953053C9F /* Pods-ezshopUser.debug.xcconfig */, 9DB79685D4C2A6A6E0AA60A0 /* Pods-ezshopUser.release.xcconfig */, ); name = Pods; sourceTree = ""; }; D245191A1E7D8488000ECC03 = { isa = PBXGroup; children = ( D24519251E7D8488000ECC03 /* ezshopUser */, D24519241E7D8488000ECC03 /* Products */, 93DD57EF27D561F811E3E7B9 /* Pods */, 46A7531CE6AD3C575B28D8F9 /* Frameworks */, ); sourceTree = ""; }; D24519241E7D8488000ECC03 /* Products */ = { isa = PBXGroup; children = ( D24519231E7D8488000ECC03 /* ezshopUser.app */, ); name = Products; sourceTree = ""; }; D24519251E7D8488000ECC03 /* ezshopUser */ = { isa = PBXGroup; children = ( D25E55661E7DB939000B18D8 /* ezshopUser.entitlements */, D24519451E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.h */, D24519461E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.m */, D24519471E7D967A000ECC03 /* CLFaceDetectionImagePicker.storyboard */, D24519481E7D967A000ECC03 /* UIImage+CL.h */, D24519491E7D967A000ECC03 /* UIImage+CL.m */, D25E55691E7E2542000B18D8 /* HudView.swift */, D24519261E7D8488000ECC03 /* AppDelegate.swift */, D24519281E7D8488000ECC03 /* ViewController.swift */, D245194D1E7D96E7000ECC03 /* kairos.swift */, D24519381E7D8568000ECC03 /* GoogleService-Info.plist */, D245193A1E7D86E1000ECC03 /* JGUtils.swift */, D245193B1E7D86E1000ECC03 /* ActivitiyIndicator.swift */, D24519401E7D872B000ECC03 /* Item.swift */, D245192A1E7D8488000ECC03 /* Main.storyboard */, D245193E1E7D8728000ECC03 /* User.swift */, D245192D1E7D8488000ECC03 /* Assets.xcassets */, D24519321E7D8488000ECC03 /* Info.plist */, D24519421E7D8BB5000ECC03 /* UserViewController.swift */, D24519441E7D9679000ECC03 /* ezshopUser-Bridging-Header.h */, ); path = ezshopUser; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ D24519221E7D8488000ECC03 /* ezshopUser */ = { isa = PBXNativeTarget; buildConfigurationList = D24519351E7D8488000ECC03 /* Build configuration list for PBXNativeTarget "ezshopUser" */; buildPhases = ( 2D1D2BA193C910B06E941C1C /* [CP] Check Pods Manifest.lock */, D245191F1E7D8488000ECC03 /* Sources */, D24519201E7D8488000ECC03 /* Frameworks */, D24519211E7D8488000ECC03 /* Resources */, 644B469D43ED3347FE34FB69 /* [CP] Embed Pods Frameworks */, DC4E51C36AD8EA294A1B31B1 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = ezshopUser; productName = ezshopUser; productReference = D24519231E7D8488000ECC03 /* ezshopUser.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ D245191B1E7D8488000ECC03 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0820; LastUpgradeCheck = 0820; ORGANIZATIONNAME = "Jung Geon Choi"; TargetAttributes = { D24519221E7D8488000ECC03 = { CreatedOnToolsVersion = 8.2.1; DevelopmentTeam = VQJM9GW22Y; LastSwiftMigration = 0820; ProvisioningStyle = Automatic; SystemCapabilities = { com.apple.Push = { enabled = 1; }; }; }; }; }; buildConfigurationList = D245191E1E7D8488000ECC03 /* Build configuration list for PBXProject "ezshopUser" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = D245191A1E7D8488000ECC03; productRefGroup = D24519241E7D8488000ECC03 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( D24519221E7D8488000ECC03 /* ezshopUser */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ D24519211E7D8488000ECC03 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( D245194B1E7D967A000ECC03 /* CLFaceDetectionImagePicker.storyboard in Resources */, D24519391E7D8568000ECC03 /* GoogleService-Info.plist in Resources */, D245192E1E7D8488000ECC03 /* Assets.xcassets in Resources */, D245192C1E7D8488000ECC03 /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 2D1D2BA193C910B06E941C1C /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_ROOT}/../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"; showEnvVarsInLog = 0; }; 644B469D43ED3347FE34FB69 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; DC4E51C36AD8EA294A1B31B1 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ezshopUser/Pods-ezshopUser-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ D245191F1E7D8488000ECC03 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( D24519431E7D8BB5000ECC03 /* UserViewController.swift in Sources */, D24519291E7D8488000ECC03 /* ViewController.swift in Sources */, D245194A1E7D967A000ECC03 /* CLFaceDetectionImagePickerViewController.m in Sources */, D245193C1E7D86E1000ECC03 /* JGUtils.swift in Sources */, D245194E1E7D96E7000ECC03 /* kairos.swift in Sources */, D245193D1E7D86E2000ECC03 /* ActivitiyIndicator.swift in Sources */, D245193F1E7D8728000ECC03 /* User.swift in Sources */, D25E556A1E7E2542000B18D8 /* HudView.swift in Sources */, D24519411E7D872C000ECC03 /* Item.swift in Sources */, D245194C1E7D967A000ECC03 /* UIImage+CL.m in Sources */, D24519271E7D8488000ECC03 /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ D245192A1E7D8488000ECC03 /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( D245192B1E7D8488000ECC03 /* Base */, ); name = Main.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ D24519331E7D8488000ECC03 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; D24519341E7D8488000ECC03 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 10.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; VALIDATE_PRODUCT = YES; }; name = Release; }; D24519361E7D8488000ECC03 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = A1A2C175D85E21E953053C9F /* Pods-ezshopUser.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ezshopUser/ezshopUser.entitlements; DEVELOPMENT_TEAM = VQJM9GW22Y; INFOPLIST_FILE = ezshopUser/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = ca.jgchoi.ezshopUser; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ezshopUser/ezshopUser-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; }; name = Debug; }; D24519371E7D8488000ECC03 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9DB79685D4C2A6A6E0AA60A0 /* Pods-ezshopUser.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = ezshopUser/ezshopUser.entitlements; DEVELOPMENT_TEAM = VQJM9GW22Y; INFOPLIST_FILE = ezshopUser/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = ca.jgchoi.ezshopUser; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "ezshopUser/ezshopUser-Bridging-Header.h"; SWIFT_VERSION = 3.0; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ D245191E1E7D8488000ECC03 /* Build configuration list for PBXProject "ezshopUser" */ = { isa = XCConfigurationList; buildConfigurations = ( D24519331E7D8488000ECC03 /* Debug */, D24519341E7D8488000ECC03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; D24519351E7D8488000ECC03 /* Build configuration list for PBXNativeTarget "ezshopUser" */ = { isa = XCConfigurationList; buildConfigurations = ( D24519361E7D8488000ECC03 /* Debug */, D24519371E7D8488000ECC03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = D245191B1E7D8488000ECC03 /* Project object */; } ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/ezshopUser.xcscheme ================================================ ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcodeproj/xcuserdata/jchoi.xcuserdatad/xcschemes/xcschememanagement.plist ================================================ SchemeUserState ezshopUser.xcscheme orderHint 0 SuppressBuildableAutocreation D24519221E7D8488000ECC03 primary ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: iOS/User/ezshopUser/ezshopUser.xcworkspace/xcuserdata/jchoi.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist ================================================ ================================================ FILE: raspberry/InventoryClient.py ================================================ import json import urllib2 import requests def update_inventory(item_id): patch_url = 'https://hackvalley-5be01.firebaseio.com/inventories/{id}/.json' json_response = get_item_inventory(item_id) if json_response > 0: json_response -= 1 req = urllib2.Request(patch_url.format(id=item_id)) req.add_header('Content-Type', 'application/json') req.add_header('type', 'PATCH') data = json.dumps({'item_count': json_response}) requests.patch(patch_url.format(id=item_id), data) print "Decremented inventory for item: {item}. {num} remaining.".format(item=item_id, num=json_response) else: print "Inventory of item {item} did not change. {num} remaining.".format(item=item_id, num=json_response) def update_events(item_id): patch_url = 'https://hackvalley-5be01.firebaseio.com/events/.json' data = json.dumps({ 'item_id': item_id, 'status': 'in_cart' }) requests.post(patch_url, data) print "Updated events for item: {item}".format(item=item_id) def get_item_inventory(item_id): url = 'https://hackvalley-5be01.firebaseio.com/inventories/{id}/item_count.json' response = urllib2.urlopen(url.format(id=item_id)).read() return json.loads(response) ================================================ FILE: raspberry/logs ================================================ ================================================ FILE: raspberry/script.py ================================================ #!/usr/local/bin/python import RPi.GPIO as GPIO import threading import time from InventoryClient import * import json GPIO.setmode(GPIO.BOARD) # define the pin that goes to the circuit PIN_1_CIRCUIT = 7 PIN_2_CIRCUIT = 29 PIN_3_CIRCUIT = 31 DARK = 100000 LIGHT = 0 REFRESH_RATE = 0.01 item_map = { PIN_1_CIRCUIT: 1, PIN_2_CIRCUIT: 3, PIN_3_CIRCUIT: 2 } item_status = { PIN_1_CIRCUIT: True, PIN_2_CIRCUIT: True, PIN_3_CIRCUIT: True } def rc_time(pin_to_circuit): count = 0 # Output on the pin for GPIO.setup(pin_to_circuit, GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW) time.sleep(REFRESH_RATE) # Change the pin back to input GPIO.setup(pin_to_circuit, GPIO.IN) # Count until the pin goes high while GPIO.input(pin_to_circuit) == GPIO.LOW: count += 1 print "Sensor: " + str(pin_to_circuit) + " value: " + str(count) if LIGHT < count < DARK: if item_status[pin_to_circuit]: item_status[pin_to_circuit] = False update_inventory(item_map[pin_to_circuit]) update_events(item_map[pin_to_circuit]) print "############# id: {0} is taken #############".format(item_map[pin_to_circuit]) return else: print "Dark {0} count {1}".format(item_map[pin_to_circuit], count) item_status[pin_to_circuit] = True try: while True: item_load = get_item_inventory(item_map[PIN_1_CIRCUIT]) if (item_load <= 0): print "Inventory of item {0} is at 0".format(item_map[PIN_1_CIRCUIT]) break else: rc_time(PIN_1_CIRCUIT) except KeyboardInterrupt: pass finally: GPIO.cleanup() ================================================ FILE: raspberry/script2.py ================================================ #!/usr/local/bin/python import RPi.GPIO as GPIO import threading import time from InventoryClient import * import json GPIO.setmode(GPIO.BOARD) # define the pin that goes to the circuit PIN_1_CIRCUIT = 7 PIN_2_CIRCUIT = 29 PIN_3_CIRCUIT = 31 DARK = 100000 LIGHT = 0 REFRESH_RATE = 0.01 item_map = { PIN_1_CIRCUIT: 1, PIN_2_CIRCUIT: 3, PIN_3_CIRCUIT: 2 } item_status = { PIN_1_CIRCUIT: True, PIN_2_CIRCUIT: True, PIN_3_CIRCUIT: True } def rc_time(pin_to_circuit): count = 0 # Output on the pin for GPIO.setup(pin_to_circuit, GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW) time.sleep(REFRESH_RATE) # Change the pin back to input GPIO.setup(pin_to_circuit, GPIO.IN) # Count until the pin goes high while GPIO.input(pin_to_circuit) == GPIO.LOW: count += 1 print "Sensor: " + str(pin_to_circuit) + " value: " + str(count) if LIGHT < count < DARK: if item_status[pin_to_circuit]: item_status[pin_to_circuit] = False update_inventory(item_map[pin_to_circuit]) update_events(item_map[pin_to_circuit]) print "############# id: {0} is taken #############".format(item_map[pin_to_circuit]) return else: print "Dark {0} count {1}".format(item_map[pin_to_circuit], count) item_status[pin_to_circuit] = True try: while True: item_load = get_item_inventory(item_map[PIN_2_CIRCUIT]) if (item_load <= 0): print "Inventory of item {0} is at 0".format(item_map[PIN_2_CIRCUIT]) break else: rc_time(PIN_2_CIRCUIT) except KeyboardInterrupt: pass finally: GPIO.cleanup() ================================================ FILE: raspberry/ultrasonic.py ================================================ # Libraries import RPi.GPIO as GPIO import time from InventoryClient import * import math # GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BCM) # set GPIO Pins GPIO_TRIGGER = 18 GPIO_ECHO = 24 BOTTLE_SIZE = 7 # cm MARGIN_ERR = 2 # cm EMPTY_D = 60 # cm ITEM_ID = 2 REFERSH_RATE = 2 # seconds # set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def distance_changed(): GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start_time = time.time() stop_time = time.time() while GPIO.input(GPIO_ECHO) == 0: start_time = time.time() while GPIO.input(GPIO_ECHO) == 1: stop_time = time.time() time_elapsed = stop_time - start_time d = (time_elapsed * 34300) / 2 num_bottles = ((EMPTY_D - d) / BOTTLE_SIZE) # print math.floor(d) return int(math.floor(abs(num_bottles))) if __name__ == '__main__': item_load = get_item_inventory(ITEM_ID) try: while True: items = distance_changed() if item_load != items: update_inventory(ITEM_ID) update_events(ITEM_ID) item_load = items print items time.sleep(REFERSH_RATE) except KeyboardInterrupt: print("Measurement stopped by User") GPIO.cleanup()