How to queue up batch operations in AFNetworking 2.0 - afnetworking

I have this function which calls a GET method on AFHTTPRequestOperationManager:
var request:NSMutableURLRequest = ParseAPIClient.sharedClient.GET(className, parameters: parameters, success: { (operation:AFHTTPRequestOperation!, response:AnyObject!) -> Void in
if response.isKindOfClass(NSDictionary) {
self.writeJSONResponse(response, toDiskForClassWithName:className)
} else { NSLog("something happened") }
}, failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
NSLog("Request for class %# failed with error: %#", className, error)
})
This generates a request uses that request to create an AFHTTPRequestOperation. That operation is returned in that method along with a response to the request. The block passed into it writes the response to disk.
In my old AF1.x code, I would then use:
SDAFParseAPIClient.sharedClient.enqueueBatchOfHTTPRequestOperations:operations progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
} completionBlock:^(NSArray *operations) {
if (!toDelete) {
self.processJSONDataRecordsIntoCoreData
} else {
self.processJSONDataRecordsForDeletion
}
}];
method to take those operations created above and do something else afterwards. Iow, I would take the data written to disk and parse it with those self.processJSONDataRecords... methods.
Im not sure what would be the new equivalent?

The equivalent functionality in AFNetworking 2.0 is provided by AFURLConnectionOperation +batchOfRequestOperations:progressBlock:completionBlock:.
The difference here is that the developer is ultimately responsible for enqueuing the array of batched operations, using NSOperationQueue -addOperations:waitUntilFinished:.

Related

How to use the completion handler version of a async function in Swift?

