The civilized way to write REST API clients for iOS / macOS

Last update: Aug 3, 2022

Siesta

The elegant way to write iOS / macOS REST clients

Build Status Version Platforms Docs GitHub license Twitter: @siestaframework

Drastically simplifies app code by providing a client-side cache of observable models for RESTful resources.

  • OS: iOS 10+, macOS 10.11+, tvOS 9.0+
  • Languages: Written in Swift, supports apps in both Swift and Objective-C
  • Tool requirements: Xcode 11.3+, Swift 5.1+ (See swift-* branches for legacy support)
  • License: MIT

Table of Contents

Overview

Documentation

  • User Guide — Extensive! Thrilling! Full of examples!
  • API Docs — Lascivious detail! Hidden treasure! More examples!
  • Specs — OK, doesn’t sound glamorous, but surprisingly informative.

What’s It For?

The Problem

Want your app to talk to a remote API? Welcome to your state nightmare!

You need to display response data whenever it arrives. Unless the requesting screen is no longer visible. Unless some other currently visible bit of UI happens to need the same data. Or is about to need it.

You should show a loading indicator (but watch out for race conditions that leave it stuck spinning forever), display user-friendly errors (but not redundantly — no modal alert dogpiles!), give users a retry mechanism … and hide all of that when a subsequent request succeeds.

Be sure to avoid redundant requests — and redundant response deserialization. Deserialization should be on a background thread, of course. Oh, and remember not to retain your ViewController / model / helper thingy by accident in your callback closures. Unless you’re supposed to.

Naturally you’ll want to rewrite all of this from scratch in a slightly different ad hoc way for every project you create.

What could possibly go wrong?

The Solution

Siesta ends this headache by providing a resource-centric alternative to the familiar request-centric approach.

Siesta provides an app-wide observable model of a RESTful resource’s state. This model answers three basic questions:

  • What is the latest data for this resource, if any?
  • Did the latest request result in an error?
  • Is there a request in progress?

…and broadcasts notifications whenever the answers to these questions change.

Siesta handles all the transitions and corner cases to deliver these answers wrapped up with a pretty bow on top, letting you focus on your logic and UI.

Features

  • Decouples view, model, and controller lifecycle from network request lifecycle
  • Decouples request initiation from request configuration
  • Eliminates error-prone state tracking logic
  • Eliminates redundant network requests
  • Unified handling for all errors: encoding, network, server-side, and parsing
  • Highly extensible, multithreaded response deserialization
  • Transparent built-in parsing (which you can turn off) for JSON, text, and images
  • Smooth progress reporting that accounts for upload, download, and latency
  • Transparent Etag / If-Modified-Since handling
  • Prebaked UI helpers for loading & error handling, remote images
  • Debug-friendly, customizable logging
  • Written in Swift with a great Swift-centric API, but…
  • …also works great from Objective-C thanks to a compatibility layer.
  • Lightweight. Won’t achieve sentience and attempt to destroy you.
  • Robust regression tests
  • Documentation and more documentation

What it doesn’t do

  • It doesn’t reinvent networking. Siesta delegates network operations to your library of choice (URLSession by default, or Alamofire, or inject your own custom adapter).
  • It doesn’t hide HTTP. On the contrary, Siesta strives to expose the full richness of HTTP while providing conveniences to simplify common usage patterns. You can devise an abstraction layer to suit your own particular needs, or work directly with Siesta’s nice APIs for requests and response entities.
  • It doesn’t do automatic response model mapping. This means that Siesta doesn’t constrain your response models, or force you to have any at all. Add a response transformer to output models of whatever flavor your app prefers, or work directly with parsed JSON.

Origin

This project started as helper code we wrote out of practical need on several Bust Out Solutions projects. When we found ourselves copying the code between projects, we knew it was time to open source it.

For the open source transition, we took the time to rewrite our code in Swift — and rethink it in Swift, embracing the language to make the API as clean as the concepts.

Siesta’s code is therefore both old and new: battle-tested on the App Store, then reincarnated in a Swifty green field.

Design Philosophy

Make the default thing the right thing most of the time.

Make the right thing easy all of the time.

Build from need. Don’t invent solutions in search of problems.

Design the API with these goals:

  1. Make client code easy to read.
  2. Make client code easy to write.
  3. Keep the API clean.
  4. Keep the implementation tidy.

