当前位置: 首页 > 软件库 > 程序开发 > 网络工具包 >

siesta

授权协议 MIT License
开发语言 C/C++
所属分类 程序开发、 网络工具包
软件类型 开源软件
地区 不详
投 递 者 蔡理
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Siesta

The elegant way to write iOS / macOS REST clients

VersionPlatformsDocsGitHub licenseTwitter: @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.

  • 前言 SIESTA是材料计算常用软件。区别于VASP的平面波基底,SIESTA基于原子轨道基底,且是免费的。科学研究人员可以免费获得其源码及赝势文件。 作为刚入门材料计算的小白,在此贴出安装SIESTA的整个流程,希望能给后来者以指引。 本次安装基于CentOS7.4 版本。因为是安装在所里服务器集群上,所以没有root权限,无法使用yum指令,很多都只能下载-编译-安装。如果你是安装在自己的pc

  • Siesta概述 Siesta控件是一个JavaScript单元测试工具,可以助您测试任何Javascript代码和同样测试DOM和模拟用户交互.工具可以和任何javascript代码—jQuery,Ext JS,NodeJS,Dojo,YUI等等,一起使用.使用它,你可以从许多警告类型中选择你的警告,从简单逻辑JS对象比较到识别DOM中的HTML元素是否可见.有两个版本:轻量版和标准版.使用轻量

  • 1 siesta 背景介绍:(Spanish Initiative for Electronic Simulations with Thousands ofAtoms)是一种实现电子结构计算和第一性原理分子动力学模拟的程序,同时也是一种实现的方法。软件主要由剑桥大学地球科学系Emilio教授、西 班牙马德里Autónoma大学的Soler与其他大学的研究人员共同开发的。SIESTA最早于1997年

  • 【原创】并行编译SIESTA最近闲的无聊,在曙光集群上并行编译了SIESTA,把其中的过程和教训跟大家分享一下. 1.获得SIESTA SIESTA对科研人员是可以免费使用的,因此可以在主页上注册,大概两个星期后管理员会通过审核,通知您可以使用SIESTA.然后就可以从上面下载到源文件,赝势文件等。 2.编译器安装 我这里使用的FORTRAN编译器是PGI7.0,并行使用MPI-1.2.7. PG

  • Install siesta and transiesta (siesta-3.2-pl-5.tar.gz) on the HLRN-smp system 1)  load related modules module unload sw.mpp1 module load sw.smp1 module load  intel.studio/14.0.1.106 module load openmp

  • 编译能通过,但运行老是报错 mpirun noticed that process rank 34 with PID 24030 on node fn043 exited on signal 11 连tests里面的si64都报错,所以我觉得不是简单的内存问题。 下面是我的make文件,请高手指教一下出了什么问题?是ldau版的 .SUFFIXES: .SUFFIXES: .f .F .o .a

  • siesta-3.0-b 所属分类:Linux/Unix编程 开发工具:Fortran 文件大小:7509KB 下载次数:268 上传日期:2010-01-13 11:26:23 上 传 者:samuel 说明:  SIESTA用于分子和固体的电子结构计算和分子动力学模拟。SIESTA使用标准的Kohn-Sham自恰密度泛函方法,结合局域密度近似(LDA-LSD)或广义梯度近似(GGA)。计算使用

  • Siesta编译没有报错,但是一运行就出现如下错误forrtl: severe (174): SIGSEGV, segmentation fault occurred,求助高手怎么解决。下面是我的arch.make文件。不胜感激!! # .SUFFIXES: .SUFFIXES: .f .F .o .a .f90 .F90 SIESTA_ARCH=x86_64-unknown-linux-gnu-

  • 1:到Src目录下 ./configure 确定你的mpi可以用! 然后修改arch.make arch.make 修改之后的: # # This file is part of the SIESTA package. # # Copyright (c) Fundacion General Universidad Autonoma de Madrid: # E.Artacho, J.Gale, A

  • SIESTA-2.0安装 0 推荐 SIESTA是采用数值原子轨道基矢展开晶体的波函数,离子实与价电子之间的相互作用采用模守恒赝势来描述的,其突出之处实现了O(N)算法,可以用来进行大规模数值计算,比如模拟蛋白质分子等复杂结构材料体系。目前已开发至2.0版本。要获取该程序,先从http://www.uam.es/departamentos/ciencias/fismateriac/siesta/下

  • (原文地址:https://medium.freecodecamp.org/swift-networking-with-siesta-5b5e7089bd8f) 今天我跟大家分享一下我的 iOS 网络库新欢,名字叫做 Siesta。“她有啥特殊的?为啥我不直接用 Almofire?”你也许会问。事实上,你仍然可以把 Alamofire 和 Siesta 一起使用!它是客户端之上的网络抽象层。 和

  • (原文地址:https://medium.freecodecamp.o...) 今天我跟大家分享一下我的 iOS 网络库新欢,名字叫做 Siesta。“她有啥特殊的?为啥我不直接用 Almofire?”你也许会问。事实上,你仍然可以把 Alamofire 和 Siesta 一起使用!它是客户端之上的网络抽象层。 和 Moya 不同,Siesta 不会隐藏 HTTP。这种中间状态,是我使用 Sies

  • siesta swift by Nikolay Derkach 通过尼古拉·德卡赫(Nikolay Derkach) 让我向您介绍我最喜欢的图书馆Siesta的Swift联网。 (Let me introduce you to Swift networking with Siesta — my new favorite library.) Today I’d like to tell you ab

  • 杈撳嚭鐨勬枃浠舵槸杩欐牱鐨� DM.Energy.Tolerance 1.0d-5 eV DM.Require.Harris.Convergence .true. DM.Harris.Tolerance 1.0d-5 eV MD.TypeOfRun FC MD.FCDispl 0.04 Bohr ************************** End of input data file *

  • 杈撳嚭鐨勬枃浠舵槸杩欐牱鐨� DM.Energy.Tolerance 1.0d-5 eV DM.Require.Harris.Convergence .true. DM.Harris.Tolerance 1.0d-5 eV MD.TypeOfRun FC MD.FCDispl 0.04 Bohr ************************** End of input data file *

  • 过去几周时间里,趋势科技收到几份利用各种应用版本漏洞窃取各类组织信息的报告,与Safe行动相似,这些行动进行的非常隐蔽。并将攻击者精心策划的这起定向攻击称为Siesta行动,其目标为能源、金融、医疗保健、媒体通信及交通运输等等固定的产业。 随后fireeye对此活动展开更详细的分析,fireeye表示此活动和APT1有关联,他们发现二零一四年二月二十〇日针对客户在电信部门,利用鱼叉式网络钓鱼邮件,