AFNetworking - re-trying until API responds correctly - ios

I'm using an API which returns a key "status" which can either be "completed" or "not completed". I have to to keep asking it until it is "completed". I want to be able to keep requesting the response until I get:
{
"status": "completed"
}
Is there a way to do this with AFNetworking? Where I can set a maximum number of requests, and a time interval between requests.

I don't believe so. You will need to maintain your own timer to trigger the checks and invalidate the timer once the success status you're waiting for is seen.

Related

Deleted Scheduled Messages still sending

I am building a slack application that will schedule a message when someone posts a specific type of workflow in a channel.
It will schedule a message, and if someone from a specific group of users replies before it has sent, it will delete the scheduled message.
Unfortuantely these messages are still sending, even though the list of scheduled messages is empty and the response when deleting the message is a successful one. I am also deleting the message within the 60 second limit that is noted on the API.
Scheduling the message gives me a success response, and if I use the list scheduled messages I get:
[
{
id: 'MESSAGE_ID',
channel_id: 'CHANNEL_ID',
post_at: 1620428096, // 2 minutes in the future for testing
date_created: 1620428026,
text: 'thread_ts: 1620428024.001300'
}
]
Canceling the message:
async function cancelScheduledMessage(scheduled_message_id) {
const response = await slackApi.post("/chat.deleteScheduledMessage", {
channel: SLACK_CHANNEL,
scheduled_message_id
})
return response.data
}
response.data returns { "ok": true }
If I use the list scheduled message API to retrieve what is scheduled I get an empty array []
However, the message will still send to the thread.
Is there something I am missing? I have the proper scopes set up and the API calls appear to be working.
If it helps, I am using AWS Lambda, and DynamoDB to store/retrieve the thread_ts and message IDs.
Thanks all.
For messages due in 5 minutes or less, chat.deleteScheduleMessage has a bug (as of November 2021) [1]. Although this API call may return OK, the actual message will still be delivered due to the bug.
Note that for messages within 60 seconds, this API does return an proper error code, as described in the documentation [2]. For the range (60 seconds, ~5 minutes), the API call returns OK but fails behind the scenes.
Before this bug is fixed, the only thing one can do is to only delete messages scheduled 5 minutes (the exact threshold may vary, according to Slack) or more (yes not very ideal and may not be feasible for some applications).
[1] Private communication with Slack support.
[2] https://api.slack.com/methods/chat.deleteScheduledMessage

How Can I set timeout interval when use bluetooth