…in that order of priority.


Installation

Siesta requires Swift 5 and Xcode 11. (Use the swift-* branches branches if you are still on an older version.)

Swift Package Manager

In Xcode:

  • File → Swift Packages → Add Package Dependency…

  • Enter https://github.com/bustoutsolutions/siesta in the URL field and click Next.

  • The defaults for the version settings are good for most projects. Click Next.

  • Check the checkbox next to “Siesta.”

    • Also check “SiestaUI” if you want to use any of the UI helpers.
    • Also check “Siesta_Alamofire” if you want to use the Alamofire extension for Siesta.
  • Click “Finish.”

  • Siesta does not yet support resources supplied by dependencies. This means that if:

    • you included SiestaUI above
    • and you plan to use ResourceStatusOverlay
    • and you are using its default initializer instead of providing your own custom UI layout,

    …then you’ll need to copy ResourceStatusOverlay.xib into your own project.

    SwiftPM just recently added support for this, and Siesta will add it in the next release.

Please note that Xcode will show all of Siesta’s optional and test-only dependencies, including Quick, Nimble, and Alamofire. Don’t worry: these won’t actually be bundled into your app (except Alamofire, if you use it).

CocoaPods

In your Podfile:

pod 'Siesta', '~> 1.0'

If you want to use the UI helpers:

pod 'Siesta/UI', '~> 1.0'

If you want to use Alamofire as your networking provider instead of Foundation’s URLSession:

pod 'Siesta/Alamofire', '~> 1.0'

(You’ll also need to pass an Alamofire.Manager when you configure your Siesta.Service. See the API docs for more info.)

Carthage

In your Cartfile:

github "bustoutsolutions/siesta" ~> 1.0

Follow the Carthage instructions to add Siesta.framework to your project. If you want to use the UI helpers, you will also need to add SiestaUI.framework to your project as well.

As of this writing, there is one additional step you need to follow that isn’t in the Carthage docs:

  • Build settings → Framework search paths → $(PROJECT_DIR)/Carthage/Build/iOS/

(In-depth discussion of Carthage in recent Xcode versions is here.)

The code in Extensions/ is not part of the Siesta.framework that Carthage builds. (This currently includes only Alamofire support.) You will need to include those source files in your project manually if you want to use them.

Git Submodule

  1. Clone Siesta as a submodule into the directory of your choice, in this case Libraries/Siesta:

    git submodule add https://github.com/bustoutsolutions/siesta.git Libraries/Siesta
    git submodule update --init
    
  2. Drag Siesta.xcodeproj into your project tree as a subproject.

  3. Under your project's Build Phases, expand Target Dependencies. Click the + button and add Siesta.

  4. Expand the Link Binary With Libraries phase. Click the + button and add Siesta.

  5. Click the + button in the top left corner to add a Copy Files build phase. Set the directory to Frameworks. Click the + button and add Siesta.

If you want to use the UI helpers, you will need to repeat steps 3–5 for SiestaUI.

Installation troubles?

Please let us know about it, even if you eventually figure it out. Knowing where people get stuck will help improve these instructions!


Basic Usage

Make a shared service instance for the REST API you want to use:

let MyAPI = Service(baseURL: "https://api.example.com")

Now register your view controller — or view, internal glue class, reactive signal/sequence, anything you like — to receive notifications whenever a particular resource’s state changes:

override func viewDidLoad() {
    super.viewDidLoad()

    MyAPI.resource("/profile").addObserver(self)
}

Use those notifications to populate your UI:

func resourceChanged(_ resource: Resource, event: ResourceEvent) {
    nameLabel.text = resource.jsonDict["name"] as? String
    colorLabel.text = resource.jsonDict["favoriteColor"] as? String

    errorLabel.text = resource.latestError?.userMessage
}

Or if you don’t like delegates, Siesta supports closure observers:

MyAPI.resource("/profile").addObserver(owner: self) {
    [weak self] resource, _ in

    self?.nameLabel.text = resource.jsonDict["name"] as? String
    self?.colorLabel.text = resource.jsonDict["favoriteColor"] as? String

    self?.errorLabel.text = resource.latestError?.userMessage
}

Note that no actual JSON parsing occurs when we invoke jsonDict. The JSON has already been parsed off the main thread, in a GCD queue — and unlike other frameworks, it is only parsed once no matter how many observers there are.

Of course, you probably don’t want to work with raw JSON in all your controllers. You can configure Siesta to automatically turn raw responses into models:

MyAPI.configureTransformer("/profile") {  // Path supports wildcards
    UserProfile(json: $0.content)         // Create models however you like
}

…and now your observers see models instead of JSON:

MyAPI.resource("/profile").addObserver(owner: self) {
    [weak self] resource, _ in
    self?.showProfile(resource.typedContent())  // Response now contains UserProfile instead of JSON
}

func showProfile(profile: UserProfile?) {
    ...
}

Trigger a staleness-aware, redundant-request-suppressing load when the view appears:

override func viewWillAppear(_ animated: Bool) {
    MyAPI.resource("/profile").loadIfNeeded()
}

…and you have a networked UI.

Add a loading indicator:

MyAPI.resource("/profile").addObserver(owner: self) {
    [weak self] resource, event in

    self?.activityIndicator.isHidden = !resource.isLoading
}

…or better yet, use Siesta’s prebaked ResourceStatusOverlay view to get an activity indicator, a nicely formatted error message, and a retry button for free:

class ProfileViewController: UIViewController, ResourceObserver {
    @IBOutlet weak var nameLabel, colorLabel: UILabel!

    @IBOutlet weak var statusOverlay: ResourceStatusOverlay!

    override func viewDidLoad() {
        super.viewDidLoad()

        MyAPI.resource("/profile")
            .addObserver(self)
            .addObserver(statusOverlay)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        MyAPI.resource("/profile").loadIfNeeded()
    }

    func resourceChanged(_ resource: Resource, event: ResourceEvent) {
        nameLabel.text  = resource.jsonDict["name"] as? String
        colorLabel.text = resource.jsonDict["favoriteColor"] as? String
    }
}

Note that this example is not toy code. Together with its storyboard, this small class is a fully armed and operational REST-backed user interface.

Your socks still on?

Take a look at AFNetworking’s venerable UIImageView extension for asynchronously loading and caching remote images on demand. Seriously, go skim that code and digest all the cool things it does. Take a few minutes. I’ll wait. I’m a README. I’m not going anywhere.

Got it? Good.

Here’s how you implement the same functionality using Siesta:

class RemoteImageView: UIImageView {
  static var imageCache: Service = Service()
  
  var placeholderImage: UIImage?
  
  var imageURL: URL? {
    get { return imageResource?.url }
    set { imageResource = RemoteImageView.imageCache.resource(absoluteURL: newValue) }
  }
  
  var imageResource: Resource? {
    willSet {
      imageResource?.removeObservers(ownedBy: self)
      imageResource?.cancelLoadIfUnobserved(afterDelay: 0.05)
    }
    
    didSet {
      imageResource?.loadIfNeeded()
      imageResource?.addObserver(owner: self) { [weak self] _,_ in
        self?.image = self?.imageResource?.typedContent(
            ifNone: self?.placeholderImage)
      }
    }
  }
}

A thumbnail of both versions, for your code comparing pleasure:

Code comparison

The same functionality. Yes, really.

(Well, OK, they’re not exactly identical. The Siesta version has more robust caching behavior, and will automatically update an image everywhere it is displayed if it’s refreshed.)

There’s a more featureful version of RemoteImageView already included with Siesta — but the UI freebies aren’t the point. “Less code” isn’t even the point. The point is that Siesta gives you an elegant abstraction that solves problems you actually have, making your code simpler and less brittle.

Comparison With Other Frameworks

Popular REST / networking frameworks have different primary goals:

  • URLSession is Apple’s standard iOS HTTP library (and is all most projects need).
  • Siesta untangles state problems with an observable resource cache.
  • Alamofire provides a Swifty, modern-feeling wrapper for URLSession.
  • Moya wraps Alamofire to hide HTTP URLs and parameters.
  • RestKit couples HTTP with JSON object model Core Data mapping.
  • AFNetworking is a modern-feeling Obj-C wrapper for Apple’s network APIs, plus a suite of related utilities.

Which one is right for your project? It depends on your needs and your tastes.

