Tasks are bound to online or offline data or services and provide methods to perform asynchronous operations using those resources.
With tasks you can:
- Download, collect, and update geographic information using
AGSGeodatabaseSyncTask
- Download and display tiled basemaps using
AGSExportTileCacheTask
- Locate addresses on the map and interpolate addresses from map locations using
AGSLocatorTask
- Calculate point-to-point or multi-stop routes and get driving directions using
AGSRouteTask
- Perform complex GIS analysis by executing geoprocessing models using
AGSGeoprocessingTask
Tasks either return their results directly from asynchronous methods on the task, or make use of jobs to provide status updates and results.
Tasks
Some operations return results directly from asynchronous methods on the task. For more complex or longer running operations, tasks make use of jobs instead.
To use tasks that return results directly:
- Create the task by initializing it to use the required data or service.
- Some operations can work both online and offline.
- Define the task inputs.
- Some operations require only simple value inputs (for example a simple geocode operation may only require an address string as input).
- Others require input parameters (for example, to limit a geocode operation to a specific country).
- Call the async operation method, passing in the inputs you defined.
- Use the results from the operation as required, for example to display geocode results on a map.
The code below creates a
AGSLocatorTask
using the Esri geocode service, and passes in an address to geocode. When the operation is complete, the result location is retrieved and displayed in a
AGSGraphicsOverlay
.
// Create a new LocatorTask from a geocode service endpoint
locatorTask = AGSLocatorTask(url: URL(string: "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer")!)
locatorTask?.geocode(withSearchText: "380 New York Street, Redlands, CA"){[weak self] (results, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
else if let bestResult = results?.first {
let bestGraphic = AGSGraphic(geometry: bestResult.displayLocation, symbol: aSymbol, attributes: bestResult.attributes)
self?.graphicsOverlay.graphics.add(bestGraphic)
}
}
Define input parameters
Tasks offer numerous options that allow you to tailor the operation to your requirements. For example, when geocoding you can restrict your search to a specific area, country, category of place, and/or number of results. When an author publishes a service or packages a resource, they can choose default values for these options that suit the specific data or the most common use case for the service.
To use these default parameter values, tasks provide helper methods that create parameter objects initialized with service-specific values. You can then make any changes to the parameter values before passing them to an operation. Creating these default parameter objects is useful for operations with many options, such as tracing a utility network.
The code below gets the default parameters for a
AGSRouteTask
, and then ensures that results using these parameters will return both a route and directions, and also that the output spatial reference matches that of the map view.
self?.routeTask?.defaultRouteParameters(){ [weak self] (params, error) -> Void in
if let error = error {
print(error)
return
}
// explicitly set values for some parameters
if let routeParameters = params {
routeParameters.returnDirections = true
routeParameters.returnRoutes = true
routeParameters.outputSpatialReference = self?.mapView.spatialReference
// solve the route with these parameters
self?.routeTask?.solveRoute(with: routeParameters) {(routeResult, error) -> Void in
if let error = error{
print(error)
return
}
//work with the results...
}
}
}
Some parameters objects have constructors that you can use if you know the values of all the input parameters you want to use. This can be more efficient when parameter settings are simple.
For example, the code below creates geocoding parameters that restrict the country within which to geocode, and to limit the maximum returned results.
let geocodeParams = AGSGeocodeParameters()
geocodeParams.countryCode = "France"
geocodeParams.maxResults = 5
Work online or offline
Many tasks can work either online by using services, or offline by using local data and resources. For example, you can geocode an address by using the default Esri geocoding service, your own geocoding service, a locator file (.loz
), or a mobile map package (.mmpk
).
// create a locator task from a geocode service endpoint
let locatorURL = URL(string: "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer")!
locatorTask = AGSLocatorTask(url: locatorURL)
// or create a locator task from a local .loz file
offlineLocatorTask = AGSLocatorTask(name: "locatorfilename.loz")
// or create a locator task from mobile map packages (if it contains one)
self.mobileMapPackage.load {[weak self] (error) -> Void in
guard error == nil else {
print(error!.localizedDescription)
return
}
self?.locatorTask = self?.mobileMapPackage.locatorTask
}
Tasks and jobs
Some tasks expose operations that have multiple stages (like preparing and downloading a geodatabase), and can generate multiple progress messages (such as percentage complete). These types of tasks are always bound to ArcGIS Server (or Local Server for platforms that support it). An example is
AGSGeodatabaseSyncTask.generateJobWithParameters()
.
Instead of returning results directly, these tasks make use of jobs to monitor status, return progress updates, and return their results. Each
AGSJob
represents a specific operation of a task. Jobs are useful for longer-running operations, because they can also be paused, resumed, and canceled. Your app can support a user action or host OS terminating a running job object, and then recreate and resume the job later.
To use operations like these:
- Create the task by initializing it to use the required data or service.
- Define the input parameters for the task.
- Call the async operation method to get a job, passing in the input parameters you defined.
- Start the job.
- Optionally, listen for changes to the job status and check the job messages, for example to update a UI and report progress to the user.
- Listen for the job completion and get the results from the operation. Check for errors in the job, and if successful, use the results.
//create a sync task with the URL of the feature service to sync
geodatabaseSyncTask = AGSGeodatabaseSyncTask(url: URL(string: "")!)
// create sync parameters
let taskParameters = AGSSyncGeodatabaseParameters()
taskParameters.rollbackOnFailure = true
taskParameters.geodatabaseSyncDirection = .bidirectional
//instantiate a job to submit the sync job
//using the synchronization parameters and the geodatabase containing the edits
syncJob = geodatabaseSyncTask.syncJob(with: taskParameters, geodatabase: self.generatedGeodatabase)
//start the sync job
//the statusHandler block is invoked whenever the job's status changes
//the completion block is invoked with the result when the job succeeds, or an error if it fails
syncJob.start(statusHandler:
{ (status) in
if status == .succeeded {print("Job succeeded")}
else if status == .failed {print("Job failed")}
else {print("Sync in progress")}
})
{ (results, error) in
if let error = error {
print(error)
return
}
//examine the results
}
Calling
AGSJob.status
retrieves the current
AGSJobStatus
in the job's workflow. Jobs periodically fire a changed event as they are running, usually with decreasingly frequency as a job progresses. More than one
AGSJobMessage
may appear in a change event. The job complete listener is called as soon as the job finishes. Whether successful or not, jobs cannot be restarted.
Report job progress
A job represents an asynchronously running operation that might take some time to finish. As described previously, you can monitor changes to job status for notification when a job has completed, failed, or been canceled, but what about the time in-between? Users may become frustrated waiting for a long job to complete without getting feedback on its progress. Fortunately, jobs provide a mechanism for reporting the current progress (percentage complete) for the running operation they represent.
As the job runs it provides a
AGSJob.progress
property, an integer representing the percentage of the operation that has been completed. This allows your app to provide more specific information about the status of a running job using UI elements like progress bars, for example.
Add an observer to the ongoing job to monitor the fraction
. This code displays this fraction
value in the status completion block. Alternatively, you could pass the observed
to the UI
and the value will be automatically updated in the UI.
//instantiate the AGSOfflineMapTask
self.offlineMapTask = AGSOfflineMapTask(onlineMap: self.map)
let params = AGSGenerateOfflineMapParameters(areaOfInterest: geometry, minScale: 100000, maxScale: 1000)
//generate an offline map job
self.offlineMapJob = self.offlineMapTask?.generateOfflineMapJob(with: params, downloadDirectory: url)
//add an observer to display the % of the job completed
offlineMapJob.progress.addObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted), options: .new, context: &myContext)
offlineMapJob.progress.removeObserver(self, forKeyPath: #keyPath(Progress.fractionCompleted), context: &myContext)
//start the job add the offline map to the mapview when complete
offlineMapJob.start(statusHandler: {[weak self] (status) in
print("Status [\(String(describing: self?.offlineMapJob.progress.fractionCompleted))]: \(status)")})
{[weak self] (result, error) in
//remove observer
guard let strongSelf = self else {return}
strongSelf.offlineMapJob.progress.removeObserver(strongSelf, forKeyPath: #keyPath(Progress.fractionCompleted), context: &myContext)
//check for errors
if let error = error {
print(error)
return
}
//display the offline map
guard let result = result as? AGSGenerateOfflineMapResult else {return}
self?.mapView.map = result.offlineMap
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let progress = object as? Progress, keyPath == #keyPath(Progress.fractionCompleted){
DispatchQueue.main.async {
//move this to the main thread because progress can proceed on a background thread
print("progress changed: \(progress.fractionCompleted * 100)")
}
}
}
Remember to remove the observer when the job has completed.
Pause, resume, or cancel a job
Jobs are designed to handle a user exiting an app while the job is running or having the app terminated by the host operating system. Jobs also provide a mechanism for explicitly pausing or canceling the operation.
Cancel a job
Sometimes, the results of a job are no longer required. For example, a user could change their mind about the area of a tile cache they want to download and want to cancel the job and start over.
Calling
AGSJob.cancelWithCompletion:()
changes
AGSJobStatus
to canceling
, cancels the
AGSJob
, and waits for any asynchronous, server-side operations to be canceled. After all cancelation tasks complete (including any server-side tasks),
AGSJobStatus
changes to failed
and
AGSJob.cancelWithCompletion:()
call back is fired . If one or more jobs cannot be canceled,
AGSJob.cancelWithCompletion:()
fires an error .
For example,
AGSGenerateOfflineMapJob
is a server-side job that launches several more server-side jobs, depending on the layers in your map. Other examples of server-side jobs include
AGSExportTileCacheJob
,
AGSExportVectorTilesJob
,
AGSGenerateGeodatabaseJob
, and
AGSGeoprocessingJob
.
You should always cancel unneeded jobs (for example when exiting your app) to avoid placing unnecessary load on the server.
The following example shows you how to examine the
AGSJob
error once the job has failed. In this case the error code NS
would indicate that the job has been terminated by the user.
offlineMapJob.start(statusHandler: {(status) in})
{ (result, error) in
if let error = error as NSError? {
if error.domain == NSCocoaErrorDomain && error.code == NSUserCancelledError{
print("User Cancelled")
}
return
}
else {
//process the result
}
}
Pause and resume a job
Jobs can be long-running operations, so there is no guarantee that they will be completed while the app is running. You can pause a job explicitly using the pause
method through the NS
API (exposed via NS
through the
AGSJob.progress
property). For example, when an app is backgrounded and does not have permissions for background operation. Pausing may also be useful if a user wishes to temporarily stop network access for any reason.
Job changed messages will not be received for a paused job. Pausing a job does not stop any server-side processes from executing. While a job is paused, outstanding requests can complete. Therefore, when resuming a job it may have a different state than when it was paused.
You can serialize a job to JSON to persist it if your app is backgrounded or the process is otherwise terminated. When you deserialize it again the
AGSJobStatus
will be in the paused state regardless of its state when serialized and should be restarted to resume listening for completion. The job changed listener is a good place to update the job JSON for storage by your app.
Serialize the job to JSON with the following code:
if let jobJson = try? self.offlineMapJob.toJSON(){
//save the JSON to disc or store in NSUserDefaults
}
}
Deserialize the job from JSON then restart the job:
//create the job from JSON
if let offlineMapJob = (try? AGSGenerateOfflineMapJob.fromJSON(jobJSON)) as? AGSGenerateOfflineMapJob{
offlineMapJob.start(statusHandler: { (status) in
//examine status
})
{ (result, error) in
//process the result and errors
}
}
Loss of network connection
Additionally, jobs using services are designed to handle situations where network connectivity is temporarily lost without needing to be immediately paused. A started job will ignore errors such as network errors for a period of up to 10 minutes. If errors continue for longer, the job will fail and the message will indicate the loss of network connection.
To handle inconsistent connectivity, you can serialize and pause a job when your app loses connectivity for a few minutes to avoid job failure (as failed jobs cannot be restarted). The job can then be deserialized and resumed when connectivity returns.