I have a async function func doWork(id: String) async throws -> String. I want to call this function from a concurrent dispatch queue like this to test some things.
for i in 1...100 {
queue.async {
obj.doWork(id: "foo") { result, error in
...
}
}
}
I want to do this because queue.async { try await obj.doWork() } is not supported. I get an error:
Cannot pass function of type '#Sendable () async throws -> Void' to parameter expecting synchronous function type
But the compiler does not provide me with a completion handler version of doWork(id:). When I call it from Obj C, I am able to use the completion handler version: [obj doWorkWithId: #"foo" completionHandler:^(NSString * val, NSError * _Nullable error) { ... }]
How do I do something similar in Swift?
You can define a DispatchQueue. This DispatchQueue will wait for the previous task to complete before proceeding to the next. 
let queue = DispatchQueue(label: "queue")
func doWork(id: String) async -> String {
print("Do id \(id)")
return id
}
func doWorksConcurrently() {
for i in 0...100 {
queue.async {
Task.init {
await doWork(id: String(i))
}
}
}
}
doWorksConcurrently()
You are initiating an asynchronous task and immediately finishing the dispatch without waiting for doWork to finish. Thus the dispatch queue is redundant. One could do:
for i in 1...100 {
Task {
let results = try await obj.doWork(id: "foo")
...
}
}
Or, if you wanted to catch/display the errors:
for i in 1...100 {
Task {
do {
let results = try await obj.doWork(id: "foo")
...
} catch {
print(error)
throw error
}
}
}
Now, generally in Swift, we would want to remain within structured concurrency and use a task group. But if you are trying to mirror what you'll experience from Objective-C, the above should be sufficient.
Needless to say, if your Objective-C code is creating a queue solely for the purpose for calling the completion-handler rendition of doWork, then the queue is unnecessary there, too. But we cannot comment on that code without seeing it.

Writing Unit Test with asynchronous code in IOS

I need to test my Api calls response but before the block return Unit test got completed
how can i test my APIs
You can use XCTestExpectation for that.
XCTestExpectation *apiCallExpectation = [self expectationWithDescription:#"APICall"];
[apiService apiCall:^(BOOL success) {
XCTAssert(success);
[apiCallExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
[apiCallExpectation closeWithCompletionHandler:nil];
}];
At first, you don't need to call the actual API in unit testing, It shall to be independent and quicker to be completed. This shall be part of integration testing.
Regarding your question, I think you need to use Expectations, and Waiter. Check the following:
func testExample() {
let responseExpectation = expectation(description: "response")
// Your API Call shall be here
DispatchQueue.main.async {
// When you get the response, and want to finalize the expectation
responseExpectation.fulfill()
}
let result = XCTWaiter.wait(for: [responseExpectation], timeout: 15) // ex: 15 seconds to wait for the response for all expectations.
// result possible values are:
//all expectations were fulfilled before timeout.
.completed
//timed out before all of its expectations were fulfilled
.timedOut
//expectations were not fulfilled in the required order
.incorrectOrder
//an inverted expectation was fulfilled
.invertedFulfillment
//waiter was interrupted before completed or timedOut
.interrupted
}
Following is an example i am performing test case on a search api. you need to declare expectation and it will get fulfil once it's done.
func test_UpdateShowSearch_Result() {
let promise = expectation(description: "Status code: 200")
let searchAPI: SearchShowApi = SearchShowApi()
searchAPI.search(query: "") { (statusCode, tvShows ,error) in
if statusCode == 200 {
// reload table
promise.fulfill()
} else if (statusCode == 204){
// show no content
XCTFail("Status code: \(statusCode)")
}
else{
XCTFail("Error: \(String(describing:error?.localizedDescription))")
return
}
}
wait(for: [promise], timeout: 10)
}

iOS AFNetwork 3.0: Is there a faster way to send multiple API requests and wait until all of it is finished?

I am currently using the following method to send GET API requests. This method works, but I was wondering if there is a faster way. All I need regarding requirements is to know when all of the Deleted mail has been synced. Any tips or suggestions are appreciated.
- (void)syncDeletedMail:(NSArray *)array atIdx:(NSInteger)idx {
if (idx < array.count) {
NSInteger idNumber = array[idx];
[apiClient deleteMail:idNumber onSuccess:^(id result) {
[self syncDeletedMail:array atIdx:(idx + 1)];
} onFailure:^(NSError *error){
[self syncDeletedMail:array atIdx:(idx + 1)];
}];
} else {
NSLog(#"finished");
}
}
Edit: I don't care what order it is completed (not sure if it matters in terms of speed), as long as all the API requests come back completed.
You can just send deleteMail requests at once and use dispatch_group to know when all the requests are finished. Below is the implementation,
- (void)syncDeletedMail:(NSArray *)array {
dispatch_group_t serviceGroup = dispatch_group_create();
for (NSInteger* idNumber in array)
{
dispatch_group_enter(serviceGroup);
[apiClient deleteMail:idNumber onSuccess:^(id result) {
dispatch_group_leave(serviceGroup);
} onFailure:^(NSError *error){
dispatch_group_leave(serviceGroup);
}];
}
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
NSLog(#"All email are deleted!");
});
}
Here you can see all the requests are fired at the same time so it will reduce the time from n folds to 1.
Swift Version of #Kamran :
let group = DispatchGroup()
for model in self.cellModels {
group.enter()
HTTPAPI.call() { (result) in
// DO YOUR CHANGE
switch result {
...
}
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
// UPDATE UI or RELOAD TABLE VIEW etc.
// self.tableView.reloadData()
}
I suppose your request is due to the fact that you might have huge amounts of queued delete requests, not just five or ten of them.
In this case, I'd also try and consider adding a server side API call that allows you to delete more than just one item at a time, maybe up to ten or twenty, so that you could also reduce the overhead of the network traffic you'd be generating (a single GET isn't just sending the id of the item you are deleting but also a bunch of data that will basically sent on and on again for each and every call) by grouping the mails in batches.

Unit test case for call back methods ios

I have a following method in my app for which I need to write unit test cases.
Can anyone suggest how can I test whether the success block or error block is called.
- (IBAction)loginButtonTapped:(id)sender
{
void (^SuccessBlock)(id, NSDictionary*) = ^(id response, NSDictionary* headers) {
[self someMethod];
};
void (^ErrorBlock)(id, NSDictionary*, id) = ^(NSError* error, NSDictionary* headers, id response) {
// some code
};
[ServiceClass deleteWebService:#“http://someurl"
data:nil
withSuccessBlock:SuccessBlock
withErrorBlock:ErrorBlock];
}
You have to use expectations, a relatively recently introduced API. They were added to solve exactly the problem you are having right now, verifying callbacks of asynchronous methods are called.
Note that you can also set a timeout that will affect the result of the test (slow network connections for example can fire false positives, unless you are checking for slow connections of course, although there are much better ways to do that).
- (void)testThatCallbackIsCalled {
// Given
XCTestExpectation *expectation = [self expectationWithDescription:#"Expecting Callback"];
// When
void (^SuccessBlock)(id, NSDictionary*) = ^(id response, NSDictionary* headers) {
// Then
[self someMethod];
[expectation fulfill]; // This tells the test that your expectation was fulfilled i.e. the callback was called.
};
void (^ErrorBlock)(id, NSDictionary*, id) = ^(NSError* error, NSDictionary* headers, id response) {
// some code
};
[ServiceClass deleteWebService:#“http://someurl"
data:nil
withSuccessBlock:SuccessBlock
withErrorBlock:ErrorBlock];
};
// Here we set the timeout, play around to find what works best for your case to avoid false positives.
[self waitForExpectationsWithTimeout:2.0 handler:nil];
}

How one tests http requests in iOS 8?

In ruby I used to test http requests with vcr gem which recorded the request so the tests didn't send request to real host. Is there anything like this in iOS8 world?
The requests I want to test really need to be recorded since those requests may be outdated in some time and will return some other response
P.S. It would be great if it was some default Apple/iOS approach/library like XCTest for testing in general
What you want is something like OHHTTPStubs or Nocilla or AMY server. All of them essentially use NSURLProtocol to intercept your request and allow you to designate a response. We used OHHTTPStubs but pick the one with the feature set closest to your use case.
Here's an example of an OHHTTPStubs implementation in a unit test for a service that talks to a single REST endpoint:
NSString *loadRoomJSON = #{ #"key" : #"value" }; /* some JSON */
NSNumber identifier = #1;
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
NSString *url = [NSString stringWithFormat:#"v1/user/%#/room", identifier];
XCTAssert([request.URL.relativePath containsString:url], #"Expected certain URL");
return YES;
} andRespond:^OHHTTPStubsResponse *(NSURLRequest *request) {
return [OHHTTPStubsResponse responseWithJSONObject:loadRoomJSON statusCode:200 headers:nil];
}];
XCTestExpectation *loadPromise = [self expectation:#"Room loaded"];
[service loadRoomOnSucceed:^(Room *room) {
// Do your asserts here. For us, the JSON is mapped to an object
// so for example you could assert that the object is mapped correctly
[loadPromise fulfill];
} onFail:^(NSError *error) {
expect(error).to.beNil();
}];
[self waitForExpectationsWithTimeout:1.0 handler:^(NSError *error) {
expect(error).to.beNil();
}];
In reality our tests are shorter since we write wrapper/helpers to make it read better so this is an exploded-out version. Should give you the general idea. OHHTTPStubs (if you use it) has helper functions to load responses directly from files as well.
Im not sure if I understood you correct. But if I understand you right, you should be able to use XCTest to test your request and response.
class Tests:XCTestCase{
func testing(){
var expectation = self.expectationWithDescription("Your request")
var url = NSURL(string: "http://yourUrl.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if let httpRes = response as? NSHTTPURLResponse {
println("status code=",httpRes.statusCode)
//200 means OK
if httpRes.statusCode == 200 {
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
}else{
println("error \(error)")
}
}
}
}

Resources