Siesta has robust functionality, but does not attempt to solve everything. In particular, Moya and RestKit address complementary / alternative concerns, while Alamofire and AFNetworking provide more robust low-level HTTP support. Further complicating a comparison, some frameworks are built on top of others. When you use Moya, for example, you’re also signing up for Alamofire. Siesta uses URLSession by default, but can also stack on top of Alamofire if you want to use its SSL trust management features. Combinations abound.

With all that in mind, here is a capabilities comparison¹:

Siesta Alamofire RestKit Moya AFNetworking URLSession
HTTP requests
Async response callbacks
Observable in-memory cache
Prevents redundant requests
Prevents redundant parsing
Parsing for common formats
Route-based parsing
Content-type-based parsing
File upload/download tasks ~
Object model mapping
Core data integration
Hides HTTP
UI helpers
Primary language Swift Swift Obj-C Swift Obj-C Obj-C
Nontrivial lines of code² 2609 3980 13220 1178 3936 ?
Built on top of any (injectable) URLSession AFNetworking Alamofire NSURLSession / NSURLConnection Apple guts

1. Disclaimer: table compiled by Siesta’s non-omniscient author. Corrections / additions? Please submit a PR.
2. “Trivial” means lines containing only whitespace, comments, parens, semicolons, and braces.

Despite this capabilities list, Siesta is a relatively lean codebase — smaller than Alamofire, and 5.5x lighter than RestKit.

What sets Siesta apart?

It’s not just the features. Siesta solves a different problem than other REST frameworks.

Other frameworks essentially view HTTP as a form of RPC. New information arrives only in responses that are coupled to requests — the return values of asynchronous functions.

Siesta puts the the “ST” back in “REST”, embracing the notion of state transfer as an architectural principle, and decoupling the act of observing state from the act of transferring it.

If that approach sounds appealing, give Siesta a try.


Documentation

Examples

This repo includes a simple example project. To download the example project, install its dependencies, and run it locally:

  1. Install CocoaPods ≥ 1.0 if you haven’t already.
  2. pod try Siesta (Note that there’s no need to download/clone Siesta locally first; this command does that for you.)

Support

To ask for help, please post a question on Stack Overflow and tag it with siesta-swift. (Be sure to include that tag. It triggers a notification to the Siesta core team.) This is preferable to filing an issue because other people may have the same question as you, and Stack Overflow answers are more discoverable than closed issues.

Things that belong on Stack Overflow:

  • “How do I…?”
  • “Is there a way to…?”
  • “Is Siesta appropriate for…?”
  • “I got this error…”

For a bug, feature request, or cool idea, please file a Github issue. Things that belong in Github issues:

  • “When I do x, I expect y but get z
  • “There should be a way to…”
  • “Documentation for x is missing / confusing”

Unsure which to choose? If you’re proposing a change to Siesta, use Github issues. If you’re asking a question that doesn’t change the project, and thus will remain valid even after you get an answer, then use Stack Overflow.

Two big little things

Keep in mind that Siesta is maintained by volunteers. Please be patient if you don’t immediately get an answer to your question; we all have jobs, families, obligations, and lives beyond this project.

Please be excellent to one another and follow our code of conduct.

GitHub

