### Swift Codegen Setup Source: https://www.apollographql.com/docs/ios/code-generation/codegen-configuration Example of how to configure Apollo iOS code generation using Swift code. ```APIDOC ## Swift Codegen Setup ### Description This Swift code demonstrates how to initialize and configure the `ApolloCodegenConfiguration` for the Apollo iOS library. ### Method Initialization of `ApolloCodegenConfiguration` and its nested properties. ### Endpoint N/A (This is a code configuration example, not an API endpoint). ### Parameters #### Request Body - **configuration** (`ApolloCodegenConfiguration`) - The main configuration object. - **options** (`ApolloCodegenConfiguration.OutputOptions`) - Configuration for output and generation behavior. - **additionalInflectionRules** (array) - Rules for pluralization and singularization. - **pluralization** (object) - Defines a pluralization rule. - **singularRegex** (string) - The singular form regex. - **replacementRegex** (string) - The regex to replace. - **appendSchemaTypeFilenameSuffix** (boolean) - Appends a suffix to schema type filenames. Defaults to `false`. - **deprecatedEnumCases** (`DeprecatedEnumCaseOption`) - How to handle deprecated enum cases. Possible values: `.include`, `.exclude`. - **schemaDocumentation** (`SchemaDocumentationOption`) - How to include schema documentation. Possible values: `.include`, `.exclude`. - **selectionSetInitializers** (`ApolloCodegenConfiguration.SelectionSetInitializers`) - Configuration for generating initializers for selection sets. - **operation** (named: `String`) - Generate initializers for a specific operation. - **fragment** (named: `String`) - Generate initializers for a specific fragment. - **operationDocumentFormat** (array) - Specifies the format of the generated operation documents. Possible values: `.document`, `.operationId`. - **warningsOnDeprecatedUsage** (`WarningsOnDeprecatedUsageOption`) - How to handle warnings for deprecated usage. Possible values: `.include`, `.exclude`. - **conversionStrategies** (`ApolloCodegenConfiguration.ConversionStrategies`) - Defines conversion strategies for various GraphQL types. - **enumCases** (`GraphQLNamingConvention`) - Strategy for converting enum cases. Possible values: `.camelCase`, `.pascalCase`, `.snakeCase`, `.none`. - **fieldAccessors** (`GraphQLNamingConvention`) - Strategy for field accessors. Possible values: `.default`, `.camelCase`, `.pascalCase`, `.snakeCase`. - **inputObjects** (`GraphQLNamingConvention`) - Strategy for input objects. Possible values: `.camelCase`, `.pascalCase`, `.snakeCase`, `.none`. - **pruneGeneratedFiles** (boolean) - Whether to automatically delete unused generated files. Defaults to `true`. - **markOperationDefinitionsAsFinal** (boolean) - Whether to mark generated GraphQL operation and local cache mutation class types as `final`. Defaults to `true`. - **reduceGeneratedSchemaTypes** (boolean) - Reduces generated `Object` types for objects implementing interfaces or only referenced in operations. Defaults to `false`. - **schemaCustomization** (`ApolloCodegenConfiguration.SchemaCustomization`) - Customization options for the schema during code generation. - **customTypeNames** (dictionary) - Maps custom names to GraphQL types. - **[String: ApolloCodegenConfiguration.CustomType]** - The GraphQL type name and its customization object. - **enum** (name: `String`, cases: `[String: String]`) - Customization for an enum type. - **type** (name: `String`) - Customization for a general type (e.g., Object, Scalar). - **inputObject** (name: `String`, fields: `[String: String]`) - Customization for an input object type. ### Request Example ```swift let configuration = ApolloCodegenConfiguration( // Other properties not shown options: ApolloCodegenConfiguration.OutputOptions( additionalInflectionRules: [ .pluralization( singularRegex: "animal", replacementRegex: "animals" ) ], appendSchemaTypeFilenameSuffix: false. deprecatedEnumCases: .include, schemaDocumentation: .include, selectionSetInitializers: [ .operation(named: "MyOperation"), .fragment(named: "MyFragment") ], operationDocumentFormat: [.document, .operationId], warningsOnDeprecatedUsage: .include, conversionStrategies: ApolloCodegenConfiguration.ConversionStrategies( enumCases: .camelCase, fieldAccessors: .default, inputObjects: .camelCase ), pruneGeneratedFiles: true, markOperationDefinitionsAsFinal: true, reduceGeneratedSchemaTypes: false, schemaCustomization: .init( customTypeNames: [ "MyEnum" : .enum( name: "CustomEnum", cases: [ "MyCase" : "CustomCase" ] ), "MyObject" : .type( name: "CustomObject" ), "MyInputObject" : .inputObject( name: "CustomInputObject", fields: [ "myField" : "customField" ] ) ] ) ) ) ``` ``` -------------------------------- ### Example of subscribe(on:) and receive(on:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/subscribe%28on%3Aoptions%3A%29 This example demonstrates how `subscribe(on:options:)` changes the upstream execution context to `backgroundQueue`, while `receive(on:options:)` directs downstream messages to `RunLoop.main` for UI updates. ```swift let ioPerformingPublisher == // Some publisher. let uiUpdatingSubscriber == // Some subscriber that updates the UI. ioPerformingPublisher .subscribe(on: backgroundQueue) .receive(on: RunLoop.main) .subscribe(uiUpdatingSubscriber) ``` -------------------------------- ### Combine Swift Publisher zip example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/zip%28_%3A_%3A_%3A_%3A%29 Example demonstrating how to use the zip operator to combine four publishers and transform their outputs. Ensure all upstream publishers emit values before the transformation occurs. ```swift let numbersPub = PassthroughSubject() // first publisher let lettersPub = PassthroughSubject() // second let emojiPub = PassthroughSubject() // third let fractionsPub = PassthroughSubject()// fourth cancellable = numbersPub .zip(lettersPub, emojiPub, fractionsPub) { anInt, aLetter, anEmoji, aFraction in ("\(String(repeating: anEmoji, count: anInt)) \(String(repeating: aLetter, count: anInt)) \(aFraction)") } .sink { print("\($0)") } numbersPub.send(1) // numbersPub: 1 lettersPub: emojiPub: zip output: numbersPub.send(2) // numbersPub: 1,2 lettersPub: emojiPub: zip output: numbersPub.send(3) // numbersPub: 1,2,3 lettersPub: emojiPub: zip output: fractionsPub.send(0.1) // numbersPub: 1,2,3 lettersPub: "A" emojiPub: zip output: lettersPub.send("A") // numbersPub: 1,2,3 lettersPub: "A" emojiPub: zip output: emojiPub.send("😀") // numbersPub: 1,2,3 lettersPub: "A" emojiPub:"😀" zip output: "😀 A" lettersPub.send("B") // numbersPub: 2,3 lettersPub: "B" emojiPub: zip output: fractionsPub.send(0.8) // numbersPub: 2,3 lettersPub: "A" emojiPub: zip output: emojiPub.send("🥰") // numbersPub: 3 lettersPub: "B" emojiPub: zip output: "🥰🥰 BB" // Prints: //1 😀 A 0.1 //2 🥰🥰 BB 0.8 ``` -------------------------------- ### Example of drop(untilOutputFrom:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/drop%28untiloutputfrom%3A%29 This example demonstrates how `drop(untilOutputFrom:)` works. Elements from `upstream` are ignored until `second` emits 'A'. After that, subsequent elements from `upstream` are printed. ```swift let upstream = PassthroughSubject() let second = PassthroughSubject() cancellable = upstream .drop(untilOutputFrom: second) .sink { print("\($0)", terminator: " ") } upstream.send(1) upstream.send(2) second.send("A") upstream.send(3) upstream.send(4) // Prints "3 4" ``` -------------------------------- ### Full Apollo Codegen Configuration Example Source: https://www.apollographql.com/docs/ios/code-generation/codegen-configuration An extensive example of `apollo-codegen-config.json` demonstrating all available configuration options for schema namespace, download, experimental features, manifest, input/output paths, and code generation options. ```json { "schemaNamespace" : "MySchema", "schemaDownload": { "downloadMethod": { "introspection": { "endpointURL": "https://server.com", "httpMethod": { "POST": {} }, "includeDeprecatedInputValues": false, "outputFormat": "SDL" } }, "downloadTimeout": 60, "headers": [], "outputPath": "./graphql/" }, "experimentalFeatures" : { "fieldMerging": [ "all" ], "legacySafelistingCompatibleOperations" : true }, "operationManifest" : { "generateManifestOnCodeGeneration" : false, "path" : "/operation/identifiers/path", "version" : "persistedQueries" }, "input" : { "operationSearchPaths" : [ "/search/path/**/*.graphql" ], "schemaSearchPaths" : [ "/path/to/schema.graphqls" ] }, "output" : { "operations" : { "absolute" : { "accessModifier" : "internal", "path" : "/absolute/path" } }, "schemaTypes" : { "moduleType" : { "embeddedInTarget" : { "accessModifier" : "public", "name" : "SomeTarget" } }, "path" : "/output/path" }, "testMocks" : { "swiftPackage" : { "targetName" : "SchemaTestMocks" } } }, "options" : { "additionalInflectionRules" : [ { "pluralization" : { "replacementRegex" : "animals", "singularRegex" : "animal" } } ], "appendSchemaTypeFilenameSuffix": false, "conversionStrategies" : { "enumCases" : "none", "fieldAccessors" : "camelCase", "inputObjects": "camelCase" }, "deprecatedEnumCases" : "exclude", "operationDocumentFormat" : [ "definition" ], "pruneGeneratedFiles" : false, "schemaDocumentation" : "exclude", "selectionSetInitializers" : { "operations": false, "namedFragments" : false, "definitionsNamed": [ "MyOperation", "MyFragment" ] }, "warningsOnDeprecatedUsage" : "exclude", "operationDocumentFormat" : ["definition", "operationId"], "markOperationDefinitionsAsFinal": true } } ``` -------------------------------- ### Using prepend(_:) with a Publisher Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/prepend%28_%3A%29-64d2f Example demonstrating how to use the prepend operator to add specific integers to the start of a publisher's sequence. ```swift let dataElements = (0...10) cancellable = dataElements.publisher .prepend(0, 1, 255) .sink { print("\($0)", terminator: " ") } // Prints: "0 1 255 0 1 2 3 4 5 6 7 8 9 10" ``` -------------------------------- ### Initialize Project Directory Source: https://www.apollographql.com/docs/ios/tutorial/codegen-getting-started Create and navigate to a new project directory for the Apollo iOS example. ```shell mkdir ios-code-gen-example cd ios-code-gen-example ``` -------------------------------- ### Example of collecting timestamps by time Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/collect%28_%3Aoptions%3A%29 This example demonstrates collecting timestamps generated on a one-second interval and grouping them into arrays every five seconds using `collect(.byTime:options:)`. The collected arrays are then printed. ```swift let sub = Timer.publish(every: 1, on: .main, in: .default) .autoconnect() .collect(.byTime(RunLoop.main, .seconds(5))) .sink { print("\($0)", terminator: "\n\n") } ``` -------------------------------- ### Start Apollo Router Source: https://www.apollographql.com/docs/ios/fetching/persisted-queries Start your GraphOS-connected router with the necessary environment variables. This command exposes health and GraphQL endpoints. ```bash APOLLO_KEY="..." APOLLO_GRAPH_REF="..." ./router --config ./router.yaml 2023-05-11T15:32:30.684460Z INFO Apollo Router v1.18.1 // (c) Apollo Graph, Inc. // Licensed as ELv2 (https://go.apollo.dev/elv2) 2023-05-11T15:32:30.684480Z INFO Anonymous usage data is gathered to inform Apollo product development. See https://go.apollo.dev/o/privacy for details. 2023-05-11T15:32:31.507085Z INFO Health check endpoint exposed at http://127.0.0.1:8088/health 2023-05-11T15:32:31.507823Z INFO GraphQL endpoint exposed at http://127.0.0.1:4000/ 🚀 ``` -------------------------------- ### Throttle Usage Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/throttle%28for%3Ascheduler%3Alatest%3A%29 Demonstrates using throttle with a Timer publisher to limit output frequency. ```swift cancellable = Timer.publish(every: 3.0, on: .main, in: .default) .autoconnect() .print("\(Date().description)") .throttle(for: 10.0, scheduler: RunLoop.main, latest: true) .sink( receiveCompletion: { print ("Completion: \($0).") }, receiveValue: { print("Received Timestamp \($0).") } ) // Prints: // Publish at: 2020-03-19 18:26:54 +0000: receive value: (2020-03-19 18:26:57 +0000) // Received Timestamp 2020-03-19 18:26:57 +0000. // Publish at: 2020-03-19 18:26:54 +0000: receive value: (2020-03-19 18:27:00 +0000) // Publish at: 2020-03-19 18:26:54 +0000: receive value: (2020-03-19 18:27:03 +0000) // Publish at: 2020-03-19 18:26:54 +0000: receive value: (2020-03-19 18:27:06 +0000) // Publish at: 2020-03-19 18:26:54 +0000: receive value: (2020-03-19 18:27:09 +0000) // Received Timestamp 2020-03-19 18:27:09 +0000. ``` -------------------------------- ### Example: Limiting Shipping Options with intersection(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/operationdocumentformat/intersection%28_%3A%29 This example demonstrates how to use the `intersection(_:)` method to find common elements between two shipping option sets. It's useful for scenarios like determining available shipping methods for specific destinations. ```swift // Can only ship standard or priority to PO Boxes let poboxShipping: ShippingOptions = [.standard, .priority] let memberShipping: ShippingOptions = [.standard, .priority, .secondDay] let availableOptions = memberShipping.intersection(poboxShipping) print(availableOptions.contains(.priority)) // Prints "true" print(availableOptions.contains(.secondDay)) // Prints "false" ``` -------------------------------- ### Usage example of output(in:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/output%28in%3A%29 Demonstrates how to use output(in:) to emit a subset of elements from an array publisher. ```swift let numbers = [1, 1, 2, 2, 2, 3, 4, 5, 6] numbers.publisher .output(in: (3...5)) .sink { print("\($0)", terminator: " ") } // Prints: "2 2 3" ``` -------------------------------- ### Combine Publishers with zip(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/zip%28_%3A%29 Example demonstrating how to use zip(_:) to pair values from two PassthroughSubjects. ```swift let numbersPub = PassthroughSubject() let lettersPub = PassthroughSubject() cancellable = numbersPub .zip(lettersPub) .sink { print("\($0)") } numbersPub.send(1) // numbersPub: 1 lettersPub: zip output: numbersPub.send(2) // numbersPub: 1,2 lettersPub: zip output: letters.send("A") // numbers: 1,2 letters:"A" zip output: numbers.send(3) // numbers: 1,2,3 letters: zip output: (1,"A") letters.send("B") // numbers: 1,2,3 letters: "B" zip output: (2,"B") // Prints: // (1, "A") // (2, "B") ``` -------------------------------- ### Clone the starter project Source: https://www.apollographql.com/docs/ios/tutorial/tutorial-configure-project Use this command to download the tutorial starter files from GitHub. ```text git clone https://github.com/apollographql/iOSTutorial.git ``` -------------------------------- ### init(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/responsepath/init%28_%3A%29 Initializes a new ResponsePath instance with a given key. ```APIDOC ## init(_:) ### Description Initializes a new ResponsePath instance using the provided key. ### Parameters #### Path Parameters - **key** (ResponsePath.Key) - Required - The key to initialize the ResponsePath with. ### Request Example ```swift let path = ResponsePath(key) ``` ``` -------------------------------- ### Get Default Client Name Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/clientawarenessmetadata/defaultclientname Retrieve the default client name used for Apollo iOS client setup. This property is read-only. ```swift static var defaultClientName: String { get } ``` -------------------------------- ### Instance Method: kickoff(request:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/requestchain/kickoff%28request%3A%29 Kicks off a request from step 1 of the Request Chain Flow. ```APIDOC ## kickoff(request:) ### Description Kicks off a request from step 1 of the Request Chain Flow. ### Method ```swift func kickoff(request: Request) -> RequestChain.ResultStream ``` ### Parameters #### Request Body - **request** (Request) - Required - The `GraphQLRequest` to kick off. ``` -------------------------------- ### Get FetchBehavior from CachePolicy.Query Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/cachepolicy/query/cacheonly/tofetchbehavior%28%29 Use this method to retrieve the FetchBehavior associated with a query's cache policy. No specific setup is required beyond having an instance of CachePolicy.Query. ```swift func toFetchBehavior() -> FetchBehavior ``` -------------------------------- ### Use last() to get the last element of a publisher Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/last%28%29 Use Publisher/last() when you need to emit only the last element from an upstream publisher. In the example below, the range publisher only emits the last element from the sequence publisher, 10, then finishes normally. ```swift let numbers = (-10...10) cancellable = numbers.publisher .last() .sink { print("\($0)") } ``` -------------------------------- ### Usage example of first() Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/first%28%29 Demonstrates using first() on a sequence publisher to emit only the first value. ```swift let numbers = (-10...10) cancellable = numbers.publisher .first() .sink { print("\($0)") } // Print: "-10" ``` -------------------------------- ### init(fromString:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/schematypesfileoutput/moduletype-swift.enum/apollosdkdependency/sdkversion/init%28fromstring%3A%29 Initializes a configuration object from a string representation. ```APIDOC ## init(fromString:) ### Description Initializes an instance of the configuration object by parsing the provided string input. ### Method Initializer ### Parameters #### Path Parameters - **str** (String) - Required - The string representation used to initialize the configuration object. ### Response - **Throws** - Throws an error if the string cannot be parsed into a valid configuration. ``` -------------------------------- ### GET /schema/download Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apolloschemadownloadconfiguration/downloadmethod-swift.enum/httpmethod/get%28queryparametername%3A%29 Configuration for using the HTTP GET method to download a GraphQL schema, where the query is passed as a parameter. ```APIDOC ## GET (HTTP Method) ### Description Use GET for HTTP requests with the GraphQL query being sent in the query string parameter named in `queryParameterName`. ### Method GET ### Parameters #### Path Parameters - **queryParameterName** (String) - Required - The name of the query string parameter used to send the GraphQL query. ``` -------------------------------- ### Example usage of dropFirst(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/dropfirst%28_%3A%29 Demonstrates dropping the first five elements from a publisher stream of numbers. ```swift let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] cancellable = numbers.publisher .dropFirst(5) .sink { print("\($0)", terminator: " ") } // Prints: "6 7 8 9 10 " ``` -------------------------------- ### Install Codegen CLI with SPM Source: https://www.apollographql.com/docs/ios/code-generation/codegen-cli Installs the Codegen CLI using the `apollo-cli-install` SPM plugin. This creates a symbolic link to the executable in your project root. ```bash swift package --allow-writing-to-package-directory apollo-cli-install ``` -------------------------------- ### Combining Publishers with zip Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/zip%28_%3A_%3A%29-3oklf An example demonstrating how to use zip to combine two PassthroughSubject publishers and transform their outputs. ```swift let numbersPub = PassthroughSubject() let lettersPub = PassthroughSubject() cancellable = numbersPub .zip(lettersPub) { anInt, aLetter in String(repeating: aLetter, count: anInt) } .sink { print("\($0)") } numbersPub.send(1) // numbersPub: 1 lettersPub: zip output: numbersPub.send(2) // numbersPub: 1,2 lettersPub: zip output: numbersPub.send(3) // numbersPub: 1,2,3 lettersPub: zip output: lettersPub.send("A") // numbersPub: 1,2,3 lettersPub: "A" zip output: "A" lettersPub.send("B") // numbersPub: 2,3 lettersPub: "B" zip output: "BB" // Prints: // A // BB ``` -------------------------------- ### GraphQLNullable init(_:) Usage Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/graphqlnullable/init%28_%3A%29-7pg3j Demonstrates the simplified usage of the `init(_:)` initializer for creating `GraphQLNullable>` values compared to the previous method. ```swift let value: GraphQLNullable> value = .init(.NEWHOPE) // Instead of value = .init(.case(.NEWHOPE)) ``` -------------------------------- ### Define GET HTTP Method for Schema Download Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apolloschemadownloadconfiguration/downloadmethod-swift.enum/httpmethod/get%28queryparametername%3A%29 Use this case to configure the schema download to use an HTTP GET request with a specified query parameter name. ```swift case GET(queryParameterName: String) ``` -------------------------------- ### init(fileURL:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollosqlite/apollosqlitedatabase/init%28fileurl%3A%29 Initializes a new instance of ApolloSQLiteDatabase with the specified file URL. ```APIDOC ## init(fileURL:) ### Description Initializes an ApolloSQLiteDatabase instance using a provided file URL. ### Method Initializer ### Parameters #### Path Parameters - **fileURL** (URL) - Required - The file URL pointing to the SQLite database location. ### Request Example let database = try ApolloSQLiteDatabase(fileURL: databaseURL) ``` -------------------------------- ### Example of Merging Publishers Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/merge%28with%3A_%3A_%3A_%3A_%3A_%3A_%3A%29 This example demonstrates how `Publisher.merge(with:_:_:_:_:_:_:)` republishes interleaved elements from upstream publishers as they are received. The output shows the sequence of numbers printed as each publisher sends its value. ```swift let pubA = PassthroughSubject() let pubB = PassthroughSubject() let pubC = PassthroughSubject() let pubD = PassthroughSubject() let pubE = PassthroughSubject() let pubF = PassthroughSubject() let pubG = PassthroughSubject() let pubH = PassthroughSubject() cancellable = pubA .merge(with: pubB, pubC, pubD, pubE, pubF, pubG, pubH) .sink { print("\($0)", terminator: " " ) } pubA.send(1) pubB.send(40) pubC.send(90) pubD.send(-1) pubE.send(33) pubF.send(44) pubG.send(54) pubH.send(1000) pubA.send(2) pubB.send(50) pubC.send(100) pubD.send(-2) pubE.send(33) pubF.send(33) pubG.send(54) pubH.send(1001) //Prints: "1 40 90 -1 33 44 54 1000 2 50 100 -2 33 33 54 1001" ``` -------------------------------- ### init(clientApplicationName:clientApplicationVersion:includeApolloLibraryAwareness:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/clientawarenessmetadata/init%28clientapplicationname%3Aclientapplicationversion%3Aincludeapollolibraryawareness%3A%29 Initializes a new instance of ClientAwarenessMetadata with optional client application details and library awareness settings. ```APIDOC ## init(clientApplicationName:clientApplicationVersion:includeApolloLibraryAwareness:) ### Description Initializes the ClientAwarenessMetadata object to include client-specific information in outgoing requests. ### Parameters - **clientApplicationName** (String?) - Optional - The name of the client application. - **clientApplicationVersion** (String?) - Optional - The version of the client application. - **includeApolloLibraryAwareness** (Bool) - Optional - Whether to include Apollo library awareness metadata. Defaults to true. ``` -------------------------------- ### Merging Publishers Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/merge%28with%3A_%3A_%3A%29 Demonstrates how to merge four PassthroughSubjects and sink the interleaved output. ```swift let pubA = PassthroughSubject() let pubB = PassthroughSubject() let pubC = PassthroughSubject() let pubD = PassthroughSubject() cancellable = pubA .merge(with: pubB, pubC, pubD) .sink { print("\($0)", terminator: " " )} pubA.send(1) pubB.send(40) pubC.send(90) pubD.send(-1) pubA.send(2) pubB.send(50) pubC.send(100) pubD.send(-2) // Prints: "1 40 90 -1 2 50 100 -2 " ``` -------------------------------- ### Conditional Debugger Breakpoint Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/breakpoint%28receivesubscription%3Areceiveoutput%3Areceivecompletion%3A%29 Demonstrates how to use the breakpoint function to stop the debugger when a specific output value is received. This example uses a PassthroughSubject and stops when the string 'DEBUGGER' is sent. ```swift let publisher = PassthroughSubject() cancellable = publisher .breakpoint( receiveOutput: { value in return value == "DEBUGGER" } ) .sink { print("\(String(describing: $0))" , terminator: " ") } publisher.send("DEBUGGER") // Prints: "error: Execution was interrupted, reason: signal SIGTRAP." // Depending on your specific environment, the console messages may // also include stack trace information, which is not shown here. ``` -------------------------------- ### init(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/asynchttpresponsechunksequence/init%28_%3A%29 Designated Initializer for AsyncHTTPResponseChunkSequence. ```APIDOC ## init(_:) ### Description Designated Initializer for `AsyncHTTPResponseChunkSequence`. ### Method `init` ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ## Parameters `bytes` (URLSession.AsyncBytes) - Required - The response byte stream to be separated into multi-part chunks. Must be the result of an HTTP `URLRequest` to ensure that `bytes.task.response` is an `HTTPURLResponse`. ``` -------------------------------- ### Example: Conditionally Insert Shipping Option - Swift Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/operationdocumentformat/insert%28_%3A%29 Demonstrates how to conditionally insert a shipping option into an `OptionSet` based on a purchase price. This example requires the `ShippingOptions` type to be declared as an `OptionSet`. ```swift let purchasePrice = 87.55 var freeOptions: ShippingOptions = [.standard, .priority] if purchasePrice > 50 { freeOptions.insert(.secondDay) } print(freeOptions.contains(.secondDay)) ``` -------------------------------- ### init(url:defaultRequestConfiguration:clientAwarenessMetadata:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/apolloclient/init%28url%3Adefaultrequestconfiguration%3Aclientawarenessmetadata%3A%29 Convenience initializer that creates a client with a default network transport and cache setup. ```APIDOC ## init(url:defaultRequestConfiguration:clientAwarenessMetadata:) ### Description Convenience initializer that creates a client with a default network transport and cache setup. This initializer uses an in-memory only cache and a RequestChainNetworkTransport. ### Parameters - **url** (URL) - Required - The URL of a GraphQL server to connect to. - **defaultRequestConfiguration** (RequestConfiguration) - Optional - A default RequestConfiguration for the client’s requests. - **clientAwarenessMetadata** (ClientAwarenessMetadata) - Optional - Metadata used by the client awareness feature of GraphOS Studio. ### Discussion The InMemoryNormalizedCache used by this client does not persist data between application runs. ``` -------------------------------- ### init(typename:implementedInterfaces:keyFields:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/object/init%28typename%3Aimplementedinterfaces%3Akeyfields%3A%29 Initializes a new Object instance with a type name, implemented interfaces, and optional key fields. ```APIDOC ## init(typename:implementedInterfaces:keyFields:) ### Description Initializes a new Object instance for use within the ApolloAPI framework. ### Parameters - **typename** (String) - Required - The name of the type. - **implementedInterfaces** ([Interface]) - Required - A list of the interfaces implemented by the type. - **keyFields** ([String]?) - Optional - A list of field names that are used to uniquely identify an instance of this type. ### Request Example ```swift init( typename: "User", implementedInterfaces: [interfaceInstance], keyFields: ["id"] ) ``` ``` -------------------------------- ### CombineLatest Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/combinelatest%28_%3A_%3A%29-3m6fr This example demonstrates how to use combineLatest(_:_:) to combine two PassthroughSubjects. The transform closure multiplies the received integers, and the sink prints the result. Note that combineLatest only emits when both publishers have emitted at least one value. ```swift let pub1 = PassthroughSubject() let pub2 = PassthroughSubject() cancellable = pub1 .combineLatest(pub2) { (first, second) in return first * second } .sink { print("Result: \($0).") } pub1.send(1) pub1.send(2) pub2.send(2) pub1.send(9) pub1.send(3) pub2.send(12) pub1.send(13) // // Prints: //Result: 4. (pub1 latest = 2, pub2 latest = 2) //Result: 18. (pub1 latest = 9, pub2 latest = 2) //Result: 6. (pub1 latest = 3, pub2 latest = 2) //Result: 36. (pub1 latest = 3, pub2 latest = 12) //Result: 156. (pub1 latest = 13, pub2 latest = 12) ``` -------------------------------- ### CLI Command: init Source: https://www.apollographql.com/docs/ios/code-generation/codegen-cli Initializes a new apollo-codegen-configuration.json file with default values to configure code generation. ```APIDOC ## CLI Command: init ### Description Creates an apollo-codegen-configuration.json file with default values to configure how the CLI generates Swift code. ### Command apollo-ios-cli init --schema-namespace --module-type [--target-name ] ### Parameters #### Options - **--schema-namespace** (string) - Required - The name used as the namespace for generated schema files. - **--module-type** (string) - Required - Packaging method for schema types (embeddedInTarget, swiftPackageManager, other). - **--target-name** (string) - Optional - Name of the target for embeddedInTarget module type. - **-p, --path** (path) - Optional - File path for the configuration (default: ./apollo-codegen-config.json). - **-w, --overwrite** (boolean) - Optional - Overwrite existing configuration file. - **-s, --print** (boolean) - Optional - Print configuration to stdout. ``` -------------------------------- ### Merging Publishers Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/merge%28with%3A%29-7ko3g Demonstrates how to merge two PassthroughSubject publishers and sink the interleaved output. ```swift let publisher = PassthroughSubject() let pub2 = PassthroughSubject() cancellable = publisher .merge(with: pub2) .sink { print("\($0)", terminator: " " )} publisher.send(2) pub2.send(2) publisher.send(3) pub2.send(22) publisher.send(45) pub2.send(22) publisher.send(17) // Prints: "2 2 3 22 45 22 17" ``` -------------------------------- ### init(customTypeNames:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/schemacustomization/init%28customtypenames%3A%29 Initializes the SchemaCustomization configuration with a dictionary of custom type names. ```APIDOC ## init(customTypeNames:) ### Description Designated initializer for SchemaCustomization that allows for renaming schema types via a dictionary mapping. ### Parameters #### Request Body - **customTypeNames** ([String : ApolloCodegenConfiguration.SchemaCustomization.CustomSchemaTypeName]) - Optional - Dictionary representing the types to be renamed and how to rename them. Defaults to Default.customTypeNames. ``` -------------------------------- ### GET errorDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/incrementalresponseerror/errordescription Retrieves the description of an IncrementalResponseError. ```APIDOC ## GET errorDescription ### Description Returns the localized description of the error encountered during incremental response execution. ### Method GET ### Endpoint errorDescription ### Response - **errorDescription** (String?) - The description of the error. ``` -------------------------------- ### init(from:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/composition/init%28from%3A%29 Initializes a new instance by decoding from a given decoder when the RawValue is a String. ```APIDOC ## init(from:) ### Description Creates a new instance by decoding from the given decoder, when the type’s RawValue is String. ### Parameters - **decoder** (any Decoder) - Required - The decoder to read data from. ### Discussion This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid. ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollosqlite/sqlitenormalizedcacheerror/localizeddescription Retrieves the localized description for a SQLiteNormalizedCacheError. ```APIDOC ## Instance Property: localizedDescription ### Description Retrieve the localized description for this error. ### Property Definition `var localizedDescription: String { get }` ### Supported Platforms - ApolloSQLiteSwift - iOS 8.0+ - macOS 10.10+ - tvOS 9.0+ - watchOS 2.0+ ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/apolloconfigurationerror/localizeddescription Retrieves the localized description for an ApolloConfigurationError. ```APIDOC ## Property: localizedDescription ### Description Retrieve the localized description for this error. ### Property Definition `var localizedDescription: String { get }` ### Compatibility - Swift - iOS 8.0+ - macOS 10.10+ - tvOS 9.0+ - watchOS 2.0+ ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/multipartresponsedeferparser/parsingerror/localizeddescription Retrieves the localized description for a MultipartResponseDeferParser.ParsingError. ```APIDOC ## GET localizedDescription ### Description Retrieve the localized description for a parsing error encountered by the MultipartResponseDeferParser. ### Property Definition `var localizedDescription: String { get }` ### Compatibility - ApolloSwift: 8.0+ - macOS: 10.10+ - tvOS: 9.0+ - watchOS: 2.0+ ``` -------------------------------- ### Record Initializer: init(key:_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/record/init%28key%3A_%3A%29 Initializes a new Record with a given CacheKey and optional fields. ```APIDOC ## Initializer: init(key:_:) ### Description Initializes a new `Record` instance with a specified `CacheKey` and an optional dictionary of fields. ### Method `init` ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift let record = Record(key: "someKey", ["fieldName": "fieldValue"]) ``` ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A (Initializer) ``` -------------------------------- ### CacheKeyInfo Initialization and Usage Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/cachekeyinfo Demonstrates how to create and use CacheKeyInfo to resolve cache keys for objects, including specific types and interfaces. ```APIDOC ## CacheKeyInfo Contains the information needed to resolve a cache key in a `NormalizedCache`. ### Overview You can create and return a `CacheKeyInfo` from your implementation of the `cacheKeyInfo(for:object:)` function to configure the cache key resolution for the types in the schema, which is used by `NormalizedCache` mechanisms. ### Cache Key Resolution You can use the `init(jsonValue:uniqueKeyGroup:)` convenience initializer in the implementation of your `cacheKeyInfo(for:object:)` function to easily resolve the cache key for an object. For an object of the type `Dog` with a unique id represented by an `id` field, you may implement cache key resolution with: ```swift enum SchemaConfiguration: ApolloAPI.SchemaConfiguration { static func cacheKeyInfo(for type: Object, object: JSONObject) -> CacheKeyInfo? { switch type { case Objects.Dog: return try? CacheKeyInfo(jsonValue: object["id"]) default: return nil } } } ``` ### Resolving Cache Keys by Interfaces If you have multiple objects that conform to an `Interface` with the same cache id resolution strategy, you can resolve the id based on the `Interface`. For example, for a schema with `Dog` and `Cat` `Object` types that implement a `Pet` `Interface`, you may implement cache key resolution with: ```swift enum SchemaConfiguration: ApolloAPI.SchemaConfiguration { static func cacheKeyInfo(for type: Object, object: JSONObject) -> CacheKeyInfo? { if type.implements(Interfaces.Pet) { return try? CacheKeyInfo(jsonValue: object["id"]) } return nil } } ``` ### Grouping Cached Objects by Interfaces If your keys are guaranteed to be unique across all `Object` types that implement an `Interface`, you may want to group them together in the cache. See `uniqueKeyGroup` for more information on the benefits of grouping cached objects. ```swift enum SchemaConfiguration: ApolloAPI.SchemaConfiguration { static func cacheKeyInfo(for type: Object, object: JSONObject) -> CacheKeyInfo? { if type.implements(Interfaces.Pet) { return try? CacheKeyInfo(jsonValue: object["id"], uniqueKeyGroup: Interfaces.Pet.name) } return nil } } ``` ### Initializers `init(id: String, uniqueKeyGroup: String?)` The Designated Initializer `init(jsonValue: (any ScalarType)?, uniqueKeyGroup: String?) throws` A convenience initializer for creating a `CacheKeyInfo` from the value of a field on a `JSONObject` dictionary representing a GraphQL response object. ### Instance Properties `let id: String` The unique cache id for the response object for the `CacheKeyInfo`. `let uniqueKeyGroup: String?` An optional identifier for a group of objects that should be grouped together in the `NormalizedCache`. ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/jsonresponseparsingerror/localizeddescription Retrieves the localized description for a JSONResponseParsingError. ```APIDOC ## localizedDescription ### Description Retrieve the localized description for a JSONResponseParsingError. ### Property Definition `var localizedDescription: String { get }` ### Compatibility - ApolloSwift: 8.0+ - macOS: 10.10+ - tvOS: 9.0+ - watchOS: 2.0+ ``` -------------------------------- ### Limiting Publisher Output with prefix(_:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/prefix%28_%3A%29 An example demonstrating how to limit a publisher's output to the first two elements. ```swift let numbers = (0...10) cancellable = numbers.publisher .prefix(2) .sink { print("\($0)", terminator: " ") } // Prints: "0 1" ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/graphqlexecutionerror/localizeddescription Retrieves the localized description for a GraphQLExecutionError. ```APIDOC ## localizedDescription ### Description Retrieve the localized description for this error. ### Property Definition `var localizedDescription: String { get }` ### Compatibility - ApolloSwift: 8.0+ - macOS: 10.10+ - tvOS: 9.0+ - watchOS: 2.0+ ``` -------------------------------- ### Instance Method scan(_:_:) Documentation Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/graphqlquerypager/scan%28_%3A_%3A%29 Detailed documentation for the scan(_:_:) method, including parameters, return values, and usage examples. ```APIDOC ## scan(_:_:) ### Description Transforms elements from the upstream publisher by providing the current element to a closure along with the last value returned by the closure. ### Method Instance Method ### Parameters - **initialResult** (T) - Required - The previous result returned by the nextPartialResult closure. - **nextPartialResult** (@escaping (T, Self.Output) -> T) - Required - A closure that takes as its arguments the previous value returned by the closure and the next element emitted from the upstream publisher. ### Return Value A publisher that transforms elements by applying a closure that receives its previous return value and the next element from the upstream publisher. ### Discussion Use Publisher/scan(_:_:) to accumulate all previously-published values into a single value, which you then combine with each newly-published value. ### Request Example ```swift let range = (0...5) cancellable = range.publisher .scan(0) { return $0 + $1 } .sink { print ("\($0)", terminator: " ") } // Prints: "0 1 3 6 10 15 ". ``` ``` -------------------------------- ### GET localizedDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollopagination/paginationerror/localizeddescription Retrieves the localized description for a PaginationError instance. ```APIDOC ## GET localizedDescription ### Description Retrieve the localized description for this error. ### Property var localizedDescription: String { get } ### Compatibility - ApolloPaginationSwift - iOS 8.0+ - macOS 10.10+ - tvOS 9.0+ - watchOS 2.0+ ``` -------------------------------- ### Subtracting Sets Example Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/operationdocumentformat/subtracting%28_%3A%29 Demonstrates creating a new set by removing elements found in another set. ```Swift let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] let nonNeighbors = employees.subtracting(neighbors) print(nonNeighbors) // Prints "["Diana", "Chris", "Alicia"]" ``` -------------------------------- ### GET operationIdentifier Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/graphqloperation/operationidentifier Retrieves the unique identifier for a GraphQL operation. ```APIDOC ## static var operationIdentifier ### Description A static property that returns the unique identifier for a GraphQL operation as a String. ### Definition `static var operationIdentifier: String? { get }` ### Usage This property is part of the `GraphQLOperation` protocol and is used to identify specific operations within the Apollo iOS framework. ``` -------------------------------- ### Implement loadMoreLaunchesIfTheyExist method Source: https://www.apollographql.com/docs/ios/tutorial/tutorial-paginate-results Check for existing launches and pagination availability before triggering a fetch. ```swift func loadMoreLaunchesIfTheyExist() async { guard !activeRequest else { return } guard let connection = self.lastConnection else { await self.loadMoreLaunches(from: nil) return } guard connection.hasMore else { return } await self.loadMoreLaunches(from: connection.cursor) } ``` -------------------------------- ### GET fragmentDefinition Source: https://www.apollographql.com/docs/ios/docc/documentation/apolloapi/fragment/fragmentdefinition Accesses the definition of a GraphQL fragment as a StaticString. ```APIDOC ## static var fragmentDefinition ### Description The definition of the fragment in GraphQL syntax. ### Property Details - **Name**: fragmentDefinition - **Type**: StaticString - **Requirement**: Required (Default implementation provided) ### Usage ```swift static var fragmentDefinition: StaticString { get } ``` ``` -------------------------------- ### Implement loadMoreLaunches method Source: https://www.apollographql.com/docs/ios/tutorial/tutorial-paginate-results Update the fetch logic to handle the cursor and update the local connection state. ```swift private func loadMoreLaunches(from cursor: String?) async { // highlight-line defer { // highlight-line activeRequest = false // highlight-line } // highlight-line do { activeRequest = true // highlight-line let response = try await ApolloClient.shared.fetch(query: LaunchListQuery(cursor: cursor ?? .null)) if let errors = response.errors { appAlert = .errors(errors: errors) } if let launchConnection = response.data?.launches { lastConnection = launchConnection // highlight-line launches.append(contentsOf: launchConnection.launches.compactMap({ $0 })) } } catch { appAlert = .errors(errors: [error]) } } ``` -------------------------------- ### GET graphQLError Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/responsecodeinterceptor/responsecodeerror/graphqlerror Retrieves the GraphQL error associated with the ResponseCodeInterceptor. ```APIDOC ## GET graphQLError ### Description Accesses the GraphQL error instance associated with the ResponseCodeInterceptor if one occurred during the request lifecycle. ### Property `var graphQLError: GraphQLError? { get }` ### Response - **graphQLError** (GraphQLError?) - An optional GraphQL error object containing details about the error encountered. ``` -------------------------------- ### init(rawValue:) Source: https://www.apollographql.com/docs/ios/docc/documentation/apollocodegenlib/apollocodegenconfiguration/operationdocumentformat/init%28rawvalue%3A%29 Initializes an instance of the configuration type using a raw UInt8 value. ```APIDOC ## init(rawValue:) ### Description Initializes an instance of the configuration type using a raw UInt8 value. ### Parameters #### Parameters - **rawValue** (UInt8) - Required - The raw value used to initialize the configuration. ``` -------------------------------- ### GET playgroundDescription Source: https://www.apollographql.com/docs/ios/docc/documentation/apollo/recordset/playgrounddescription Retrieves the playground description for the RecordSet instance. ```APIDOC ## playgroundDescription ### Description Returns the playground description for the current RecordSet instance. ### Property `var playgroundDescription: Any { get }` ``` -------------------------------- ### Initialize a basic ApolloClient Source: https://www.apollographql.com/docs/ios/networking/client-creation Creates a client with default configuration using an in-memory cache and HTTP network transport. ```swift let client = ApolloClient(url: URL(string: "http://localhost:4000/graphql")!) ```