When I use bluetooth to write data, I hope get response. But when the peripheral goes wrong, it doesn't send notification. I need set a timeout interval to handle this bad interaction. Like we use urlrequest:
/// Creates and initializes a URLRequest with the given URL and cache policy.
/// - parameter: url The URL for the request.
/// - parameter: cachePolicy The cache policy for the request. Defaults to `.useProtocolCachePolicy`
/// - parameter: timeoutInterval The timeout interval for the request. See the commentary for the `timeoutInterval` for more information on timeout intervals. Defaults to 60.0
public init(url: URL, cachePolicy: CachePolicy = .useProtocolCachePolicy, timeoutInterval: TimeInterval = 60.0) {
_handle = _MutableHandle(adoptingReference: NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval))
}
How could I make it.
By "when the peripheral goes wrong" - if you mean that the peripheral crashes or stops working then you should get a BLE disconnection event to indicate the crash:
(centralManager:didDisconnectPeripheral:)
If this is not the case and you just stop receiving notifications after some time and the BLE connection is still alive, then there is no way to tell why the peripheral stopped sending notifications. The reason for this is that there is no specific "time" associated with notifications. Some peripherals send notifications every 1 second and some send notifications every 1 week. Some peripherals send notifications on a value change (e.g. if the temperature increases by 1 degree) and some send notifications on a user action (e.g. the user pressed a button).
The only workaround for this is if you add a timer in your central device, then every time you receive a notification using:
peripheral(_:didUpdateValueFor:error:)
you can reset that timer (if it is the exact notifications you're expecting to timeout). Then if the timer expires, you know that you did not receive your notification on time as expected and therefore you can flag an error or force a disconnection. This is just one example and there are a few variations of this that you can create (e.g. set a flag on peripheral(_:didUpdateValueFor:error:) that you check and reset every 30 seconds). You can find more information about timers in the links below:-
The ultimate guide to timer
Timer: Apple Developer Documentation
iOS Timer Tutorial
I hope this helps.
This is an interesting question.
After checking CoreBluetooth, i figured out that there's already an timeout Error in their list .
https://developer.apple.com/documentation/corebluetooth/cberror/2325746-connectiontimeout
But It's only works for the first time connect to peripheral.
So I think that, if you send a request, but you don't get any response, you have to make your own timer manager.
The concept for timeout is quite complicated. You need make a queue for timer, It's FIFO. You need an uniqueId for each request and you have to map it with your expected response.
Ex :
You call :
Call to get health info via BLE (any thread).
Call to get height info via BLE (any thread).
Call to get health info via BLE (any thread).
Your response :
height info.
health info.
After mapping your request with your response, you will notice that there's one expected response is missing. So how to know the request 1 or request 3 is missing response. It's your choice.
In conclusion, I think that you need a queue request and a queue expected response and a queue for timer. To manage these queue is not really a very big problem.

How to end a twilio call prematurely

I want to use twilio to test our internal phone system, and make sure calls are routing as they should, since our provider is notoriously bad of notifying us to problems.
I'm can initiate a call from twilio, use the "gather" verb to record speech (to ensure we hit the right queue) and then hang up. Everything works fine. Except that the gather ends up taking over 2 minutes to listen to the whole message from our phone system, charging us for 8 15 second gather chunks. I only need the first 15 seconds, but can't figure out how to hangup sooner. Is there a simple way to limit calls to a specific time?
timeLimit, and timeout both don't apply here, since timeLimit only works inside of a dial verb, and timeout only works for pauses in speech during the gather.
Perhaps just set a timer in your code for 15 seconds or so and then use the POST endpoint at /2010-04-01/Accounts/{AccountSid}/Calls/{CallSid} to cancel the call (using the Status=Completed parameter in order to cancel calls even if they are in progress).
If you use their Ruby SDK, and you make a normal call (not a conference call) then you can use the update method:
client = Twilio::REST::Client.new(account_sid, auth_token)
# fetch all in-progress calls between the two numbers
client.calls.list(from: '+11231231234',
to: '+12312311234',
status: 'in-progress').each do |c| #it's supposed to be just one record, but you can play it safe
c.update(status: 'completed')
end
Updating the status to completed should hangup the call if in-progress.
Updating the status to canceled should hangup the call if ringing/queued.
If you know for sure that the call is in-progress and you know the call sid, then you can use:
client = Twilio::REST::Client.new(account_sid, auth_token)
in_progress_call = client.calls(call_sid).fetch
in_progress_call.update(status: 'completed') if in_progress_call.present?
There is some general information in the official docs. Also snippets are available for the other SDKs.
You can find the source code of the update method here for more details.

Pattern for retrying URLSession dataTask?

I'm fairly new to iOS/Swift development and I'm working on an app that makes several requests to a REST API. Here's a sample of one of those calls which retrieves "messages":
func getMessages() {
let endpoint = "/api/outgoingMessages"
let parameters: [String: Any] = [
"limit" : 100,
"sortOrder" : "ASC"
]
guard let url = createURLWithComponents(endpoint: endpoint, parameters: parameters) else {
print("Failed to create URL!")
return
}
do {
var request = try URLRequest(url: url, method: .get)
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
if let error = error {
print("Request failed with error: \(error)")
// TODO: retry failed request
} else if let data = data, let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
// process data here
} else {
// TODO: retry failed request
}
}
}
task.resume()
} catch {
print("Failed to construct URL: \(error)")
}
}
Of course, it's possible for this request to fail for a number of different reasons (server is unreachable, request timed out, server returns something other than 200, etc). If my request fails, I'd like to have the ability to retry it, perhaps even with a delay before the next attempt. I didn't see any guidance on this scenario in Apple's documentation but I found a couple of related discussions on SO. Unfortunately, both of those were a few years old and in Objective-C which I've never worked with. Are there any common patterns or implementations for doing something like this in Swift?
This question is airing on the side of opinion-based, and is rather broad, but I bet most are similar, so here goes.
For data updates that trigger UI changes:
(e.g. a table populated with data, or images loading) the general rule of thumb is to notify the user in a non-obstructing way, like so:
And then have a pull-to-refresh control or a refresh button.
For background data updates that don't impact the user's actions or behavior:
You could easily add a retry counter into your request result depending on the code - but I'd be careful with this one and build out some more intelligent logic. For example, given the following status codes, you might want to handle things differently:
5xx: Something is wrong with your server. You may want to delay the retry for 30s or a minute, but if it happens 3 or 4 times, you're going to want to stop hammering your back end.
401: The authenticated user may no longer be authorized to call your API. You're not going to want to retry this at all; instead, you'd probably want to log the user out so the next time they use your app they're prompted to re-authenticate.
Network time-out/lost connection: Retrying is irrelevant until connection is re-established. You could write some logic around your reachability handler to queue background requests for actioning the next time network connectivity is available.
And finally, as we touched on in the comments, you might want to look at notification-driven background app refreshing. This is where instead of polling your server for changes, you can send a notification to tell the app to update itself even when it's not running in the foreground. If you're clever enough, you can have your server repeat notifications to your app until the app has confirmed receipt - this solves for connectivity failures and a myriad of other server response error codes in a consistent way.
I'd categorize three methods for handling retry:
Reachability Retry
Reachability is a fancy way of saying "let me know when network connection has changed". Apple has some snippets for this, but they aren't fun to look at — my recommendation is to use something like Ashley Mill's Reachability replacement.
In addition to Reachability, Apple provides a waitsForConnectivity (iOS 11+) property that you can set on the URLSession configuration. By setting it, you are alerted via the URLSessionDataDelegate when a task is waiting for a network connection. You could use that opportunity to enable an offline mode or display something to the user.
Manual Retry
Let the user decide when to retry the request. I'd say this is most commonly implemented using a "pull to refresh" gesture/UI.
Timed/Auto Retry
Wait for a few second and try again.
Apple's Combine framework provides a convenient way to retry failed network requests. See Processing URL Session Data Task Results with Combine
From Apple Docs: Life Cycle of a URL Session (deprecated)... your app should not retry [a request] immediately, however. Instead, it should use reachability APIs to determine whether the server is reachable, and should make a new request only when it receives a notification that reachability has changed.