https://github.com/bustoutsolutions/siesta
Comments
  • 1. Update API for Apple’s newly released API design guidelines

    I reviewed Siesta’s API against Apple’s new API Design Guidelines for Swift, and identified ~27 names of concern. Of those, I recommend changing  8  14.

    Details of my review, proposed changes, and rationale are in this gist: https://gist.github.com/pcantrell/22a6564ca7d22789315b

    If anybody has opinions about these changes, or notices other places where Siesta’s naming conventions contradict the new guidelines, please comment on this issue.

    API changes will appear as deprecations in beta 6, and the deprecated methods will be removed in the subsequent release.

    Reviewed by pcantrell at 2015-12-09 06:37
  • 2. configureTransformer returns double-optional content

    Checking to see if there are any examples or tips on using ObjectMapper for model mapping in Siesta.

    I think something as simple as this should work, where User is a working ObjectMapper Mappable model, and I'm using the SwiftyJSON global transformer from @pcantrell here.

        configureTransformer("/profile/") {
            Mapper<User>.map($0.content as JSON) //error: type of expression is ambiguous without more context
        }
    
    Reviewed by andrewloyola at 2016-01-19 23:25
  • 3. Adding OSX target

    Hi,

    This PR is about adding an OSX target. After having looked around and tested various things, I think siesta is one of the best candidates for the app I am preparing. But it's an OSX app. I need an OSX target...

    This PR introduces the OSX target. Apart from all UIKit stuff, there are 0 changes (and I've merged upstream). The problem of course is UIKit's stuff. Fortunately it is fairly easy to workaround, since many many classes share the same APIs between the various platforms.

    For the cases where it is different, I've written a OSX.swift compatibility file where typealiases are defined (they allow to use the same type everywhere, mapping to the correct one depending on platform). And where I've written the little tricks necessary for the iOS siesta code to NOT change. That is, the tricks are here to adapt OSX interfaces to iOS ones, since I guess iOS remains the main ... target. :-)

    I've been able to build an OSX Test target as well. However, given the various dependencies on other thing to build tests, this makes things quite a lot more difficult. In particular, I had to create an OSX target for Nocilla (and change the file Cartfile.private to point to it)

    Anyway, I think the constraint of an OSX target is a good occasion to clearly separate class/code concerns/responsabilities. This PR is created maybe a bit toot early, but I wanted to expose/discuss it before siesta reach 1.0, to raise awareness. I am happy to discuss it for any changes and improvements necessary before merge, of course!

    Thanks anyway for the great project.

    Reviewed by onekiloparsec at 2016-06-05 09:01
  • 4. Unable to use 'Alamofire' as a networkprovider

    I have imported the 'Siesta' library by downloading through github. I want to add 'Alamofire; as a networkprovider. Service.init(baseURL: urlstring, useDefaultTransformers: true, networking: Alamofire.SessionManager ) I am getting error 'use of unresolved identifier 'Alamofire'. Help me to solve this.

    I want to use 'Alamofire' as a network provider for my rest api calls.

    Reviewed by LavanayaV at 2017-08-09 06:04
  • 5. ReactiveCocoa Extension

    Here is an initial draft for the ReactiveCocoa extension we talked about here. Some quick notes:

    • Resource class was changed to split the request(_:_:) method in two, you can see the detailed explanation in the commit message.
    • Errors in Error class are used but since default memberwise initializers are internal by default, and the ReactiveCocoa extension is not part of the framework, public initializers are added to instantiate them. However maybe that part of the code can be split like the request(_:_:) method in Resource class so that errors aren't accessed directly, but I wanted to check with you before going forward.
    • On a general note about the point above:rac_request methods duplicate the logic in request methods, so maybe request methods should be split for better reuse?
    • allowedCharsInURLEncoding variable is duplicated as well, it is private and the compiler gives an error when it is declared as public, the reason it being both final and dynamic in that case. I wanted to check with you as to how to eliminate this.
    • I opted for a glue object to do the observing and forward a ResourceState object when resourceChanged(_:_:) is called on them.

    Is there any configuration for swiftlint or anything like that for your code conventions? Do you do them manually or do you automate them?

    Needless to say, all feedback is welcome, critic feedback is more welcome :) Especially regarding method and variable names, I opted for quick names like nsreqWith but I'm open to suggestions.

    Reviewed by akaralar at 2016-07-16 15:28
  • 6. Possible memory leak in ProgressTracker

    Hi,

    Just found a memory leak using Instruments in Siesta. Seems to be related to the timer in ProgressTracker.swift, but not the obvious thing (strong reference from within timer closure).

    Image

    Reviewed by edwardmp at 2018-08-16 19:12
  • 7. Error when trying siesta with Argo

    Hi Paul,

    I'm diving even deeper into siesta, and I try to make it work with Argo. But I get an error I couldn't work around. That's maybe not an issue, but merely my own failure to grasp all the details involved here, especially with the siesta blocks arguments.

    Here is the code, in my subclass of Service:

        public init(withAPIVersion version: String = "1") {
            self.APIVersion = version
            super.init(baseURL: "http://api.arcsecond.io")
    
            self.configureTransformer("/\(self.APIVersion)/objects/*") {
                decode($0.content) as AstronomicalObject
            }
        }
    

    I get the following at the line self.configureTransformer...:

    Cannot invoke 'configureTransformer' with an argument list of type '(String, (_) -> _)'

    The code for AstronomicalObject follows the exact same example given by Argo, in its simplest form:

    public struct AstronomicalObject {
        public let name: String
    }
    
    public extension AstronomicalObject: Decodable {
        public static func decode(json: JSON) -> Decoded<AstronomicalObject> {
            return curry(AstronomicalObject.init)
                <^> json <| "name"
        }
    }
    

    I don't get this error when writing a "normal" init method for my struct, taking the json as parameter and doing all the parsing myself. But my goal is to use Argo precisely for that.

    Any idea? Thanks in advance!

    Reviewed by onekiloparsec at 2016-08-10 17:35
  • 8. Adds support for watchOS and tvOS

    • Added new targets and schemes
    • Added correct Foundation class mapping for the two new OS
    • Bypasses memory warning logic for watchOS as it is not supported
    Reviewed by victorcotap at 2017-03-16 23:04
  • 9. Allow EntityCache to function at any point in the transformer pipeline

    EntityCache currently must store and return only the values at the very end of the transformer pipeline.

    This works well when the end result of the pipeline is an easily serializable type such as text or JSON:

    siesta pipeline 1

    However, it’s problematic when the transform pipeline produces a model, which can be difficult for an EntityCache to store and retrieve:

    siesta pipeline 2

    Attempts to solve this problem by keeping models in a database quickly become problematic:

    • The database needs to be able to look up models by REST URL, which mixes abstraction layers and leads to hackish workarounds.
    • The EntityCache API is not designed to work with databases. (For example, it wants to pass cached entities across threads, which Realm doesn’t like.)

    Suppose, however, that an EntityCache could insert itself at any point in the transformer pipeline and not just the end. In other words, this is currently the only supported structure:

    → JSON transformer → Model transformer → (EntityCache) →
    

    …but suppose the pipeline instead supported this:

    → JSON transformer → (EntityCache) → Model transformer →
    

    When there is a cache hit, the pipeline would pick up immediately after the cache's position in the pipeline. An EntityCache could then work only with its preferred data type:

    siesta pipeline 3

    …or even:

    siesta pipeline 4

    This would require some hard thought in the plumbing, but seems to make sense. @annicaburns, would this solve the problems you were having with EntityCache? Would you still want to use Realm even with a mechanism like this in place?

    Reviewed by pcantrell at 2016-01-05 18:27
  • 10. Update for Xcode 9.3/Swift 4.1

    Basically I just did 2 things:

    • Automatic Xcode upgrade of the project
    • Replaced flatMap with compactMap where said map returned optionals

    Note: Travis Build shall fail until it's updated to use Xcode 9.3 image

    Reviewed by joaomvfsantos at 2018-04-03 14:52
  • 11. Specify queue on which resourceChanged to be called

    Currently I was not able to find an option to specify on which thread resourceChanged to be received. Such option would allow more flexibility when dealing with big responses.

    Reviewed by richardtop at 2017-01-30 00:46
  • 12. Add Combine support and RxSwift extension

    Hi Paul,

    Here's support for Combine and RxSwift as we talked about. Combine is in the main library code; RxSwift is in Extensions.

    It's influenced somewhat by the ReactiveCocoa extension and the talk around that.

    As ever, there's more than one way to skin any particular cat, and perhaps especially so in RxSwift. But I've been fairly conservative - nothing too outrageous here.

    Feedback entirely welcome of course.

    Adrian

    Reviewed by luxmentis at 2020-05-07 04:05
  • 13. [WIP] @ResourceBacked property wrapper

    A common idiom in Siesta projects is to have UI code point at some resource that can change, and whenever it changes, to:

    • stop observing the old resource,
    • add one or more observers to the new resource (the same observers every time), and
    • load if needed.

    The Siesta docs and the example project recommend doing this via didSet:

    var doodadsResource: Resource? {
        didSet {
            oldValue?.removeObservers(ownedBy: self)
    
            doodadsResource?
                .addObserver(self)
                .addObserver(statusOverlay, owner: self)
                .loadIfNeeded()
        }
    }
    
    var doodads: [Doodad] {  // convenience accessor
        return doodadsResource?.typedContent() ?? []
    }
    

    Swift 5.2’s property wrappers give us a better option. This PR adds a @ResourceBacked property wrapper that lets any variable take its value from a Siesta resource.

    The example above becomes:

    @ResourceBacked(default: [])
    var doodads: [Doodad]
    
    // during initialization, e.g. in viewDidLoad() or some such:
    $doodads.addObserver(self)
    $doodads.addObserver(statusOverlay)
    

    The doodads variable now behaves as if it is a read-only Doodad array; for example, we can do this:

    for doodad in doodads {  // just works
        print(doodad.name)
    }
    

    However, that array comes from a Siesta resource — and we can switch which resource on the fly:

    $doodads.resource = api.resource(“foo”).child(newDoodadID)
    

    Changing the resource in this way automatically:

    • removes our little flock of observers from the old resource (if any),
    • adds our flock of observers to the new resource (if any),
    • sends the appropriate events to the observers so they show the change immediately, and
    • triggers a call to loadIfNeeded().

    Future work on this feature

    • [ ] The wrapper should detect whether the resource’s value does not match the variable’s type, and report this as an error via $doodads.error. This would give better error reporting to the user if the server returns well-formed but unexpected content. (If you ask for $doodads.resource?.latestError, you still get only underlying resource errors, since resources (at least in Siesta 1.0) have freely typed content.)
    • [ ] Property wrapper should wrap response to observers to reflect the above
    • [ ] Clients should be able to opt out of automatic loadIfNeeded
    • [ ] Any facilities necessary for doing custom requests?
    • [ ] Make sure it plays nice with SwiftUI
    Reviewed by pcantrell at 2020-04-08 03:58
  • 14. File cache

    This PR adds a file-based cache implementation to Siesta. This will give most projects offline access & fast launch for almost free.

    A word on why this is so compelling for Siesta: traditional HTTP caches (such as URLSession’s cache) exist to prevent requests for data that is still fresh (enough). This makes them good for reducing network traffic, but bad for offline access: it’s a strict choice between getting the cached data or the fresh network data. Worse yet, the API gets to make that choice for you based on (usually ill-behaved) HTTP headers!

    Siesta’s architecture, however, makes it possible for a Resource to simultaneously have data and be in the midst of requesting data. This makes it possible for your app to launch with the last data it last had — no matter how old, you decide whether you want to show it — and show that stored data even as it is requesting fresh data, even if that request fails.

    This all happens fairly transparently for Siesta apps. Called loadIfNeeded and you’ll get a newData(cache) event when the cached data arrives, then a newData(network) event if the load request succeeds. All you have to do is build your UI so that loading and network errors don’t completely obscure the UI, and bingo! offline access.

    There is still documentation work and cleanup to do here, but the code on this branch should be ready to use in your project! I encourage Siesta users to try it and report back. Please give it a whirl! 🙏

    To try it out:

    service.configure {
        $0.pipeline[.rawData].cacheUsing {
            try FileCache<Data>(
                poolName: “some locally unique name for your API",
                dataIsolation: .perUser(identifiedBy: someUserSpecificValue))
        }
    }
    

    …or if you are using public data that can be shared across users of the app:

                dataIsolation: .sharedByAllUsers
    

    This PR also fixes numerous subtle problems with the existing cache infrastructure. It’s long been possible roll your own persistent caching for Siesta, but it always involved a bit of per-project finagling. Improvements here should make custom caches both easier to write and easier to work with — most notably, caches now only apply to GET requests and do not apply to cross-resource requests with load(using:). These two gotchas were a common source of trouble with custom cache implementations.

    Fixes #289. Fixes #291.

    Reviewed by pcantrell at 2020-04-06 05:37
  • 15. 404 errors from a resource don't clear as expected from a resource("static url").load()

      My app needs to monitor the network connection to an API. After enough errors accumulate, It stops making normal requests and lazily pings the API with a static URL as follows:
    
     let userRequest = VAPI.sharedInstance.resource("").load(). // Base url is a health check for the api.
    

    When an adequate number of successful pings has occurred, the app goes back to normal operation. During testing I can inject errors into the API response and clear them as needed. For every error except 404, the system works as expected. With 404, the ping keeps getting 404 responses from the load() even after the network response has gone back to a normal 200.

    As the error clears the load() returns 1 good response and then resumes returning 404. Using URLSession I get a 200 for the success. With Alamofire, the success is a 304. A parallel direct URLSession request as follows:

    // Test code let url = URL.init(string: VAPI.VAPIBaseURL) let dataTask = self.defaultSession.dataTask(with: url!) { [weak self] data, response, error in // 5 if error != nil { print(error?.localizedDescription) } else if let data = data, let response = response as? HTTPURLResponse { print("URLSession Response =====> ", response.statusCode) } }

            dataTask.resume()
    

    Behaves as expected. I've attached a log file of the divergent responses.

    404 Clearing Log.docx

    Reviewed by tjmorgan0 at 2019-12-17 17:29
  • 16. Chained request progress support

    Chained requests currently do not support progress. If you are reading these words and want that feature, please file an issue on Github!

    It happened! How big of a deal is this?

    Reviewed by karlshea at 2019-09-19 02:31
