Issues with progress tracking - AFNetworking queue - iphone

I have the following code for downloading two request using AFNetwork queue
NSMutableArray *operations = [NSMutableArray array];
NSURLRequest *request1 = [NSURLRequest requestWithURL:URL1];
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
operation1.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH1 append:NO];
[operation1 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
float progress = (float)totalBytesRead / totalBytesExpectedToRead;
NSLog(#"Progress 1 = %f",progress);
}];
[operations addObject:operation1];
NSURLRequest *request2 = [NSURLRequest requestWithURL:URL2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
operation2.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH2 append:NO];
[operation2 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
float progress = (float)totalBytesRead / totalBytesExpectedToRead;
NSLog(#"Progress 2 = %f",progress*100);
}];
[operations addObject:operation2];
Adding requests to AFTHTTPClient
AFHTTPClient *requestHandler = [[AFHTTPClient alloc] initWithBaseURL:BASEURL];
[requestHandler enqueueBatchOfHTTPRequestOperations:operations progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
NSLog(#"%d completed on %d",numberOfCompletedOperations,totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
}];
The problem is I get the progresses separate for each request. But I need the progress as a whole for both the requests combined.

Just create a global float to control this, and the total of all progress is:
TotalProgress = firstProgress/numOperations + secondProgress/numOperations
//Declare this like a global.
#define numOperation 2
float globalProgress = 0.0f;
//Your Operation Instances:
NSMutableArray *operations = [NSMutableArray array];
NSURLRequest *request1 = [NSURLRequest requestWithURL:URL1];
AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
operation1.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH1 append:NO];
[operation1 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
globalProgress += ((float)totalBytesRead / totalBytesExpectedToRead)/numOperation;
}];
[operations addObject:operation1];
NSURLRequest *request2 = [NSURLRequest requestWithURL:URL2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
operation2.outputStream = [NSOutputStream outputStreamToFileAtPath:PATH2 append:NO];
[operation2 setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
globalProgress += ((float)totalBytesRead / totalBytesExpectedToRead)/numOperation;
}];
[operations addObject:operation2];
Hope this help :)

Related

Thumbnail for youtube video

