Two Asynchronous NSURLRequests using Cocoa Touch - cocoa-touch

I am using the example shown here - listing's 1-5 to request the content of a URL and everything is working perfectly. Now my problem is, while the first request is sent off, I want to request content from a second web page, my problem is, even if I duplicate everything there for a second request and connection, and create another variable for NSMutableData that should hold the second request's data, I am only getting the second requests data filled into *receivedData (i.e. the original first requests NSMutableData)
Its like the moment I add code for a second request, only the second request is executing...
Does anyone know how to modify the code in the linked example so I can issue two separate requests?
Disclaimer: learning objective-C now, my background is C#/VB.

If you are using "self" as the delegate for both requests, then you'll be getting callbacks for both of the requests and you are most likely only writing the bytes into a single receivedData object. What you need to do is either create a new class to act as the delegate and create a new instance of the class for each request, or if you want to continue using "self" as the delegate make sure you take a look at the "connection" parameter passed into the delegate methods. That will indicate which connection the callback belongs to, allowing you to write the data to the appropriate receivedData object.

Related

Capture start of long running POST VB.net MVC4

I have a subroutine in my Controller
<HttpPost>
Sub Index(Id, varLotsOfData)
'Point B.
'By the time it gets here - all the data has been accepted by server.
What I would like to do it capture the Id of the inbound POST and mark, for example, a database record to say "Id xx is receiving data"
The POST receive can take a long time as there is lots of data.
When execution gets to point B I can mark the record "All data received".
Where can I place this type of "pre-POST completed" code?
I should add - we are receiving the POST data from clients that we do not control - that is, it is most likely a client's server sending the data - not a webbrowser client that we have served up from our webserver.
UPDATE: This is looking more complex than I had imagined.
I'm thinking that a possible solution would be to inspect the worker processes in IIS programatically. Via the IIS Manager you can do this for example - How to use IIS Manager to get Worker Processes (w3wp.exe) details information ?
From your description, you want to display on the client page that the method is executing and you can show also a loading gif, and when the execution completed, you will show a message to the user that the execution is completed.
The answer is simply: use SignalR
here you can find some references
Getting started with signalR 1.x and Mvc4
Creating your first SignalR hub MVC project
Hope this will help you
If I understand your goal correctly, it sounds like HttpRequest.GetBufferlessInputStream might be worth a look. It allows you to begin acting on incoming post data immediately and in "pieces" rather than waiting until the entire post has been received.
An excerpt from Microsoft's documentation:
...provides an alternative to using the InputStream propertywhich waits until the whole request has been received. In contrast, the GetBufferlessInputStream method returns the Stream object immediately. You can use the method to begin processing the entity body before the complete contents of the body have been received and asynchronously read the request entity in chunks. This method can be useful if the request is uploading a large file and you want to begin accessing the file contents before the upload is finished.
So you could grab the beginning of the post, and provided your client-facing page sends the ID towards the beginning of its transmission, you may be able to pull that out. Of course, this would be reading raw byte data which would need to be decoded so you could grab the inbound post's ID. There's also a buffered one that will allow the stream to be read in pieces but will also build a complete request object for processing once it has been completely received.
Create a custom action filter,
Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.
Specifically you'll want to look at the
OnActionExecuted – This method is called after a controller action is executed.
Here are a couple of links:
http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2016/03/04/how-to-create-a-custom-action-filter-in-asp-net-mvc.aspx
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-vb
Here is a lab, but I think it's C#
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters

AFNetworking get Parameters from Operation