FreeRDP is a free remote desktop protocol library and clients

FreeRDP: A Remote Desktop Protocol Implementation FreeRDP is a free implementation of the Remote Desktop Protocol (RDP), released under the Apache lic

Aug 5, 2022
TheraForge's Client REST API framework to connect to TheraForge's secure CloudBox Backend-as-a-Service (BaaS)

OTFCloudClientAPI TheraForge's Client REST API Framework to Connect to TheraForg

Dec 23, 2021
Lightweight REST library for iOS and watchOS. Available on cococapods
Lightweight REST library for iOS and watchOS. Available on cococapods

RMHttp RMHttp is a Lightweight REST library for iOS and watchOS. Features Chainable Request URL / JSON Parameter Encoding HTTP Methods GET/POST/DELETE

Mar 13, 2022
Swift/Obj-C HTTP framework with a focus on REST and JSON

Now Archived and Forked PMHTTP will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PHMT

Jul 31, 2022
Lightweight REST and JSON library for Swift.

RestEssentials is an extremely lightweight REST and JSON library for Swift and can be used on iOS, iPadOS, macOS, tvOS, and watchOS. Features Easily p

Jul 1, 2022
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

Apr 18, 2022
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

Apr 18, 2022
Write clean, concise and declarative network code relying on URLSession, with the power of RxSwift. Inspired by Retrofit.