I am trying to create a thumbnail for youtube video,but me getting below error:-
Error Domain=AVFoundationErrorDomain Code=-11850 "Operation Stopped" UserInfo=0xa07ac00 NSLocalizedDescription=Operation Stopped, NSUnderlyingError=0xa07e580 "The operation couldn’t be completed. (OSStatus error -12939.)", NSLocalizedFailureReason=The server is not correctly configured.
Please help me out to create a thumbnail of youtube video from youtube link.
The Code am using to create thumbnail is as follows:-
NSURL *url = [NSURL URLWithString:strVideoURL];
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
{
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(#"couldn't generate thumbnail, error:%#", error);
}
// TODO Do something with the image
NSLog(#"CGImage---- %#", im);
UIImage *thumbnail=[UIImage imageWithCGImage:im];
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(30, 50, 120, 120)];
imageView.backgroundColor=[UIColor redColor];
imageView.image=thumbnail;
[image addSubview:imageView];
UIView *view=(UIView*)[self.view viewWithTag:10];
[view removeFromSuperview];
};
CGSize maxSize = CGSizeMake(128, 128);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];
Although your question doesn't have any source code of yours so i have no idea where have you gone wrong. Try this, its working for me.
#define YOUTUBE_URL #"https://gdata.youtube.com/feeds/api/videos?v=2&author=%#&orderby=published"
NSString *userName = #"ipl";
_url = [NSURL URLWithString:[NSString stringWithFormat:YOUTUBE_URL,userName]];
-(void) fetchYoutubeThumbnails {
NSURLRequest *_request = [[NSURLRequest alloc] initWithURL: _url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[recievedData appendData:data]; //recievedData is a class variable of type NSMutableData
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *xmlString = [[NSString alloc] initWithData:recievedData encoding:NSUTF8StringEncoding];
NSDictionary *result = [XMLReader dictionaryForXMLString:xmlString error:Nil];
if(result.count > 0) {
NSMutableArray *items = [[result objectForKey:#"feed"] objectForKey:#"entry"];
for(int i = items.count -1; i >= 0; i--) {
NSDictionary *item = [items objectAtIndex:i];
NSString *videoThumbnaulUrl = [[[[item valueForKey:#"media:group"] valueForKey:#"media:thumbnail"] objectAtIndex:0] valueForKey:#"url"];
// Use this url to get the thumbnail.
}
}

insert images to the device's cache - iOS

is there a way to insert images, that are downloaded from the web, to the devices cache?
in my application, there's a few views that contains images. at every tableView there's 25-30 images.
the problem is that the images are loaded when scrolled, and the result is at scrolling the image takes 2-3 seconds to reload... doesn't look good :)
at the moment, i'm using NSURLRequest at each cell.
NSURL* url = [NSURL URLWithString:article.articleImage];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error)
{
if (!error)
{
UIImage* image = [[UIImage alloc] initWithData:data];
MainImg.image = image;
article.articleImg=image;
}
}];
I've tried to use multi thread, but the launch of the application takes too long.
ideas?
Hi you need UIImageView+AFNetworking.h category download and use AFNetworking u are sorted
use its - (void)setImageWithURL:(NSURL *)url method works like charm
You can use NSURLCache for this purpose. Yesterday I've worked with this, and I make class:
#interface MyURLCache : NSURLCache
#property (nonatomic, assign) NSTimeInterval timeAvaiable;
#end
#implementation MyURLCache
- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
if(self){
_timeAvaiable = 5*60;//5 мин
}
return self;
}
- (id)init
{
self = [super init];
if(self){
_timeAvaiable = 5*60;
}
return self;
}
+ (NSCachedURLResponse*)addInfoDataToCachedResponce:(NSCachedURLResponse*)cachedResponse
{
NSMutableDictionary* newUserInfo = [#{#"LastUpdate" : #([[NSDate date] timeIntervalSince1970])} mutableCopy];
if([cachedResponse userInfo])
newUserInfo[#"UserInfo"] = [cachedResponse userInfo];
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
data:[cachedResponse data]
userInfo:newUserInfo
storagePolicy:[cachedResponse storagePolicy]];
}
+ (NSCachedURLResponse*)removeInfoDataFromCachedResponce:(NSCachedURLResponse*)cachedResponse
{
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
data:[cachedResponse data]
userInfo:[cachedResponse userInfo][#"UserInfo"]
storagePolicy:[cachedResponse storagePolicy]];
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSCachedURLResponse* result = [super cachedResponseForRequest:request];
NSDate* lastUpdate = [NSDate dateWithTimeIntervalSince1970:[result.userInfo[#"LastUpdate"] doubleValue]];
BOOL expired = fabs([lastUpdate timeIntervalSinceNow]) > _timeAvaiable;
return expired? nil : [[self class] removeInfoDataFromCachedResponce:result];
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
[super storeCachedResponse:[[self class] addInfoDataToCachedResponce:cachedResponse] forRequest:request];
}
#end
And just enable cache when app loaded:
MyURLCache *URLCache = [[MyURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:20 * 1024 * 1024
diskPath:[SDURLCache defaultCachePath]];
[NSURLCache setSharedURLCache:URLCache];
For each request need set cachePolicy to NSURLRequestReturnCacheDataElseLoad.
Or just use AFNetworking :)
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
In all my apps I'm using this framework. Very simple to use
https://github.com/rs/SDWebImage
Code example
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
];
Use This:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *savedImagePath = [NSString stringWithFormat:#"%#/%#",[paths objectAtIndex:0],[article.articleImage lastPathComponent]];
UIImage *image = [UIImage imageNamed:savedImagePath];
if(!image)
{
NSURL* url = [NSURL URLWithString:article.articleImage];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error)
{
if (!error)
{
[data writeToFile:savedImagePath atomically:NO];
UIImage* image = [UIImage imageNamed:savedImagePath];
MainImg.image = image;
article.articleImg=image;
}
}];
}
else
{
MainImg.image = image;
article.articleImg=image;
}

iPhone - NSURLConnection asynchronous download using URLs in NSArray

I have seen almost all the posts about NSURL on this site, and I am still stuck. I am using Xcode 4.5.
I am trying to download images and display them in a UIScrollView.
I want to download asynchronously download images using URLs, that get stored in an array populated using JSON. I get the URLs from a JSON grab off of my database. That works quite well and I can see the URL's being placed into the urlArray, but making the URLConnection to get the image, seems to fail.
I can't get any of the images to download, or at least they don't show up in my imageArray.
Here is my code and thank you for any help!! Let me know what else is needed
- (void)viewDidLoad
{
[super viewDidLoad];
//show network activity to user.... very useful
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//call getJSON. getJSON does not parse, but it connects and gets the data.
[self getJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getJSON
{
NSURL *url = [NSURL URLWithString:#"http://"My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//just initialize the connection, do not
[[NSURLConnection alloc] initWithRequest:request delegate:self]; //"Ecression result unused" warning here
}
- (void)getNextImage
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
imageData = [UIImage imageWithData:imgData];
[imageArray addObject:imageData];
}
NSLog(#"LEAVING getNextImage");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
theJsonData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[theJsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
jsonArray = [NSJSONSerialization JSONObjectWithData:theJsonData options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self getNextImage];
//display the images..... Not sure why this is in connectionDidFinishLoading.
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageData];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
NSLog(#"!!!!!!leaving connection did finnish loading!!!!!");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//show error message to user if there is a connection error.
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The Download could not complete - please make sure you're connected to the internet." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
//turn off the network activity indicatior
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you never download imageData. you assign it the request object . thats why you get the warning too. a NSURLConnection object is not a NSData object: NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
I would today rewrite it using the startAsyncConnection method. sec
-- there you go, untested and written in text edit but it should get you started (I reused most of your code but cut it down a lot too)
#import "RootViewController.h"
#interface RootViewController ()
#property(assign) IBOutlet UIScrollView *mainScroll;
#end
#implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self getJSONAndImageData];
}
- (void)getJSONAndImageData
{
NSURL *url = [NSURL URLWithString:#"http://My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*r, NSData*d, NSError*e) {
[self parseJSONAndGetImages:d];
}];
}
- (void)parseJSONAndGetImages:(NSData*)data
{
NSMutableArray *urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *jsonArray = (NSArray*)[NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here => likely not an array then
assert([jsonArray isKindOfClass:[NSArray class]]);
//could be made in one liner with KVC
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self loadImageArray:urlArray handler:^(NSArray* imageArray) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageArray[x]];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
}];
}
//for SIMPLICITY I do synchronous networking here!
- (void)loadImageArray:(NSArray *)urlArray handler:(void(^)())handler {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSMutableArray *imageArray = [NSMutableArray array];
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];
UIImage *image = [UIImage imageWithData:imgData];
[imageArray addObject:image];
}
dispatch_async(dispatch_get_main_queue(),^ {
handler(imageArray);
});
});
}
#end

AFNetworking check if image is cached

I have this method, which downloads full size image for UIImageView when clicked on cell.
- (void)configureView
{
NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:self.imageURL];
AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:URLRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[SVProgressHUD showSuccessWithStatus:#"Done!"];
[self.imageView setImage:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
float percentage = (totalBytesRead / (totalBytesExpectedToRead * 1.0f) * 100);
NSLog(#"Percentage: %f", percentage);
if (percentage != 100.0)
{
[SVProgressHUD showWithStatus:[NSString stringWithFormat:#"Downloading... %0.0f%%", percentage]];
}
}];
[operation start];
}
So when download completes, [SVProgressHUD showSuccessWithStatus:#"Done!"]; is called.
but when you go back to tableViewController and click on the same cell, [SVProgressHUD showSuccessWithStatus:#"Done!"]; is called again even though the image is cached.
How can I check if the image is cached and only call [SVProgressHUD showSuccessWithStatus:#"Done!"]; when it is not?
AFImageRequestOperation doesn't cache images. I think you are confusing AFNetworking's category "UIImageView+AFNetworking" with "AFImageRequestOperation". The category does cache images, AFImageRequestOperation does not.

How can we handle multiple NSURLConnection in iPhone Xcode?

I am developing one small app in which i have multiple NSURLConnection.I have created that NSURL Connection but i don't know how to handle it.My code is like below.
-(void) loadTrafficAndEvent {
int a=10;
//Get the map view bounds for fetch the travel time markers from web service
MKCoordinateRegion region = mapView.region;
float print = region.center.latitude;
// NSLog(#"region.center=%g",print);
CGPoint firstcorner = CGPointMake(self.mapView.bounds.origin.x , mapView.bounds.origin.y);
CGPoint secondcorner = CGPointMake((self.mapView.bounds.origin.x+mapView.bounds.size.width) , mapView.bounds.origin.y);
CGPoint thirdcorner = CGPointMake(self.mapView.bounds.origin.x , (mapView.bounds.origin.y+ mapView.bounds.size.height));
CGPoint fourthcorner = CGPointMake((self.mapView.bounds.origin.x+mapView.bounds.size.width), (mapView.bounds.origin.y + mapView.bounds.size.height));;
//Then transform those point into lat,lng values
CLLocationCoordinate2D mapfirstcorner,mapsecondcorner,mapthirdcorner,mapfourthcorner,requestsender;
mapfirstcorner = [mapView convertPoint:firstcorner toCoordinateFromView:mapView];
mapsecondcorner = [mapView convertPoint:secondcorner toCoordinateFromView:mapView];
mapthirdcorner = [mapView convertPoint:thirdcorner toCoordinateFromView:mapView];
mapfourthcorner = [mapView convertPoint:fourthcorner toCoordinateFromView:mapView];
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy"];
NSString *date = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
NSString *checksumString = [NSString stringWithFormat:#"TrafficAndEvents%#ForTravelStar", date];
NSString *md5Checksum = [self getMD5CheckSum:checksumString];
NSString *url = [NSString stringWithFormat:#"http://www.travelstar.nl/travelstarwebservice/ProviderServices.asmx/GetTrafficStatusAndEvent?northWestLatitude=%f&northWestLongitude=%f&southEastLatitude=%f&southEastLongitude=%f&zoomLevel=%d&date=%#&checksum=%#", mapfirstcorner.latitude,mapfirstcorner.longitude, self.mapView.region.center.latitude, self.mapView.region.center.longitude, a,date,md5Checksum];
NSString *url1 = [NSString stringWithFormat:#"http://www.travelstar.nl/travelstarwebservice/ProviderServices.asmx/GetTrafficStatusAndEvent?northWestLatitude=%f&northWestLongitude=%f&southEastLatitude=%f&southEastLongitude=%f&zoomLevel=%d&date=%#&checksum=%#", mapsecondcorner.latitude,mapsecondcorner.longitude, self.mapView.region.center.latitude, self.mapView.region.center.longitude, a,date,md5Checksum];
NSString *url2 = [NSString stringWithFormat:#"http://www.travelstar.nl/travelstarwebservice/ProviderServices.asmx/GetTrafficStatusAndEvent?northWestLatitude=%f&northWestLongitude=%f&southEastLatitude=%f&southEastLongitude=%f&zoomLevel=%d&date=%#&checksum=%#", mapthirdcorner.latitude,mapthirdcorner.longitude, self.mapView.region.center.latitude, self.mapView.region.center.longitude, a,date,md5Checksum];
NSString *url3 = [NSString stringWithFormat:#"http://www.travelstar.nl/travelstarwebservice/ProviderServices.asmx/GetTrafficStatusAndEvent?northWestLatitude=%f&northWestLongitude=%f&southEastLatitude=%f&southEastLongitude=%f&zoomLevel=%d&date=%#&checksum=%#", mapfourthcorner.latitude,mapfourthcorner.longitude, self.mapView.region.center.latitude, self.mapView.region.center.longitude, a,date,md5Checksum];
//Release the request if it is already created.
if(request1 ) {
[request release];
request = nil;
}
else if(request1 ) {
[request1 release];
request1 = nil;
}
else if(request2 ) {
[request2 release];
request2 = nil;
}
else if(request3 ) {
[request3 release];
request3 = nil;
}
//Release the connection if it is already created.
if(conn) {
[conn cancel];
[conn release];
conn = nil;
}
else if(conn1) {
[conn1 cancel];
[conn1 release];
conn1 = nil;
}
else if(conn2) {
[conn2 cancel];
[conn2 release];
conn2 = nil;
}
else if(conn3) {
[conn3 cancel];
[conn3 release];
conn3 = nil;
}
//If zoom level is grater then 6 then it will request for fetch the travel time markers from the web servce.
if(a > 6) {
ZOOM_LEVEL = a;
//Create the request for fetch the data from web service.
request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
request1 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url1]];
request2 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url2]];
request3 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url3]];
//NSLog(#"%#",url);
//NSLog(#"Request sent");
//entryDate = [NSDate date];
//[entryDate retain];
//Create the connection with the web service for fetch the data
// DownloadDelegate *dd = [[DownloadDelegate alloc] init];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
conn2 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
conn3 = [[NSURLConnection alloc] initWithRequest:request3 delegate:self];
}
}
Declare conn,conn1,conn2,conn3 in .h file.
Then do the following.
in loadTrafficAndEvent:
conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
in connectionDidFinishDownloading: method,
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL{
if(connection==conn){
conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
}
else if(connection==conn1){
conn2 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
}
else if(connection==conn2){
conn3 = [[NSURLConnection alloc] initWithRequest:request3 delegate:self];
}
}
Do the operations inside each if else condition, and no need to allocate and initialize all NSURLConnection in loadTrafficAndEvent: The download will occur one after other.
you might want to take a look at AFNetworking for an easier and tidier way of doing network requests.
Implement NSURLConnection delegate methods and rest will be handle by itself