I am attempting to get the parameters for a POST request sent via the AFNetworking pod. However, I can't seem to get them. I am looping through the active operations with the below:
for(AFHTTPRequestOperation* operation in manager.operationQueue.operations){
NSLog(#"%#",operation.request.URL.path);
}
However, I can't get the parameters. I've tried using operation.request.URL.parameterString, but since it is POST, the string is null. Anyone know how to get these? I'd like to collect them so that I can cancel requests that are specific to the path and parameters sent, ensuring I'll get down to just the single request I need to cancel.
I ended up going about this a different way. I created a class that handled all the AFNetworking path calls. In this class is a dictionary which stored an integer id for the call and the operation. As the operations complete or fail, they are removed. The integer id is passed back to the calling object, allowing for unique access for canceling requests or polling.

Return result of asynchronous call to the method the called it

I'm writing a standard NSURLConnection class for the App I'm working on right now which I will hopefully be able to use subsequent apps as well.
The idea is to able to pass a URL and a parameters array to a method in this class that will start the connection and then have it return the result when it is done.
-(NSData*)go :(NSString*)url :(NSArray)params
Since I'm calling this from another class I'd like to be able to set the result to a variable in that calling class.
NSData *result = [[connect alloc]go:testurl :testparams];
The problem is that the result doesn't arrive right away so when I return the NSData I have set in the "go" method it is blank.
I've tried a few things like NSCondition and running a while loop on another thread in the go method to check if it was finished.
Unfortunately, and I did not know this beforehand, the asynchronous connections form NSURLConnections run on the same thread as my NSCondition in the "go" method ran on. Because of this when I locked up that method so it didn't return early, I also locked up my connection so it never reached it's completion callback.
How can I effectively pause my "go" method long enough for my connection to finish so I can return the data to anywhere in my app.
There's a chance I'm going about this the completely wrong way so please let me know if that is the case. It does need to work kind of like this though because multiple requests will be going out at the same time and I'd like different instances of this connection class to be able to control them all.

How to get a complete request from a NSURLRequest?

Is there any way to get the actual data that will be sent when a NSURLConnection sends a NSURLRequest? Right now I'm mainly interested in looking at HTTP and HTTPS requests, but since NSURLRequest works for many protocols, it seems like there ought to be a general way to see the corresponding data for any type of request.
Am I missing something, or do I need to construct the request myself by combining the headers, body, etc?
Just to be clear, I'd like to do this programmatically, not by watching what shows up at the server end.
Update: At this point I've written code that effectively constructs a request using the data in a NSURLRequest, so I'm not asking how to go about that. However, I'd still like to know if there's a way to access the request stream that the URL loading system would generate. In other words, can I get access to the exact bytes that would be sent if a NSURLConnection were to send my NSURLRequest?
According your last question:
Check cookiesCenter.
Check credentialsStorage.
Log all headers for example on the first urlConnection's delegate method didReceiveResponse:.
Make this connection with local webservice and try to catch all headers, params, etc.
Also, the most simple way, is making request yourself.
Am I missing something, or do I need to construct the request myself
by combining the headers, body, etc?
It turns out that this is exactly what I needed to do, and it makes sense. It's the protocol handler (NSURLProtocol subclass), not NSURLRequest, that knows how to format the request for its particular protocol. Luckily, it's very easy to render an instance of NSURLRequest into a valid HTTP request. You can get the method (GET, POST, etc.), requested resource, and host from the request, and you can also get all the HTTP headers using the -allHTTPHeaderFields method, which returns a dictionary. You can then loop over the keys in the dictionary and add lines to the request like:
for (NSString *h in headers) {
[renderedRequest appendFormat:#"%#: %#\r\n", h, [headers objectForKey:h]];
}

How can I avoid data corruption with multiple instances of NSUrlConnection

I have written an iOS app that calls NSUrlConnection multiple times to download image data from the web. Sometimes, one NSUrlConnection has not finished before the other starts. I am seeing corrupt jpeg data and I think it is because my didReceiveData delegate is saving data from two separate NSUrlConnections and munging the two jpeg data streams together into one data variable, hence causing the corruption.
My question is: what is the best way to avoid this? There doesn't seem to be a way to make each NSUrlConnection instance save to a separate data variable, or make each instance wait until the previous instance is done before saving.
My code basically follows Apple's example here except I call a loadData function multiple times which creates the NSURLRequest and NSURLConnection. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
Thanks in advance for any help.
When your delegate's connection:didReceiveData: method is called, you'll have the connection instance as the first parameter. So you'll need to use that to keep track of which connection just received data.
Apple's sample maintains one instance of NSMutableData. Your code will require several instances, one for each active connection.
Or, of course, you could have a separate delegate object (an individual instance) for each connection. That may be easier.