简体   繁体   中英

Swift Siesta Framework: do something before sending requests

I am trying the Siesta framework and I want to call a function before sending every API calls.

I saw that decorateRequests(with:) is best suited for what I am looking to do, but as the return value must be a Request , there's an error on the following code:

service.decorateRequests(with: { (res, req) -> Request in
  if (res.url == self.tests.url) {
    // do things..., then call req.repeated()
  } else {
    req.repeated()
  }
})

However, I have this error: Missing return in a closure expected to return 'Request'

Any idea how I can make it work? Thanks

The basic Swift syntax error here is that you need to use the return keyword if a value-returning closure contains more than one statement.


If what you need to do is something that either:

  1. can synchronously block the main thread because it is brief (eg log the request, flip a test expectation), or
  2. needs to be started when the request is sent, but the request can go ahead and start immediately without waiting for it to finish

…then it needn't be complicated. Do your brief task while everyone waits, then return the request:

service.decorateRequests { req, res in
  if res.url == self.tests.url {
    doThatOtherThing()  // blocks the main thread, which is fine if it’s brief
  }
  return req
}

If on the other hand you need to do something that will take an indefinite amount of time while the main thread continues, and then at a later time initiate that request, then Siesta currently doesn't support that very well . You can do it by writing a custom implementation of the Request protocol, but that's laborious and error prone. A better approach is coming in a future version of Siesta.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM