UIProgressView with multiple asynchronous NSURLConnection in iOs - iphone

I am using following code to download file from url's asynchronously,
NSMutableData *responseData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://www.tuiscos.com/images/trading.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// do something with data
[responseData appendData:data];
myImage8.image = [UIImage imageWithData:data];
NSInteger len = response.expectedContentLength;
NSInteger receiverdBytes = 0;
receiverdBytes = data.length+ receiverdBytes;
float prog = (float)[responseData length]/(float)len;
[progress8 setProgress:prog];
}];
as the download progresses, I want to update the progress bar, but using this code, I am not getting a gradual progress, instead it is waiting to complete the download and jumping to the maximum value. How can I make a gradual progress in the value?
Can somebody provide a sample code? For asynchronous method with delegate methods.
Thanks :)

If you don't want to code everything on your own, I would suggest using ASIHTTPRequesst on this task:
http://allseeing-i.com/ASIHTTPRequest/How-to-use
It is very simple to implement and you can do simultaneous, asynchrony downloads. It also provides delegates for all needs, also for progress updates.
I used it in my projects for almost a year now and never regretted it.

CompletionHandler is executed at completion, of course. You have to a delegate for the connection. Use -initWithRequest:delegate: method. You will have to code the NSURLConnectionDelegate methods and the one you need to set progressView value is -connection:didReceiveData:
Here is the doc: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.pdf

Related

AFImageRequestOperation with SDWebImage issue

