ArcGIS Runtime SDK for iOS

Run a geoprocessing task

A geoprocessing service contains one or more geoprocessing tasks. A geoprocessing task is a geoprocessing tool running on a service and its execution and outputs are managed by the service. You can run these tools from an ArcGIS Runtime app.

Steps to run a geoprocessing task at a high level:

  1. Create a AGSGeoprocessingTask using full URL to the target geoprocessing task endpoint.
  2. Create AGSGeoprocessingParameters providing corresponding AGSGeoprocessingExecutionType.
  3. Create AGSGeoprocessingParameter(s) as required, and add them to AGSGeoprocessingParameters:inputs: where key is the name of the parameter and value is created parameter.
  4. Set environment variables on AGSGeoprocessingParameters if needed.
  5. Create AGSGeoprocessingJob by calling the job creation method on the geoprocessing task, using the parameters created previously.
  6. Listen for job changed status and message changes on the AGSGeoprocessingJob.
  7. Run the geoprocessing job and if it completes successfully, get the AGSGeoprocessingResult.
  8. Handle returned values accordingly. Output parameters are accessed as a dictionary on AGSGeoprocessingResult where key is the name of the output parameter and the value is returned parameter. If the geoprocessing service is configured to use a result map service then the result may also contain a map image layer that has been created for you.

Creating a geoprocessing task

AGSGeoprocessingTask is the main component when running geoprocessing tasks which is used to run a single geoprocessing task. The target is defined by providing URL to the target REST endpoint.

The format for a geoprocessing task URL is http://<gpservice-url>/<taskName>. The endpoint for a task called 'BufferPoints' hosted on 'myserver', for example, would be something like:

https://myserver/ArcGIS/rest/services/BufferPoints/GPServer/BufferPoints