ReactiveAPI Reactive API library allows you to write clean, concise and declarative network code, with the power of RxSwift and URLSession! iOS Demo A

Jul 8, 2022
APIProvider - API Provider Package for easier API management inspired by abstraction

APIProvider Using APIProvider you can easily communicate with all API endpoints

Apr 21, 2022
macOS VM for Apple Silicon using Virtualization API
macOS VM for Apple Silicon using Virtualization API

MacVM macOS Monterey added support for virtualizing macOS with Apple silicon host. This project provides an example project for the setup. Currently o

Aug 5, 2022
EasyImplementationAlamoFire - An iOS project to demonstrate the usage of Alamofire in an efficient and organised way.

EasyImplementationAlamoFire Tutorial to demonstrate an efficient way of handling the APIs structure for your iOS Applications. Prerequisites Swift 5 X

Jan 3, 2022
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

Jun 5, 2022
The easy way to use sockets on Apple platforms

SwiftSocket SwiftSocket library provides as easy to use interface for socket based connections on server or client side. Supports both TCP and UDP soc

Aug 2, 2022
Music Room: a mobile app that offers a new way of experiencing music
Music Room: a mobile app that offers a new way of experiencing music

?? Music Room - 42 School Project ?? ???? Music Room is a mobile app that offers

Feb 18, 2022
Real-time Apps the SwiftUI way
Real-time Apps the SwiftUI way

Sync Sync is a proof of concept for expanding on the Magic of ObservableObject, and making it work over the network. This let's you create real-time A

Aug 11, 2022
Jan 26, 2022
🌸 Powerful Codable API requests builder and manager for iOS.
🌸 Powerful Codable API requests builder and manager for iOS.

This lib is about network requests with blackjack, roulette and craps! Using it you will be able to convert your massive API layer code into an awesom

Jul 21, 2022
An iOS library to route API paths to objects on client side with request, mapping, routing and auth layers

WANetworkRouting Developed and Maintained by ipodishima Founder & CTO at Wasappli Inc. Sponsored by Wisembly A routing library to fetch objects from a

Oct 24, 2016
The official iOS client library for api.video
The official iOS client library for api.video

api.video iOS client api.video is the video infrastructure for product builders.

May 24, 2022