I use AFImageRequestOperation to download some icons, meanwhile use SDWebImage to download some pics for main view. Each AFImageRequestOperation is added to my publicOperationQueue defined in app delegate, its maxConcurrentOperationCount is set to 10. Strange thing is that sometimes one or two of my 10+ icons will be replaced by some pic in main view, which should be downloaded by SDWebImage. And when I set a larger maxConcurrentOperationCount which is bigger than my icon counts, it works fine. I doubt if it has something to do with multiple NSOperationQueues sharing some resources and maxConcurrentOperationCount. Any one could help?
//below is the icon downloading code
//============================//
for(NSString *url in picUrls)
{
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[urlRequest setHTTPShouldHandleCookies:NO];
[urlRequest addValue:#"image/*" forHTTPHeaderField:#"Accept"];
AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
NSString *imageName = trimNilOrNuLL([url lastPathComponent]);
if(imageName.length > 0)
{
NSData *imageData = UIImagePNGRepresentation(responseObject);
[imageData writeToFile:[path stringByAppendingPathComponent:imageName] atomically:YES];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(#"%#",error);
}];
[[AppShare appDelegate].publicOperationQueue addOperation:requestOperation];
}
//============================//
and for SDWebImage, I use - (void)setImageWithURL:(NSURL *)url method in UIImageView+WebCache category to download pic
OK,From the question found that you are using AFNetworking .Then for image downloading why dont you use the UIImageView Extention of AFNetworking?
You dont have to implement any queue or anything for this
some code like this is enough i think
[self.imageview setImageWithURL:url placeholderImage:nil];

iPhone objective c Asyncron HTTPS request in NSThread

I need a good solution for my little issue.
What I have at the moment:
My App works with asyncron https request very well. At the moment the app uploads an JSON object, so far so good. After that I save the object in an sqlite database.
Now I have to change to determine what the received server response code is.
I will get an response code like 000 if the uploaded data was valid, and a code like 151 if not. For that I have to wait for the server response to save the response code in the database as well.
I experimented with NSThread, too. But that didn't work out as well as I expected.
Somebody any suggestions? I mean, it should be one of the most common things ;) I just don't see it.
thx, dominik
I usually use an NSOperationQueue to manage my communication. This lets you use a synchronous request instead of asynchronous, and handle the whole shebang in one method.
Example:
-(void)doIt {
NSInvocationOperation *op = [[[NSInvocationOperation alloc] initWithTarget:self selector:#selector(doIt_) object:nil] autorelease];
[opQueue addOperation:op];
}
-(void)doIt_ {
NSData *data;
NSMutableURLRequest *request;
NSURLResponse *response = nil;
NSError *error = nil;
// Build request to spec
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
// do something with data
[self performSelectorOnMainThread:#selector(yadda) withObject:yaddayadda waitUntilDone:NO];
}
If you do use the asynchronous loading methods, you have to implement a delegate to catch the response data as it comes down, and do something with it when finished.
I recommend that you take a look at ASIHTTPRequest which is a wrapper for the CFNetwork API. Particularly look into the mechanism it offers for asynchronous HTTP requests, where you can define blocks to be executed once the request has completed or failed and can you can inspect the response data easily. Your code would be something like this:
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
// add your json object to the request
[request setCompletionBlock:^{
int responseCode = [request responseStatusCode];
NSData *responseData = [request responseData];
// do whatever you want with this info
}];
[request setFailedBlock:^{
NSError *error = [request error];
// handle the error
}];
[request startAsynchronous];

NSURLConnection sendSynchronousRequest - background to foreground

I m using sendSynchronousRequest to get the data from the server. I know that synchronous will wait until the data received for that request.
But the problem comes when user by mistake enters some non-existing url and than tries to get response. In this case, if user goes in to background and than comes into foreground it shows only black screen. It only shows status bar. Also its not showing any background application. I have to press Home button to come out of my application.
On simulator, After 1+ minute it shows me the message that "Request time out" (No crash).
On Device, within 1 min application get crashes.
Any suggestion. Any Help. This is really a serious issue in my app.
Thanks.
Just like Julien said, the watchdog is killing your app. To answer some questions:
why does this happen only on the simulator?
Because when you're debugging the watchdog leaves your app alone, it can take time.
why does this happen only when the user enters a wrong url?
Because of the system timeout, the system will keep trying for 60 secs if it can't find a server.
so the problem is synchronous vs asynchronous?
No, the problem is the thread, you can do the same operation in a background thread, just don't do it on the main thread and the watchdog will leave you alone.
why is the screen black when the app comes up?
Remember, you are making blocking stuff on the main thread, the thread that draws...
Hope that was all. Let me know if I missed something.
Why not setting a timeout for your connection?
NSString *urlString = TEST_CONNECTION;
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSURLRequest *request = [NSURLRequest
requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:5.0];
NSData *conn = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This should release the synchronous waiting after a number of seconds, which should solve your problem without going with an asynchronous call (which sometimes isn't the proper solution)
I know this works properly because this is how I check if I am connected to a certain VPN (where reachability flags totally fail).
you should take a look to this article: https://developer.apple.com/library/ios/#qa/qa1693/_index.html
iOs contains a watchdog, if your application is blocked to much time on an operation on the main thread, this one will be killed. (for more details about Watchdog: http://en.wikipedia.org/wiki/Watchdog_timer)
So if you want to download something, don't download it on the main thread.
RELATE
UIImage *image = [self.imgCache objectForKey:urlString];
if(!image){
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(#"%#",response);
UIImage *img = [UIImage imageWithData:data];
//
if(img)
{
dispatch_sync(dispatch_get_main_queue(), ^{
[self.imgCache setObject:img forKey:urlString];
completionBlock(img);
});
}
});
}
else{
completionBlock(image);
}
use ASIHttpRequest class instead of NSURLConnection , its nothing but wrapper around NSURLConnection and has very simple callbacks , you can also set time to complete a request. Please go through this link for more info http://allseeing-i.com/ASIHTTPRequest/
I think you first have to test user data whether it is correct or not and than only if it is correct, sends the request otherwise prompt user that "please enter correct data"...
or
when your parsing of data in response failed. You can also make protocol delegate method i.e FinishWithError so that you come up with your last UI.
Try this one:
#import "ASIHTTPRequest.h"
//In a method
[self performSelectorInBackground:#selector(DownLoadImageInBackground:) withObject:imgUrlArr];
-(void) DownLoadImageInBackground:(NSArray *)imgUrlArr1
{
NSURL * url = [Image URL];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}
-(void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(#"URL Fail : %#",request.url);
NSError *error = [request error];
// you can give here alert too..
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
UIImage *imgInBackground = [[UIImage alloc]
initWithData:responseData];
[imageView setImage: imgInBackground];
}
This might help you: I am also loading a number of images at one time, so images that have no proper data show a black screen. To avoid this, try to resize your imageview.
You could check the reachability of the URL before starting the request.
Apple has Reachability Methods to do so. But its easier to use a wrapper. E.g. ASIReachability.
I think the application crashing because you does not get any data when user enters wrong URL and you are using this 'returned' nil NSData to do stuffs.
I think this will fix your problem
NSData *data=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if(data!=nil){
///
} else {
NSLog(#"NO DATA");
}

dispatch_async memory problems in iOS

I have a loop of about 2000+ items I need to go through:
for (NSDictionary* dict in array) {
NSString *fileName = [NSString stringWithFormat:#"%#/%#_lg.jpg?t=",manufacturerID, [[dict valueForKey:#"ItemID"] stringByReplacingOccurrencesOfString:#" " withString:#"%20"]];
NSString *savePath = [documentsPath stringByAppendingPathComponent:fileName];
NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:kProductImagesURL, fileName]stringByAppendingString:lastImagesSyncDate]];
dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(aQueue, ^{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
int statusCode = [request responseStatusCode];
if (statusCode==200) {
NSData *responseData = [request responseData];
[responseData writeToFile:[savePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "] atomically:YES];
}
}
});
}
This works great and my main thread is not blocked but my memory goes through the roof - how do I get it to be released? Once the queue is empty it drops but I need it to clear out as it is going along.
Although you are running the code in the background you are running all of the code in the background at the same time. As fast you are able to loop through the array you are creating a new ASIHttpRequest that will be trying to download and save data at the same time. You may want to move your loop inside of the dispatch_async, or use an NSOperation that does the same thing but limit the max concurrent operations on the NSOperationQueue. If you move the loop inside of dispatch_async to do one at a time remember to create an NSAutoreleasePool locally and drain it periodically.
Instead of getting an autoreleased ASIHTTPRequest , try to alloc ,init , release one.
Haven't tried it , but think about alternating async and sync calls (to the same thread, not the main one) , like having 20 async requests followed by one sync.. this trick could help.

Loading Image into UIImageView using NSURLConnection

Hey all. I'm really new at this obj-c/xcode stuff. I'm trying to load the background of my xib file. To do this i'm using a UIImageView and populating that with an image I found from the net. the problem with that is that it's REALLY slow. Feels like it's crashing but it's not. I was told to use an NSURLConnection to fix the problem but don't know how. Here's the code i was using previously.
wallpaper.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://mysite.com/mobile/wallpaperR.asp?id=%i",customerID]]]];
How do i translate the above code into the NSURLConnection equivalent?
NSURLConnection will download the data in a new thread, so you app will feel much faster.
It is pretty easy to implement but it does require you to understand the concept of delegation.
I have a useful class I created to handle image downloads on separate threads, I will share the code with you, with comments to let you know what is going on:
AsyncImage.h
AsyncImage.m
If you need help implementing it just leave a comment and I can help you get it working, I remember this used to be pain for me too when I started developing.
You need to do parsing for this as you are using the webservice.Like this
-(void)startParsingForPhotoAlbumList:(NSString*)providerIdString
{
NSString *urlString = [NSString stringWithFormat:#"http://YourUrl/showalbumxml.php?id=%#&show=show",providerIdString];
NSURL *xmlURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
NSURLResponse *returnedResponse = nil;
NSError *returnedError = nil;
NSData *itemData = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
self.xmlParser = [[NSXMLParser alloc] initWithData:itemData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
and need to implement parser's delegate method as an example.
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
if ([[[resultArray objectAtIndex:1]objectForKey:#"Transaction"]isEqualToString:#"Myapp/snaps"])
{
[(LoginViewController *)obj getRegisterResult:resultArray];
}
}
Then in your Viewcontroller access the data,from parsing you need to pass objects,using array or dictionary.
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:itemImagePath]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
There is an example which may help:
NSURLConnection loading image example