How to guarantee the correct order in async request

I have a iOS application that use Alamofire to make URL requests. I sometimes find the requests arriving in the wrong order when there is very little time between them. This has to do with the nature of async requests as I understand. Is there any way to guarantee the correct order of the requests? I've been thinking you could wait for each request to finish because you have a completion handler or maybe you could handle this at the server side with a timestamp on each request so the server can discard requests that has a lower timestamp. I don't know what's the best solution though.
My code so far:
Alamofire.request(
defaults.string(forKey: "APIurl")! + path,
method: httpMethod,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
// Check if the request was successful
var success = false
if (response.result.isSuccess) {
let statusCode = response.response!.statusCode
if (statusCode == 200) {
success = true
} else {
showAlert("COULD_NOT_COMPLETE_TASK_TITLE", message: "TRY_AGAIN_LATER")
}
}
}
I use sliders to change a value between 0 and 100. So in my case the order of the requests are crucial. Let's say I change a slider from 50 to 60. With async requests it sometimes execute first 60 and then 50. This is an issue as it's sent to my API that way and saves the latest value (in this case 50) in the database even though my desired value was 60.
If the thread is serial which in your case it is then the order will always be the same as you input it. So calling a few operations asynchronously on a same serial thread will force the operations to preserve that order.
The problem in your case is that you are not calling these operations, Alamofire is calling them. The order is preserved but it depends on when the responses are received and parsed. That means you may have no control over the order of the async operations being called.
You have 2 ways of serializing responses:
You need to wait for each response to be completed before you call the next request. If your responses are standard (all look alike) you only need some manager that will store an array of requests and will not call the new one until the previous one is completed. This might be a bit slow since there is no reason (or at least it seems that way in your case) not to perform the requests at the same time.
Serialize the responses so they are called in the same order as input. This means you call the requests whenever and responses will be called whenever. But once the response is received you will check for other responses being complete and only if they are you will trigger a callback on this one. That would again mean having some manager that serializes there responses.
So for the second one you would need something like:
SerializedRequestManager.performRequest(request, myCallbackClosure)
The manager would then save the request into some array of request wrappers like:
let requestWrapper = RequestWrapper(request, myCallbackClosure, isCompleted: false)
self.requestPool.append(requestWrapper)
AF.performRequest(request, myInternalClosure)
Then on response (myInternalClosure) you need to set the correct wrapper to have response to true and then flush the responses from the start of the array. All the responses finished then must be removed from the array:
requestWrapper.responseData = data // Same wrapper that was just added into the array
requestWrapper.responseError = error // Same wrapper that was just added into the array
requestWrapper.isCompleted = true
self.flushResponses()
So then flushResponses:
var newPool = [RequestWrapper]() // This is where all the pending items will stay
var shouldFlushResponse = true // Will be set to false with first request that was not completed
self.requestPool.forEach { wrapper in
if wrapper.isCompleted && shouldFlushResponse {
wrapper.callback(wrapper.responseData, wrapper.responseError) // perform response closure
} else {
shouldFlushResponse = false
newPool.append(wrapper)
}
}
self.requestPool = newPool
But you need to be very careful about the multithreading here. All the operation on the array requestPool should be done on the same thread but it may be any thread you want.
Well if the order of requests in crucial in your case then you should go for the NSOperationQueue that is the only way to make sure the order of your requests.
Follow this tutorial to have a border idea

Resources