AFImageRequestOperation with SDWebImage issue - iphone

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];

Related

Taking time to load the image from URL to UIImageview

I am using this code for displaying the image from URL to UIImageview
UIImageView *myview=[[UIImageView alloc]init];
myview.frame = CGRectMake(50, 50, 320, 480);
NSURL *imgURL=[[NSURL alloc]initWithString:#"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];
NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];
UIImage *image=[[UIImage alloc]initWithData:imgdata];
myview.image=image;
[self.view addSubview:myview];
But the problem is that its taking too long time to display the image in imageview.
Please help me...
Is there any method to fast the process...
Instead of dispatch_async, Use SDWebImage for caching the images.
This is best I have seen...
The problem of dispatch_async is that if you lost focus from image, it will load again. However SDWebImage, Caches the image and it wont reload again.
The answers given to me on my own question Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block does makes sense.So be sure that if you use [NSData dataWithContentsOfURL:URL] inside the GCD(as many developers do these days) is not a great idea to download the files/images.So i am leaning towards the below approach(you can either use NSOperationQueue).
Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.
As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code
EDIT:
Example on [NSURLConnection sendAsynchronousRequest:queue:completionHandler:
NSURL *url = [NSURL URLWithString:#"your_URL"];
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//doSomething With The data
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//time out error
else if (error != nil)
//download error
}];
Use Dispatch queue to load image from URL.
dispatch_async(dispatch_get_main_queue(), ^{
});
Or add a placeholder image till your image gets load from URL.

Downloading and saving an image from link in UIWebView

I am trying to save an image to the photo library from a website which is opened in an uiwebview.The link is not just an image link where NSURLConnection can be used to download.I want to achieve the download by long pressing the image in UIWebView just as it can be done in safari. How can i achieve this..is it possible??
NSURL *url = [NSURL URLWithString:link];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
the response string contains complete information
Sorry to ask, but why do you use an UIWebView to only load an image. The UIImageView class constructor imageWithContentsOfURL: would do the job perfect.
Then you can just use an UIPopoverController for presenting a UIViewController with an UIButton calling UIImageWriteToSavedPhotosAlbum (http://goo.gl/uAJYS) to save the UIImage from your UIImageView directly into the users camera roll.
For Optimisation use an UITableViewController instead of the UIViewController - more the default iOS look&feel - and present the UIPopoverController with a small delay by overwriting the UIResponder methods on the UIImageView.
// EDIT: If you really mean how to get the exact behaviour of the Safari to save any image in the dom tree, i am a bit stumped. Maybe someone else can contribute some information on that.

threads is exiting my app

I'm trying to upload images to a php file, everything works, but sometimes when the site is
getting slow to load our app start frizzing until the page is done loading so i thought
about using threads to avoid such frizzing, but right now our app display and quit. I dont
see any warnings or problem... it just enter the app and exist right away. Please help me
out
the code:
-(void) source {
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 80);
NSString *urlString = #"http://domain";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
our_label.text = [NSString stringWithFormat:#"%#", returnString];
}
-(void)som:(id)param{
[lock lock];
[lock unlock];
}
You can use the NSURLRequest in an asynch method, however if you want your current code to work follow these insturctions
First change this line
[NSThread detachNewThreadSelector:#selector(multithreading:) toTarget: [MainViewController class] withObject:nil];
to
[NSThread detachNewThreadSelector:#selector(multithreading:) toTarget:self withObject:nil];
Second, you are updating the UI in a non UI thread, so wrap this
our_label.text = [NSString stringWithFormat:#"%#", returnString];
around dispatch_get_main_queue like the following
dispatch_async(dispatch_get_main_queue(), ^{
our_label.text = [NSString stringWithFormat:#"%#", returnString];
});
Finally remove the locks since you are not really using them
//[lock lock];
[self source];
//[lock unlock];
Totally wrong approach. Look carefully at the documentation of NSURLConnection, and you will find the method sendAsynchronousRequest:queue:completionHandler:.
You will need to learn using blocks though (but it is worth it).
In addition to yan.kun's answer,
I suggest you to use third party library such as AFNetworking which has all the functionality to deal with Async operation which will be more easy to code and safe.
link : https://github.com/AFNetworking/AFNetworking/

UIProgressView with multiple asynchronous NSURLConnection in iOs

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

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