### youtube.playlistItems.list Example Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home This example demonstrates how to construct a query to list playlist items using the `youtube.playlistItems.list` method. It shows the Objective-C interface for the query class and how to instantiate it with the required 'part' parameter. ```APIDOC ## youtube.playlistItems.list ### Description Returns a collection of playlist items that match the API request parameters. ### Method GET (implied by list operation) ### Endpoint (Not explicitly defined, but implied by the method name) ### Parameters #### Query Parameters - **part** (string) - Required - A comma-separated list of one or more playlistItem resource properties that the API response will include. ### Response #### Success Response (200) - **GTLRYouTube_PlaylistItemListResponse** - The response object containing playlist items. ``` -------------------------------- ### Uploading a File (Google Drive) Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home This example demonstrates how to upload a file to Google Drive using `GTLRUploadParameters`. It covers specifying the file URL, MIME type, and handling the upload completion. ```APIDOC ## Upload File to Google Drive ### Description Uploads a file to the user's Google Drive account. ### Method POST (implied by create operation with upload) ### Endpoint (Not explicitly defined, but implied by the method name `GTLRDriveQuery_FilesCreate`) ### Parameters #### Request Body - **GTLRDrive_File** - Represents the file metadata. - **name** (string) - The name of the file to be uploaded. #### Upload Parameters - **GTLRUploadParameters** - Object containing file data and MIME type. - **fileURL** (NSURL) - Required - The URL of the file to upload. - **MIMEType** (string) - Required - The MIME type of the file. - **useBackgroundSession** (BOOL) - Optional - Set to YES to use background NSURLSession for chunked uploads. - **shouldUploadWithSingleRequest** (BOOL) - Optional - Set to YES for small uploads to use a single server request. ### Request Example ```Objective-C - (void)uploadFileURL:(NSURL *)fileToUploadURL { GTLRDriveService *service = self.driveService; GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithFileURL:fileToUploadURL MIMEType:@"text/plain"]; GTLRDrive_File *newFile = [GTLRDrive_File object]; newFile.name = path.lastPathComponent; GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:newFile uploadParameters:uploadParameters]; GTLRServiceTicket *uploadTicket = [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDrive_File *uploadedFile, NSError *callbackError) { if (callbackError == nil) { // Succeeded } }]; } ``` ``` -------------------------------- ### Upload a File to Google Drive Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Uploads a file to Google Drive using its URL. This example demonstrates creating GTLRUploadParameters with a file URL and MIME type, then executing a file creation query. ```Objective-C - (void)uploadFileURL:(NSURL *)fileToUploadURL { GTLRDriveService *service = self.driveService; GTLRUploadParameters *uploadParameters = [GTLRUploadParameters uploadParametersWithFileURL:fileToUploadURL MIMEType:@"text/plain"]; GTLRDrive_File *newFile = [GTLRDrive_File object]; newFile.name = path.lastPathComponent; GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:newFile uploadParameters:uploadParameters]; GTLRServiceTicket *uploadTicket = [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDrive_File *uploadedFile, NSError *callbackError) { if (callbackError == nil) { // Succeeded } }]; } ``` -------------------------------- ### Batch Operations: Individual Query Completion Block Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Execute multiple unrelated queries together in a batch for improved performance. This example shows how to add a query to a batch and specify an individual completion block for its results. ```Objective-C GTLRCalendarQuery_EventsList *eventsQuery = [GTLRCalendarQuery_EventsList queryWithCalendarId:calendarID]; eventsQuery.completionBlock = ^(GTLRServiceTicket *callbackTicket, GTLRCalendar_Events *events, NSError *callbackError) { If (callbackError == nil) { // This query succeeded. } }; GTLRBatchQuery *batch = [GTLRBatchQuery batchQuery]; [batch addQuery:eventsQuery]; ``` -------------------------------- ### Add Core Library to Podfile for Custom APIs Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md If you are generating code for your own APIs, add this to your Podfile to get the core library runtime. You will then manually add the generated sources to your Xcode project. ```ruby pod 'GoogleAPIClientForREST/Core' ``` -------------------------------- ### Partial Update: Change Calendar Name Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Use a patch query to replace only specific fields of an item. This example shows how to change only the summary of a calendar. ```Objective-C GTLRCalendar_Calendar *patchObject = [GTLRCalendar_Calendar object]; patchObject.summary = newCalendarName; GTLRCalendarQuery_CalendarsPatch *query = [GTLRCalendarQuery_CalendarsPatch queryWithObject:patchObject calendarId:calendarID]; [service executeQuery:query ... ``` -------------------------------- ### Partial Update: Delete Calendar Location Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home An explicit null value indicates that a field should be deleted. This example demonstrates removing only the location from a calendar. ```Objective-C GTLRCalendar_Calendar *patchObject = [GTLRCalendar_Calendar object]; patchObject.location = [GTLRObject nullValue]; GTLRCalendarQuery_CalendarsPatch *query = [GTLRCalendarQuery_CalendarsPatch queryWithObject:patchObject calendarId:calendarID]; [service executeQuery:query ... ``` -------------------------------- ### Partial Update: Delete Calendar Location Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md To delete a field, set its value to an explicit null value using `[GTLRObject nullValue]`. This example removes the location from a calendar. ```Objective-C GTLRCalendar_Calendar *patchObject = [GTLRCalendar_Calendar object]; patchObject.location = [GTLRObject nullValue]; GTLRCalendarQuery_CalendarsPatch *query = [GTLRCalendarQuery_CalendarsPatch queryWithObject:patchObject calendarId:calendarID]; [service executeQuery:query ... ``` -------------------------------- ### Fetch YouTube Playlist Items with Objective-C Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Demonstrates how to create a service, construct a query for playlist items, and execute it. It also shows how to handle the response, including iterating through playlist items and accessing their properties. Ensure you replace "put your API key here" with your actual API key. ```Objective-C ```Objective-C - (void)fetchPublicPlaylistWithID:(NSString *)playlistID { // Create a service for executing queries. For best performance, reuse // the same service instance throughout the app. // // Some of the service's properties may be set on a per-query basis // via the query's executionParameters property. GTLRYouTubeService *service = [[GTLRYouTubeService alloc] init]; // Services which do not require user authentication may need an API key // from the Google Developers Console service.APIKey = @"put your API key here"; // APIs which retrieve a collection of items may need to fetch // multiple pages. The service can optionally make multiple requests // to fetch all pages. The page size can be set in most APIs with the // query parameter maxResults. service.shouldFetchNextPages = YES; // The library can retry common networking errors. The retry criteria // may be customized by setting the service's retryBlock property. service.retryEnabled = YES; // Each API method has a unique class. The required properties // of the API method are the parameters of the constructor. // Optional properties of the API method are properties of the // class. // The YouTube API requires a "part" parameter for each query. // The playlist ID an an optional property of the method. GTLRYouTubeQuery_PlaylistItemsList *query = [GTLRYouTubeQuery_PlaylistItemsList queryWithPart:@"snippet"]; query.playlistId = playlistID; // A ticket is returned to let the app monitor or cancel query execution. GTLRServiceTicket *ticket = [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRYouTube_PlaylistItemListResponse *playlistItemList, NSError *callbackError) { // This callback block is run when the fetch completes. if (callbackError != nil) { NSLog(@"Fetch failed: %@", callbackError); } else { // The error is nil, so the fetch succeeded. // // GTLRYouTube_PlaylistItemListResponse derives from // GTLRCollectionObject, so it supports iteration of // items and subscript access to items. for (GTLRYouTube_PlaylistItem *item in playlistItemList) { // Print the name of each playlist item. NSLog(@"%@", item.snippet.title); } } }]; } ``` ``` -------------------------------- ### Generate Service with Options Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/Tools/ServiceGenerator/README.md Invoke the built ServiceGenerator with the --help flag to view available options and usage instructions. ```shell .build/release/ServiceGenerator --help ``` -------------------------------- ### Build Service Generator Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/Tools/ServiceGenerator/README.md Clone the repository, navigate to the ServiceGenerator directory, and build the project using Swift Package Manager. ```shell git clone cd google-api-objectivec-client-for-rest/Tools/ServiceGenerator swift build -configuration release ``` -------------------------------- ### Creating a GTLRObject from Scratch (Google Drive Folder) Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home This snippet illustrates how to create a `GTLRObject` instance from scratch, specifically for creating a new folder in Google Drive. It shows how to set properties like `name` and `mimeType` before executing the query. ```APIDOC ## Create Google Drive Folder ### Description Creates a new folder within the user's Google Drive account. ### Method POST (implied by create operation) ### Endpoint (Not explicitly defined, but implied by the method name `GTLRDriveQuery_FilesCreate`) ### Request Body - **GTLRDrive_File** - Represents the file or folder to be created. - **name** (string) - Required - The name of the new folder. - **mimeType** (string) - Required - The MIME type, set to 'application/vnd.google-apps.folder' for folders. ### Request Example ```Objective-C - (void)createAFolder { GTLRDriveService *service = self.driveService; GTLRDrive_File *folder = [GTLRDrive_File object]; folder.name = @"New Folder Name"; folder.mimeType = @"application/vnd.google-apps.folder"; GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:folder uploadParameters:nil]; [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDrive_File *folderItem, NSError *callbackError) { // Callback if (callbackError == nil) { // Succeeded. } }]; } ``` ``` -------------------------------- ### Download File using Query Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home For smaller files, use a library query to download media. The downloaded file is passed as a GTLRDataObject to the query callback. ```Objective-C GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileID]; [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDataObject *dataObject, NSError *callbackError) { if (callbackError == nil) { // The file downloaded successfully; its data is available as dataObject.data } }]; ``` -------------------------------- ### Create a Google Drive Folder Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Creates a new folder in Google Drive. This method initializes a GTLRDrive_File object, sets its name and MIME type, and then executes a create query. ```Objective-C - (void)createAFolder { GTLRDriveService *service = self.driveService; GTLRDrive_File *folder = [GTLRDrive_File object]; folder.name = @"New Folder Name" folder.mimeType = @"application/vnd.google-apps.folder"; GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:folderObj uploadParameters:nil]; [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDrive_File *folderItem, NSError *callbackError) { // Callback if (callbackError == nil) { // Succeeded. } }]; } ``` -------------------------------- ### Generate Services from Discovery Artifact Cache Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/DEVELOPMENT.md Generate services using a local cache of discovery data. This avoids network issues and allows skipping specific artifacts. ```bash Tools/GenerateCheckedInServices \ --no-preferred \ `Tools/preferred_paths_from_cache.py --skip poly ../discovery-artifact-manager/discoveries` \ ../discovery-artifact-manager/discoveries/admin.directory_v1.json \ ../discovery-artifact-manager/discoveries/admin.datatransfer_v1.json ``` -------------------------------- ### Publish CocoaPod Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/DEVELOPMENT.md Push the CocoaPod to trunk, skipping import validation and tests for faster release. Ensure you are logged in and a registered owner. ```bash pod trunk push --skip-import-validation --skip-tests GoogleAPIClientForREST.podspec ``` -------------------------------- ### Import GTLRService and GTLRYouTube in Objective-C Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md When using Objective-C, you can import library headers using the framework import syntax, which works with both CocoaPods and SwiftPM. ```objectivec #import #import ``` -------------------------------- ### Add Drive API to Podfile Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md To include the Drive API, add this line to your Podfile. This will also include the core library files. ```ruby pod 'GoogleAPIClientForREST/Drive' ``` -------------------------------- ### Download File Media with a Query Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Download media files directly using a library query. The downloaded file data is passed as a GTLRDataObject instance to the query callback. ```Objective-C GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileID]; [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRDataObject *dataObject, NSError *callbackError) { if (callbackError == nil) { // The file downloaded successfully; its data is available as dataObject.data } }]; ``` -------------------------------- ### Fetch Public YouTube Playlist Items Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Use this to fetch items from a public YouTube playlist. Ensure you reuse the service instance for performance. Set an API key for services not requiring user authentication. The library can automatically fetch all pages if needed. ```Objective-C - (void)fetchPublicPlaylistWithID:(NSString *)playlistID { // Create a service for executing queries. For best performance, reuse // the same service instance throughout the app. // // Some of the service's properties may be set on a per-query basis // via the query's executionParameters property. GTLRYouTubeService *service = [[GTLRYouTubeService alloc] init]; // Services which do not require user authentication may need an API key // from the Google Developers Console service.APIKey = @"put your API key here"; // APIs which retrieve a collection of items may need to fetch // multiple pages. The service can optionally make multiple requests // to fetch all pages. The page size can be set in most APIs with the // query parameter maxResults. service.shouldFetchNextPages = YES; // The library can retry common networking errors. The retry criteria // may be customized by setting the service's retryBlock property. service.retryEnabled = YES; // Each API method has a unique class. The required properties // of the API method are the parameters of the constructor. // Optional properties of the API method are properties of the // class. // The YouTube API requires a "part" parameter for each query. // The playlist ID an an optional property of the method. GTLRYouTubeQuery_PlaylistItemsList *query = [GTLRYouTubeQuery_PlaylistItemsList queryWithPart:@"snippet"]; query.playlistId = playlistID; // A ticket is returned to let the app monitor or cancel query execution. GTLRServiceTicket *ticket = [service executeQuery:query completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRYouTube_PlaylistItemListResponse *playlistItemList, NSError *callbackError) { // This callback block is run when the fetch completes. if (callbackError != nil) { NSLog(@"Fetch failed: %@", callbackError); } else { // The error is the nil, so the fetch succeeded. // // GTLRYouTube_PlaylistItemListResponse derives from // GTLRCollectionObject, so it supports iteration of // items and subscript access to items. for (GTLRYouTube_PlaylistItem *item in playlistItemList) { // Print the name of each playlist item. NSLog(@"%@", item.snippet.title); } } }]; } ``` -------------------------------- ### Generate Xcode Project with CocoaPods Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/DEVELOPMENT.md Use this command to generate an Xcode project from the podspec for development. Specify platforms like 'macos', 'tvos', or 'watchos' as needed. ```bash pod gen GoogleAPIClientForREST.podspec --local-sources=./ --auto-open --platforms=ios ``` -------------------------------- ### Manually Fetch Next Page of Results Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Check if more pages are available and manually construct a query to fetch the next page of results by reusing a copy of the previous query and setting the pageToken. ```Objective-C // Check if more pages are available for this collection object. if (object.nextPageToken) { // Manually make a query to fetch the next page of results by reusing a copy // of the previous query that was made before the query was executed. GTLRTasksQuery *nextQuery = copyOfPreviousQuery; nextQuery.pageToken = object.nextPageToken; GTLRServiceTicket *nextTicket = [service executeQuery:nextQuery ... } ``` -------------------------------- ### GTLRYouTube_PlaylistItem Object Interface Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Illustrates the structure of a GTLRYouTube_PlaylistItem object, showing its properties and their types. This helps in understanding how to access data fields within playlist items. ```Objective-C ```Objective-C @interface GTLRYouTube_PlaylistItem : GTLRObject @property(strong) GTLRYouTube_PlaylistItemContentDetails *contentDetails; @property(copy) NSString *ETag; @property(copy) NSString *identifier; @property(copy) NSString *kind; @property(strong) GTLRYouTube_PlaylistItemSnippet *snippet; @property(strong) GTLRYouTube_PlaylistItemStatus *status; @end ``` ``` -------------------------------- ### Update Generated Services Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/DEVELOPMENT.md Run this script to update the generated services in Sources/GeneratedServices. Use --skip arguments to ignore problematic services. ```bash Tools/GenerateCheckedInServices ``` -------------------------------- ### Download File using GTMSessionFetcher Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home For larger files, use GTMSessionFetcher to download content. The service method `requestForQuery:` converts a library query into an NSURLRequest, and a fetcher created from the service's fetcher service will authorize the download. ```Objective-C GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileID]; NSURLRequest *downloadRequest = [service requestForQuery:query]; GTMSessionFetcher *fetcher = [service.fetcherService fetcherWithRequest:downloadRequest]; [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *fetchError) { if (fetchError == nil) { // Download succeeded. } }]; ``` -------------------------------- ### Progress Monitoring for Uploads Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home This snippet shows how to implement progress monitoring during file uploads by providing a block to the `uploadProgressBlock` property of the query's execution parameters. ```APIDOC ## Upload Progress Monitoring ### Description Allows an application to monitor the progress of file uploads by providing a callback block. ### Method (Applies to any upload query) ### Parameters #### Execution Parameters - **uploadProgressBlock** (block) - A block to be called for displaying progress during uploads. - **ticket** (GTLRServiceTicket *) - The service ticket for the upload. - **numberOfBytesRead** (unsigned long long) - The number of bytes read so far. - **dataLength** (unsigned long long) - The total expected data length of the upload. ### Code Example ```Objective-C query.executionParameters.uploadProgressBlock = ^(GTLRServiceTicket *ticket, unsigned long long numberOfBytesRead, unsigned long long dataLength) { [uploadProgressIndicator setDoubleValue:(double)numberOfBytesRead]; [uploadProgressIndicator setMaxValue:(double)dataLength]; }; ``` ``` -------------------------------- ### Execute Query with Delegate and Selector Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Execute a query and receive the result via a delegate and selector. The delegate is retained until the query completes or is canceled. ```Objective-C GTLRServiceTicket *ticket = [service executeQuery:query \ delegate:self \ finishedSelector:@selector(serviceTicket:finishedWithObject:error:)]; ``` -------------------------------- ### Execute Query with Delegate and Selector Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Use this method to execute a query and receive the result via a callback. The delegate is retained until the query completes or is canceled. ```Objective-C GTLRServiceTicket *ticket = [service executeQuery:query delegate:self finishedSelector:@selector(serviceTicket:finishedWithObject:error:)]; ``` -------------------------------- ### Define YouTube Playlist Item List Query Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Defines a query object for fetching a collection of playlist items. Use this when you need to retrieve playlist items based on specified parameters. ```Objective-C /** * Returns a collection of playlist items that match the API request * parameters. * * Method: youtube.playlistItems.list */ @interface GTLRYouTubeQuery_PlaylistItemsList : GTLRYouTubeQuery /** * Fetches a GTLRYouTube_PlaylistItemListResponse * * @param part The part parameter specifies a comma-separated list of one or * more playlistItem resource properties that the API response will include. * * @returns GTLRYouTube_PlaylistItemListResponse */ + (instancetype)queryWithPart:(NSString *)part; ``` -------------------------------- ### Enable Automatic Page Fetches Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Turn on automatic fetching of all result pages by setting the shouldFetchNextPages property to YES on the service object. ```Objective-C // Turn on automatic page fetches service.shouldFetchNextPages = YES; ``` -------------------------------- ### Enable HTTP Logging in Objective-C Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Enable logging of HTTP server traffic, including headers, by calling `[GTMSessionFetcher setLoggingEnabled:YES]`. Ensure `GTMSessionFetcherLogging.h` and `.m` are included in your project. ```Objective-C [GTMSessionFetcher setLoggingEnabled:YES] ``` -------------------------------- ### Enable Single Request Upload Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Configures upload parameters to use a single server request for small uploads. This can improve performance for files under approximately 500K. ```Objective-C uploadParameters.shouldUploadWithSingleRequest = YES; ``` -------------------------------- ### Update Project Version Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/DEVELOPMENT.md Execute this script to update the version number across project files. Ensure the version is in X.Y.Z format. ```bash ./update_version.py 3.2.1 ``` -------------------------------- ### Monitor Upload Progress Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Sets a block to be called during file uploads to monitor progress. This allows for updating UI elements like progress indicators. ```Objective-C query.executionParameters.uploadProgressBlock = ^(GTLRServiceTicket *ticket, unsigned long long numberOfBytesRead, unsigned long long dataLength) { [uploadProgressIndicator setDoubleValue:(double)numberOfBytesRead]; [uploadProgressIndicator setMaxValue:(double)dataLength]; }; ``` -------------------------------- ### Download File Media with GTMSessionFetcher Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Download any NSURLRequest using GTMSessionFetcher. Use 'requestForQuery:completion:' when calling from the UI thread to avoid blocking. A fetcher created from the GTLRService object's fetcher service will authorize the download request. ```Objective-C GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileID]; [service requestForQuery:query completion:^(NSURLRequest *downloadRequest) { GTMSessionFetcher *fetcher = [service.fetcherService fetcherWithRequest:downloadRequest]; [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *fetchError) { if (fetchError == nil) { // Download succeeded. } }]; }]; ``` -------------------------------- ### Open HTTP Debug Logs Directory in Shell Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Paste the provided log path into a terminal window to open the directory containing saved HTTP traffic logs. ```shell open "/Users/username/Library/Developer/.../GTMHTTPDebugLogs" ``` -------------------------------- ### Configure Test Block for Unit Tests in Objective-C Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Use the `testBlock` property to simulate query responses during unit tests without making network calls. The block should invoke its response parameter with a mock object or error. ```Objective-C query.executionParameters.testBlock = ^(GTLRServiceTicket *ticket, GTLRQueryTestResponse testResponse) { // The query is available from the ticket. GTLRQuery *testQuery = ticket.originalQuery; // The testBlock can create a GTLRObject or GTLRBatchResult, or an NSError. // // Here, we will make a GTLRObject as the test response. GTLRDrive_File *fileObj = [GTLRDrive_File object]; fileObj.name = @"My Fake File"; NSError *testError = nil; testResponse(fileObj, testError); }; ``` -------------------------------- ### Batch Operation: Individual Query Completion Block Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Specify a completion block for each query within a batch operation. This is useful for handling results of unrelated methods individually. ```Objective-C GTLRCalendarQuery_EventsList *eventsQuery = [GTLRCalendarQuery_EventsList queryWithCalendarId:calendarID]; eventsQuery.completionBlock = ^(GTLRServiceTicket *callbackTicket, GTLRCalendar_Events *events, NSError *callbackError) { If (callbackError == nil) { // This query succeeded. } }; GTLRBatchQuery *batch = [GTLRBatchQuery batchQuery]; [batch addQuery:eventsQuery]; ``` -------------------------------- ### Request Specific Fields in Response Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Optimize API calls by fetching only necessary data using the `fields` property on a query. Ensure `kind` fields are always included for proper object instantiation, and include `nextPageToken` for collection responses. ```Objective-C query.fields = @"items(id,author/email,kind),kind,nextPageToken"; ``` -------------------------------- ### Execute Batch Queries with Completion Handler Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Use this to execute multiple GTLRQuery objects in a single batch request. The completion handler receives a GTLRBatchResult containing successes and failures, or an NSError if the entire batch execution failed. ```Objective-C GTLRBatchQuery *batchQuery = [GTLRBatchQuery batchQuery]; [batchQuery addQuery:query1]; [batchQuery addQuery:query2]; [service executeQuery:batchQuery completionHandler:^(GTLRServiceTicket *callbackTicket, GTLRBatchResult *batchResult, NSError *callbackError) { if (callbackError == nil) { // Execute succeeded: step through the query successes // and failures in the result. NSDictionary *successes = batchResult.successes; for (NSString *requestID in successes) { GTLRObject *result = [successes objectForKey:requestID]; } NSDictionary *failures = batchResults.failures; for (NSString *requestID in failures) { GTLRErrorObject *errorObj = [failures objectForKey:requestID]; } } else { // Here, callbackError is non-nil so the execute failed: // no success or failure results were obtained from the server. } }]; ``` -------------------------------- ### Pass Data to Query Callbacks Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Provide application-specific data to callback methods by setting `ticketProperties` on the query's execution parameters. This data is accessible within the callback via the ticket. ```Objective-C query.executionParameters.ticketProperties = @{ @"file source", localFileURL }; ticket = [service executeQuery:query delegate:self didFinishSelector:@selector(serviceTicket:finishedWithObject:error:)]; ``` ```Objective-C - (void)serviceTicket:(GTLRServiceTicket *)callbackTicket finishedWithObject:(Test_GTLRDrive_File *)object error:(NSError *)callbackError { if (callbackError == nil) { NSURL *localFileURL = callbackTicket.ticketProperties[@"file source"]; } } ``` -------------------------------- ### Batch Operation: Error Handling for Specific Queries Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home When using completion blocks for individual queries in a batch, errors passed to the block may contain an underlying GTLRErrorObject if the server returned an error for that specific query. ```Objective-C GTLRErrorObject *errorObj = [GTLRErrorObject underlyingObjectForError:error]; if (errorObj) { // The server returned this error for this specific query. } else { // This error occurred because the batch execution failed. } ``` -------------------------------- ### Pass Data to Query Callbacks via Ticket Properties Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Pass application-specific data to callback methods by setting ticketProperties on the query's executionParameters. Access this data within the callback using the ticketProperties property of the GTLRServiceTicket. ```Objective-C query.executionParameters.ticketProperties = @{ @"file source", localFileURL }; ticket = [service executeQuery:query delegate:self didFinishSelector:@selector(serviceTicket:finishedWithObject:error:)]; ``` -------------------------------- ### Specify Large Page Size for Results Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Reduce the need to fetch additional result pages by specifying a large page size using the maxResults property on the query object. ```Objective-C // Specify a large page size to reduce the need to fetch additional result pages GTLRTasksQuery *query = [GTLRTasksQuery_TasklistsList query]; query.maxResults = 1000; ticket = [service executeQuery:query ... ``` -------------------------------- ### Specify Large Page Size for Results Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Reduce the need to fetch additional result pages by specifying a large page size using the maxResults property on the query object. ```Objective-C // Specify a large page size to reduce the need to fetch additional result pages GTLRTasksQuery *query = [GTLRTasksQuery_TasklistsList query]; query.maxResults = 1000; ticket = [service executeQuery:query ... } ``` -------------------------------- ### GTLRYouTube_PlaylistItem Object Interface Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md This Objective-C interface defines the properties of a YouTube playlist item object, which is a subclass of GTLRObject. ```Objective-C @interface GTLRYouTube_PlaylistItem : GTLRObject @property(strong) GTLRYouTube_PlaylistItemContentDetails *contentDetails; @property(copy) NSString *ETag; @property(copy) NSString *identifier; @property(copy) NSString *kind; @property(strong) GTLRYouTube_PlaylistItemSnippet *snippet; @property(strong) GTLRYouTube_PlaylistItemStatus *status; @end ``` -------------------------------- ### Pause and Resume Uploads Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Uploads can be paused and resumed using the ticket object. This functionality is not available for uploads sent with `shouldUploadWithSingleRequest` set. ```Objective-C if (ticket.uploadPaused) { [ticket resumeUpload]; } else { [ticket pauseUpload]; } ``` -------------------------------- ### Add User Properties to GTLRObject Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Attach local data to a GTLRObject instance using the userProperties dictionary. This data is not sent to the server or serialized. ```Objective-C GTLRDrive_File *file = [GTLRDrive_File object]; file.userProperties = @{ @”LocalFileURL” : fileLocalURL }; ``` -------------------------------- ### Set Custom Class Resolver for a Single Query Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Override the objectClassResolver for a specific query using its executionParameters property. This allows for per-query subclass instantiation. ```Objective-C GTLRDriveQuery_FilesList *query = [GTLRDriveQuery_FilesList query]; query.executionProperties.objectClassResolver = updatedResolver; ``` -------------------------------- ### Deserialize Property List Data to GTLRObject Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Deserialize NSData back into a GTLRObject using NSPropertyListSerialization and the +objectWithJSON: class method. Use the objectClassResolver variant for better type resolution based on 'kind' properties. ```Objective-C NSData *data = [NSData dataWithContentsOfURL:fileURL options:0 error:&error]; if (data) { NSMutableDictionary *dict = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:NULL error:&error]; if (dict) { GTLRCalendar_Events *eventsList = [GTLRCalendar_Events objectWithJSON:dict]; // or GTLRCalendar_Events *eventsList2 = [GTLRCalendar_Events objectWithJSON:dict objectClassResolver:calendarService.objectClassResolver]; } } ``` -------------------------------- ### Subclass GTLRObjects with Custom Class Resolver Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Subclass GTLRObjects to add custom properties and methods. Set the objectClassResolver on the service to instantiate your subclasses during JSON parsing. ```Objective-C GTLRDriveService *service = [[GTLRDriveService alloc] init]; NSDictionary *surrogates = @{ [GTLRDrive_File class] : [MyFile class], [GTLRDrive_FileList class] : [MyFileList class] }; NSDictionary *serviceKindMap = [[service class] kindStringToClassMap]; GTLRObjectClassResolver *updatedResolver = [GTLRObjectClassResolver resolverWithKindMap:serviceKindMap surrogates:surrogates]; service.objectClassResolver = updatedResolver; ``` -------------------------------- ### Subclass GTLRObjects for Custom Parsing Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Replace standard GTLRObject subclasses with custom ones during JSON parsing by setting the `objectClassResolver` on the service. This allows for custom properties and methods. ```Objective-C GTLRDriveService *service = [[GTLRDriveService alloc] init]; NSDictionary *surrogates = @{ [GTLRDrive_File class] : [MyFile class], [GTLRDrive_FileList class] : [MyFileList class] }; NSDictionary *serviceKindMap = [[service class] kindStringToClassMap]; GTLRObjectClassResolver *updatedResolver = [GTLRObjectClassResolver resolverWithKindMap:serviceKindMap surrogates:surrogates]; service.objectClassResolver = updatedResolver; ``` ```Objective-C GTLRDriveQuery_FilesList *query = [GTLRDriveQuery_FilesList query]; query.executionProperties.objectClassResolver = updatedResolver; ``` -------------------------------- ### Partial Update: Change Calendar Name Source: https://github.com/google/google-api-objectivec-client-for-rest/blob/main/USING.md Use a patch query to replace only specific fields of an item, such as changing the name of a calendar. This replaces the entire item on the server with only the specified fields. ```Objective-C GTLRCalendar_Calendar *patchObject = [GTLRCalendar_Calendar object]; patchObject.summary = newCalendarName; GTLRCalendarQuery_CalendarsPatch *query = [GTLRCalendarQuery_CalendarsPatch queryWithObject:patchObject calendarId:calendarID]; [service executeQuery:query ... ``` -------------------------------- ### Enable Automatic Retry for GTLR Service Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Enable automatic retry for common network and server errors by setting the retryEnabled property to YES on the GTLR service. This helps in handling transient issues gracefully. ```Objective-C // Turn on automatic retry of some common error results service.retryEnabled = YES; ``` -------------------------------- ### Serialize GTLRObject to Property List Data Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Serialize a GTLRObject's JSON representation into NSData using NSPropertyListSerialization for saving to disk. Ensure the JSON dictionary is constructed with mutable containers when deserializing. ```Objective-C // Saving to disk. NSError *serializeError; NSData *data = [NSPropertyListSerialization dataWithPropertyList:events.JSON format:NSPropertyListBinaryFormat_v1_0 options:0 error:&serializeError]; if (data) { NSError *writeError; BOOL didWrite = [data writeToURL:fileURL options:0 error:&writeError]; } ``` -------------------------------- ### Access Ticket Properties in Callback Source: https://github.com/google/google-api-objectivec-client-for-rest/wiki/Home Retrieve application-specific data passed to a callback method from the ticketProperties of the GTLRServiceTicket. This is useful for correlating callbacks with their originating requests. ```Objective-C - (void)serviceTicket:(GTLRServiceTicket *)callbackTicket finishedWithObject:(Test_GTLRDrive_File *)object error:(NSError *)callbackError { if (callbackError == nil) { NSURL *localFileURL = callbackTicket.ticketProperties[@"file source"]; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.