UIActivityItemProvider -item method: waiting for NSURLConnection?
I have a subclass UIActivityItemProvider
that I need to provide NSURL
for UIActivityViewController
by doing the following:
- Uploading an image to my server
- Get url from server
- Provide this URL to your members.
In theory it seemed pretty straightforward: set up a method placeholderItem
to return a bogus NSURL, and then set up all the logic to handle the upload, etc. in the method item
.
The problem is that the method item
is a single synchronous method that is called on a background thread and has to handle all processing and return an item (in this case NSURL
) ... and the methods I need to use to handle the download are asynchronous (namely , I create NSURLConnection
with a subclass UIActivityItemProvider
as its delegate, respond to its delegate methods to update my interface with a progress bar, etc. but I can't just do it in the method item
because I can't let item
go back until my url ...
My attempt at a solution was for the method to item
start a url connection and then go into this loop:
while ((self.uploadedFileURL == nil) && (self.uploadErrorMessage == nil)) {
[NSThread sleepForTimeInterval:1.0f];
NSLog(@"Waiting for upload...");
}
and then I rely on various delegate methods NSURLConnection
to update progress, etc. In the methods of the delegate didFinishLoading
and didFailWithError
I emit values self.uploadedFileURL
and self.uploadErrorMessage
respectively.
But: It doesn't work. NSURLConnection
never fires a delegate method and I must assume for some reason that it is blocked. I get "Waiting to load ..." in the log every second as I expected, but nothing else happens.
What am I missing here?
update: I found a kind of solution, but less than ideal: using a synchronous request in a method -item
. The big drawback is that I cannot show a progress bar and there is no good network error handling. So ... Look for a better way.
source to share
OK, so I found a pretty good solution. The following method provides a pseudo-synchronous variant of the NSURLConnection methods:
https://gist.github.com/SQiShER/5009086
It is "pseudo-synchronous" in that the methods it provides return their values synchronously, but use asynchronous methods at the end. I'm sure this is really not a legitimate term, but that's all I have :)
In any case, the code in the link responds to some, but not all of the nsurlconnection delegation methods ... However, it's trivial to add more. If anyone sees this and wants more details please comment and I will take the time to formulate this answer.
source to share