let geoprocessingTask = AGSGeoprocessingTask(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/911CallsHotspot/GPServer/911%20Calls%20Hotspot")!)

Creating input parameters

AGSGeoprocessingParameters contains input parameters and environment variables. Required input parameters are defined by the geoprocessing task. Environment variables are common geoprocessing variables that guide how the service works.

When AGSGeoprocessingParameters is created, it needs to know the execution type of the task. This defines which REST endpoint the AGSGeoprocessingJob is using when the task is executed. This value needs to match the one defined in the used service.

GeoprocessingParameters.inputs is a dictionary that contains all the parameters that are sent to the service. The key of the item is the name of the parameter and the value contains the AGSGeoprocessingParameter. When parameters are provided to the geoprocessing task their parameter name and type needs to match the one defined in a task. At a minimum all parameters that are set as required on the task must be provided to run the task successfully.

You can also provide a set of optional environment variables. These control general settings for the service, such as whether the Z and M values are returned in the result, or which spatial reference to use for the results. For example, if you are visualizing the results of the analysis on the map, requesting the results in the same spatial reference as the map view uses removes the need for the client to reproject the results before adding them to the map view.

//create a GeoprocessingParameters with an asynchronous execution type
let params = AGSGeoprocessingParameters(executionType: .asynchronousSubmit)

//provide a query string as an input parameters to the geoprocessing task
let queryString = "(\"DATE\" > date '1998-01-01 00:00:00' AND \"DATE\" < date '1998-01-03 00:00:00')"
params.inputs["Query"] = AGSGeoprocessingString(value: queryString)

Task execution types

When working with geoprocessing services, you must be aware of the execution type that the service was published with. This execution type can be found on the service's REST page. There are multiple execution types that define how geoprocessing tasks run on a server:

  • Execute (defined as esriExecutionTypeSynchronous in task page)

    Synchronous execution is designed for fast-running tasks and they are run synchronously on the server. The client sends a request asynchronously to the service and waits for the response. This means these types of services use less resources on the server. When targeting a geoprocessing service that is exposed using this type, AGSGeoprocessingParameters needs to be created using AGSGeoprocessingExecutionTypeSynchronousExecute.

  • Submit (defined as esriExecutionTypeAsynchronous in task page)

    Asynchronous services are best suited for long running jobs and are run using asynchronous model on the server. For asynchronous tasks, the server returns a job ID that the client uses to poll for the task status. When the job is completed, the results are fetched separately from the job result endpoints. When targeting a geoprocessing service that is exposed using this type, AGSGeoprocessingParameters needs to be created using AGSGeoprocessingExecutionTypeAsynchronousSubmit.

If a geoprocessing tool is published from ArcGIS Desktop with a map server result to visually represent each geodataset output parameter as a layer then the geoprocessing server (GPServer) will have an accompanying dynamic map server of the same name for presenting the results. This map service's symbology is based on the symbology of the output layer that resulted from running the geoprocessing tool in ArcGIS Desktop during the publishing process. See Defining output symbology for geoprocessing tasks for additional information on setting the symbology for a result map service.

AGSGeoprocessingJob, which does the communication between the client and the service, knows which REST endpoint to use based on the execution type that was given as a parameter for AGSGeoprocessingParameters and it has to match the execution type on the service. If the value isn't correct then an exception is thrown when the task is run.

Parameters

Geoprocessing tasks usually have input and output parameters. These parameters are defined when the geoprocessing task is authored and can be seen in geoprocessing task page in the services directory. Each parameter of a task has a set of descriptive properties that help you understand the parameter and provide appropriate value for the successful execution of the task.

When parameters are provided to the geoprocessing task their parameter name and type needs to match the one defined in a task. At a minimum all parameters that are set as required on the task must be provided to run the task successfully

The significance of each property is described below

Parameter direction

Every parameter has a direction which is defined in the parameter information. This information helps you identify whether the parameter is an input or output parameter.

When the task is executed, the client needs to provide values for the input parameters only. Output parameters are returned from the task when the job has been run successfully.

Output parameters are always returned from a geoprocessing task in a dictionary.

Parameter data types

The data type of the parameter specifies the type of value that the client must provide for the parameter. The value of a parameter can be as simple as a string, long, double, Boolean or date. Or, it can be a set of features or records or a raster file. For example, if the task is expecting to have a raster input parameter, you need to provide a geoprocessing raster parameter in a AGSGeoprocessingParameters:getInputs: collection to execute the tool successfully.

Here is a list of ArcGIS Runtime geoprocessing parameter types and which types they correspond to the service.

Required and optional parameters

Parameters can be defined as: required, required with default value, optional, or derived. When the parameter is required but doesn't have default value defined, the parameter must be provided when the geoprocessing task is executed. If the default value is defined, then you can override that value by providing a new parameter in a AGSGeoprocessingParameters.inputsdictionary. Optional parameters can be provided in the same manner. Derived means that the you do not enter a value for the parameter. Derived types are always output parameters.

ArcGIS Runtime parameter typesCorresponding REST typesNote

AGS GeoprocessingString

GPString

A string. If ChoiceList is defined in a parameter then the value must match one of the items in the list

AGS GeoprocessingDouble

GPDouble

A decimal value approximately between -2.2E308 to 1.7E308

AGSGeoprocessingLong

GPLong

An integer value between −2,147,483,648 to 2,147,483,647

AGS GeoprocessingBoolean

GPBoolean

True or false

AGS GeoprocessingDate

GPDate

A date value

AGS GeoprocessingLinearUnit

GPLinearUnit

A value that has a distance value and its unit of measurement such as kilometers or meters

AGS GeoprocessingDataFile

GPDataFile

References a file such as .txt, .pdf, .csv, and so on. Supported data types are controlled by the used service. Can reference a file that is uploaded to the service using Uploads capability

AGS GeoprocessingRaster

GPRasterData

References a single raster file such as .tif or .jpg, and so on.

Can reference a raster that is uploaded to the service using Uploads capability.

AGS GeoprocessingRaster

GPRasterDataLayer

Super set of GPRasterData that supports showing values on result map server.

AGS GeoprocessingFeatures

GPRecordSet

A set of Features that represents rows and columns. Doesn't have a geometry or spatial reference.

Can reference a file that has the features serialized.

AGS GeoprocessingFeatures

GPFeatureRecordSetLayer

A set of Features that have a geometry, spatial reference and attributes.

Can reference a file that has the features serialized.

AGS GeoprocessingMultiValue

GPMultiValue

An array of geoprocessing parameters of the same data type

Running the task and handling the results

The targeted geoprocessing task is run using AGSGeoprocessingJob which is responsible handling the communication between the client and the service. AGSGeoprocessingJob is created using AGSGeoprocessingTask and AGSGeoprocessingParameters, and it can be started by calling startWithStatusHandler. AGSGeoprocessingJob also provides an awaitable task which runs the job and returns the results when the task is completed successfully. If any errors occurs while the job is running, an exception is thrown. The error can be also retrieved directly from the AGSGeoprocessingJob.

let geoprocessingJob = geoprocessingTask.geoprocessingJob(with: params)
 geoprocessingJob.start(statusHandler: { (status) in
    print("Status: \(status.statusString())")},
    completion: { (result, error) in
        if let error = error {
            print(error)
            return
        }

        if geoprocessingJob.result != nil {
            //process results
            print("Process results")
        }
    }
)

Results as a map image layer

The result map server is a dynamic map service that accompanies a geoprocessing service to visualize the geoprocessing results. If this is enabled in the geoprocessing task, then theAGSGeoprocessingResult.mapImageLayer might be populated for you. The visualization of the layer is determined by the symbology on the geoprocessing service.

This functionality is available on the geoprocessing services that has execution type of submit with result map server functionality enabled.

//confirm there is a result
if geoprocessingJob.result == nil {
    return
}
 //display the results as a Map Image Layer
let mapImageLayer = result?.mapImageLayer
 if let mapImageLayer = mapImageLayer {
    self?.mapView.map?.operationalLayers.add(mapImageLayer)
}

In case where AGSGeoprocessingResult.mapImageLayer is populated in the results and the geoprocessing result outputs contain AGSGeoprocessingFeatures parameters, features aren't automatically downloaded to the client to avoid unnecessary traffic between the service and the client. If you need to download the features, you can get the features explicitly from the results.

if let resultFeatures = geoprocessingJob.result?.outputs["Output_Features"] as? AGSGeoprocessingFeatures {
          if resultFeatures.canFetchOutputFeatures {
                 resultFeatures.fetchOutputFeatures(completion: { (resultFeatureSet, error) in
            if let error = error {
                print(error)
                return
            }
            if let resultFeatureSet = resultFeatureSet {
                for feature in resultFeatureSet.featureEnumerator().allObjects {
                    let redSymbol = AGSSimpleMarkerSymbol(style: .circle, color: .red, size: 10)
                    let graphic = AGSGraphic(geometry: feature.geometry, symbol: redSymbol, attributes: nil)
                    self?.resultsGraphicsOverlay.graphics.add(graphic)
                }
            }
        })
    }
}

Downloading geoprocessing data files and rasters

If AGSGeoprocessingDataFiles or AGSGeoprocessingRasters are used as output parameters, they have a URL specified to the location of the output file. This file can be downloaded to the client device easily by using an awaitable task.

if let resultRaster = geoprocessingJob.result?.outputs["Hotspot_Raster"] as? AGSGeoprocessingRaster {
         let fileURL = URL(fileURLWithPath: filePath)
         //download the raster file
    resultRaster.download(toFileURL: fileURL, completion: { (localURL, error) in

        if let error = error {
            print(error)
            return
        }
                 if let localURL = localURL {
            print(localURL)
        }
    })
}