In my application i need to download pdf file from url.i know how to download pdf file from url and store in local document directory.But i need to show downloading process and i want to know whether download is completed.Please any body give an idea..
Here My code:
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.msy.com.au/Parts/PARTS.pdf"]];
//Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
Use ASIHTTPRequest for download file. for below code I had used ASIHTTPRequest
float currentProgress;
UILabel *dwnLbl;
UIProgressView * myProgressIndicator;
UIProgressView *progressBar;
#property (nonatomic, retain) ASIHTTPRequest *rqstForAudio;
-(void)viewDidLoad{
self.av=[[UIAlertView alloc] initWithTitle:#"Downloading.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[self.actV setFrame:CGRectMake(125, 60, 37, 37)];
dwnLbl = [[UILabel alloc] initWithFrame:CGRectMake(45, 30, 200, 37)];
dwnLbl.textAlignment = UITextAlignmentCenter;
dwnLbl.font = [UIFont boldSystemFontOfSize:20];
dwnLbl.backgroundColor = [UIColor clearColor];
dwnLbl.textColor = [UIColor whiteColor];
progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressBar setFrame:CGRectMake(45, 65, 200, 20)];
progressBar.progress = 0;
[self.av addSubview:dwnLbl];
[self.av addSubview:progressBar];
}
-(void)downLoadBook{
NSString *strAudioURL=#"http://www.msy.com.au/Parts/PARTS.pdf"
// check first locally exists or not
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#/%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
AudioFolder];
NSDictionary *dOfAudios=[NSDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios valueForKey:strAudioURL]) {
} else {
self.av.title = #"Downloading..";
[self.av show];
NSString *pdf = #"bookTitle.pdf";
NSURL *audioURL = [NSURL URLWithString:strAudioURL];
NSString *strPathToDownload=[NSString stringWithFormat:#"%#/%#",[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],pdf];
[self.rqstForAudio setDownloadProgressDelegate:myProgressIndicator];
if(!self.rqstForAudio || [self.rqstForAudio isFinished]) {
self.rqstForAudio=[ASIHTTPRequest requestWithURL:audioURL];
[self.rqstForAudio setDelegate:self];
[self.rqstForAudio setDownloadProgressDelegate:self];
[self.rqstForAudio setAllowResumeForFileDownloads:YES];
[self.rqstForAudio setCachePolicy:ASIUseDefaultCachePolicy];
[self.rqstForAudio setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[self.rqstForAudio setDidFailSelector:#selector(failedToLoad:)];
[self.rqstForAudio setDidFinishSelector:#selector(finishedLoading:)];
[self.rqstForAudio setDownloadCache:[ASIDownloadCache sharedCache]];
[self.rqstForAudio setDownloadDestinationPath:strPathToDownload];
[self.rqstForAudio startAsynchronous];
}
}
}
- (void)failedToLoad:(ASIHTTPRequest*)request {
[self.av dismissWithClickedButtonIndex:0 animated:YES];
NSLog(#"failed to download");
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"MESSAGE" message:#"Failed to Download" delegate:self cancelButtonTitle:RETRY otherButtonTitles:nil, nil];
av.delegate = self;
[av show];
}
- (void)finishedLoading:(ASIHTTPRequest*)request {
NSLog(#"finished loading");
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios allKeys].count>0) {
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
} else {
dOfAudios=[NSMutableDictionary dictionary];
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
}
[self.av dismissWithClickedButtonIndex:0 animated:YES];
[dOfAudios writeToFile:strPathToAudioCache atomically:YES];
}
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes{
[self setProgress:[myProgressIndicator progress]];
}
- (void)setProgress:(float)progress
{
currentProgress = progress;
if (!progress == 0.0) {
}
if(currentProgress*100 == 100.00){
self.av.title = #"Finishing..";
}
progressBar.progress = currentProgress;
dwnLbl.text = [NSString stringWithFormat:#"%.2f%%",currentProgress*100];
}
EDIT
You can used the NSURLSession method to implement such scenario
NSURLSession
I'd highly recommend taking a look at ASIHTTPRequest for easy file downloading.
where the numbers of the functionality thru you can able to use the download progress.
Related
How to download multiple images and save it to the disk.
The Send request i'm using is below.
for(NSDictionary *image in [data objectForKey:#"Catalogues"])
{
NSString *imurl =[image objectForKey:#"Image_Path"];
NSLog(#"%#",imurl);
NSString *urlstring =imurl;
NSLog(#"demo %#",urlstring);
NSURL *mailurl =[NSURL URLWithString:urlstring];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:mailurl];
NSOperationQueue *ques =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:ques completionHandler:^(NSURLResponse *respo, NSData *data, NSError *err) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 150, 150)];
im.image = image;
[self.view addSubview:im];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",documentsDirectory]
any native methods available for multiple images?
you can implement an AsyncImage class like this
in AsyncImage.h file
#import <UIKit/UIKit.h>
#interface AsyncImage : UIView
{
NSURLConnection* connection;
NSMutableData* data;
UIImageView *image;
UIActivityIndicatorView *scrollingWheel;
NSString *imgName;
}
-(void)loadImageFromString:(NSString*)url;
-(void)loadImageFromURL:(NSURL*)url;
-(void)setLocalImage:(UIImage *)localImage;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
#end
in AsyncImage.m file
#import "AsyncImage.h"
#implementation AsyncImage
-(id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
[self addSubview:scrollingWheel];
self.clipsToBounds = YES;
}
return self;
}
-(void)loadImageFromString:(NSString*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
imgName = [[[url componentsSeparatedByString:#"/"] lastObject]retain];
// NSLog(#"imgName=%#",imgName);
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
// NSLog(#"imagePath=%#",imagePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)setLocalImage:(UIImage *)localImage
{
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
image = [[[UIImageView alloc] initWithImage:localImage] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
}
//for URL
-(void)loadImageFromURL:(NSURL*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
NSString *strurl=[NSString stringWithFormat:#"%#",url];
imgName = [[[strurl componentsSeparatedByString:#"/"] lastObject]retain];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj
{
[data appendData:dataObj];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[connection release];
connection=nil;
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
[data writeToFile:imagePath atomically:YES];
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)dealloc
{
[scrollingWheel release];
[super dealloc];
}
-(NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection
{
if (connection !=nil) {
[connection cancel];
connection=nil;
}
if(data!=nil){
[data release];
data=nil;
}
[scrollingWheel stopAnimating];
}
#end
and at your viewController.m you can import this class and call it like this
AsyncImage *imgBOD = [[AsyncImage alloc] initWithFrame:CGRectMake(10, 46, 70, 70)];
[imgBOD loadImageFromString:[dictData objectForKey:#"image_path"]];
[self.view addSubview:imgBOD];
There is no "native method" for this particular problem.
If you just want to save a list of images to disk, you can improve your approach by not creating UIImages in the first place, just treat the data as binary data and save to disk directly.
In order to maintain low memory foot-print, implement NSURLConnection's delegate methods, and write (append) the image data piece-wise to the destination file as the chunk data arrives in connection:didReceiveData:.
The latter will be best solved by creating a dedicated class which encapsulates NSURLConnection and other related states and is subclassed from NSOperation and employs the asynchronous style implementing NSURLConnection delegates.
You might consider a third party library, too. A warning though: almost all well-known third party network libraries will not let you easily write data in pieces to a file. Per default, they accumulate all received data into one NSMutableData object. That may increase your memory-foot print, since images may be large, and since you can start multiple connections at once.
Also, don't start more than two connections at once.
when the purchase is completed in my app, i am downloading the images from server to the application.
I am able to download a image from online and i write inside iPhone using asihttprequest.
i have checked inside the iphone's simulator documents directory , the downloaded file is exist.
how i am doing is , i have placed a uibutton inside the tableview when clicking the button, it starts downloading and displays it inside the uitableviewcell.
up-to this it is fine.when going back and coming to the same uitableview, the image is not displayed.it simply empty.when again i tap uibutton it starts downloading from online.
i am not sure how to display the locally saved image? and how to display image which is downloaded and written into the app and if image is not availabale inside the app , then need to start downloading from the server.
Please guide me
Please is my code
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
int tablePadding = 40;
int tableWidth = [self.tblPoemTypes frame].size.width;
if (tableWidth > 480) {
tablePadding = 110;
}
static NSString *CellIdentifier = #"PoemTypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero]autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Only load cached images; defer new downloads until scrolling ends
/* if (!psTypeTags.image)
{
cellImageView.image = [UIImage imageNamed:#"no-image-available.jpg"];
[cell.contentView addSubview:cellImageView];
[self startIconDownload:psTypeTags forIndexPath:indexPath];
}
else
{
NSLog(#"YES Image *****************");
cellImageView.image = psTypeTags.image;
[cell.contentView addSubview:cellImageView];
}*/
//----added by re
if([indexPath row]==0)
{
goButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[goButton setTitle:#"Go" forState:UIControlStateNormal];
[goButton sizeToFit];
[goButton setFrame:CGRectMake(220,30,50,30)];
[goButton addTarget:self action:#selector(fetchThreeImages1:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:goButton];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
[imageView1 setImage:[array objectAtIndex:0]];
[cell addSubview:imageView1];
imageProgressIndicator1 = [[[UIProgressView alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:imageProgressIndicator1];
}
NSUInteger imageWidth = (tableWidth-tablePadding-20)/3;
NSUInteger imageHeight = 35;
[imageView1 setFrame:CGRectMake(tablePadding/2,20,imageWidth,imageHeight)];
[imageProgressIndicator1 setFrame:CGRectMake(120,40,imageWidth,20)];
//-----------------
}
return cell;
}
- (void)fetchThreeImages1:(id)sender
{
[imageView1 setImage:nil];
if (!networkQueue) {
networkQueue = [[ASINetworkQueue alloc] init];
}
failed = NO;
[networkQueue reset];
[networkQueue setRequestDidFinishSelector:#selector(requestForDownloadOfFileFinished:)];
[networkQueue setRequestDidFailSelector:#selector(requestForDownloadOfFileFailed:)];
[networkQueue setShowAccurateProgress:YES];
[networkQueue setDelegate:self];
self.request=nil;
NSURL *url;
NSString *urlString=#"http://cdn.visual-blast.com/wp-content/uploads/2012/03/1700-royalty-free-stock-images-48x48.jpg";
url = [NSURL URLWithString:urlString];
request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadProgressDelegate:imageProgressIndicator1];
[request setUserInfo:[NSDictionary dictionaryWithObject:#"request1" forKey:#"name"]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:#"1.png"]];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setDelegate:self];
[request setDidReceiveDataSelector:#selector(request:didReceiveBytes:)];
[request setShowAccurateProgress:YES];
[networkQueue addOperation:request];
[networkQueue go];
}
- (void)requestForDownloadOfFileFinished:(ASIHTTPRequest *)request1
{
NSLog(#"req finish.........");
NSLog(#"Content will be %llu bytes in size",[request1 contentLength]);
goButton.hidden=YES;
[imageProgressIndicator1 removeFromSuperview];
UIImage *img = [UIImage imageWithContentsOfFile:[request1 downloadDestinationPath]];
array=[[[NSMutableArray alloc]init]autorelease];
[array addObject:img];
image = [[UIImage alloc ]initWithData:[request1 responseData]];
NSString *receivedString = [request1 responseString];
NSLog(#"received string %#",receivedString);
NSData *responseData = [request1 responseData];
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Server response:%#", response);
NSLog(#"response data %#",[request1 responseData]);
NSLog(#"download destination path %#",[request downloadDestinationPath]);
NSLog(#"download destination path1 %#",[request1 downloadDestinationPath]);
NSLog(#"image %#",img);
NSLog(#"image1 %#",image);
if (img) {
[imageView1 setImage:img];
}
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Download" message:#"Download Completed" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
//completed=true;
NSLog(#"mutablearray count %#",[array objectAtIndex:0]);
//[self.tblPoemTypes reloadData];
}
- (void)requestForDownloadOfFileFailed:(ASIHTTPRequest *)request1
{
if (!failed) {
if ([[request1 error] domain] != NetworkRequestErrorDomain || [[request1 error] code] != ASIRequestCancelledErrorType) {
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Download failed" message:#"Failed to download images" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
}
failed = YES;
}
}
After the image is downloaded you have to save the image say in document directory.So when you launch the tableview first check whether that image is present in the document, if it is present directly display the image as:
Edit:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(void)loadimage{
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"your image-name"];
UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubView:myimage];
[myimage release];
}
If it not present then download it.
have a look at this project:
https://github.com/rs/SDWebImage/
After the purchase is completed ,i want to donwload image, audio and video from server.
Currently i am able to download the image and can see the progress in UIProgressView but i am not sure how can we show the single UIProgressView for multiple url requests.
I would like to know whether we can show one UIProgressView for multiple url request using ASIHttpRequest.
please let me know how to proceed? and thanks a lot
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.request=nil;
}
return self;
}
- (void)fetchThreeImages1:(id)sender
{
[imageView1 setImage:nil];
if (!networkQueue) {
networkQueue = [[ASINetworkQueue alloc] init];
}
failed = NO;
[networkQueue reset];
[networkQueue setRequestDidFinishSelector:#selector(requestForDownloadOfFileFinished:)];
[networkQueue setRequestDidFailSelector:#selector(requestForDownloadOfFileFailed:)];
[networkQueue setShowAccurateProgress:YES];
[networkQueue setDelegate:self];
self.request=nil;
NSURL *url;
NSString *urlString=#"http://www.digitalreview.ca/cams/pics/DSCN0044.JPG";
url = [NSURL URLWithString:urlString];
request = [ASIHTTPRequest requestWithURL:url];
NSString *Filename = [urlString lastPathComponent];
[request setDownloadProgressDelegate:imageProgressIndicator1];
[request setUserInfo:[NSDictionary dictionaryWithObject:#"request1" forKey:#"name"]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:Filename]];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setDelegate:self];
[request setDidReceiveDataSelector:#selector(request:didReceiveBytes:)];
[request setShowAccurateProgress:YES];
[networkQueue addOperation:request];
[networkQueue go];
}
- (void)requestForDownloadOfFileFinished:(ASIHTTPRequest *)request1
{
NSLog(#"req finish.........");
NSLog(#"Content will be %llu bytes in size",[request1 contentLength]);
goButton.hidden=YES;
[imageProgressIndicator1 removeFromSuperview];
UIImage *img = [UIImage imageWithContentsOfFile:[request1 downloadDestinationPath]];
array=[[[NSMutableArray alloc]init]autorelease];
[array addObject:img];
image = [[UIImage alloc ]initWithData:[request1 responseData]];
NSString *receivedString = [request1 responseString];
NSLog(#"received string %#",receivedString);
NSData *responseData = [request1 responseData];
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Server response:%#", response);
NSLog(#"response data %#",[request1 responseData]);
NSLog(#"download destination path %#",[request downloadDestinationPath]);
NSLog(#"download destination path1 %#",[request1 downloadDestinationPath]);
NSLog(#"image %#",img);
NSLog(#"image1 %#",image);
if (img) {
[imageView1 setImage:img];
}
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Download" message:#"Download Completed" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
//completed=true;
NSLog(#"mutablearray count %#",[array objectAtIndex:0]);
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
int tablePadding = 40;
int tableWidth = [self.tblViewDownload frame].size.width;
if (tableWidth > 480) {
tablePadding = 110;
}
static NSString *CellIdentifier = #"TypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero]autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if([indexPath row]==0)
{
NSString *urlString=#"http://www.digitalreview.ca/cams/pics/DSCN0044.JPG";
NSString* theFileName = [urlString lastPathComponent];
NSLog(#"%# the filename",theFileName);
goButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[goButton setTitle:#"Go" forState:UIControlStateNormal];
[goButton sizeToFit];
[goButton setFrame:CGRectMake(220,30,50,30)];
[goButton addTarget:self action:#selector(fetchThreeImages1:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:goButton];
//-------------
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
NSLog(#"%# workSpacePath ",workSpacePath);
//--------------
UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
//imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
imageView1.image = [UIImage imageWithContentsOfFile:workSpacePath];
[cell addSubview:imageView1];
NSLog(#"dfdfD");
NSLog(#"sdfdsf");
}
imageProgressIndicator1 = [[[UIProgressView alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:imageProgressIndicator1];
}
NSUInteger imageWidth = (tableWidth-tablePadding-20)/3;
NSUInteger imageHeight = 35;
[imageView1 setFrame:CGRectMake(tablePadding/2,20,imageWidth,imageHeight)];
[imageProgressIndicator1 setFrame:CGRectMake(120,40,imageWidth,20)];
}
return cell;
}
Have a look at the ASIHTTPRequest documentation section 'Tracking download progress for a set of requests'.
You basically need to create an ASINetworkQueue and add each of your requests to it. The queue is responsible for tracking overall progress and will call delegate methods where you can update your progress bar.
My NSMutableArray data are in NSData formate.I am trying to attached NSMutableArray data to E-mail body.Here is my NSMutableArray code:
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSString *msg1 = [defaults1 objectForKey:#"key5"];
NSData *colorData = [defaults1 objectForKey:#"key6"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
NSData *colorData1 = [defaults1 objectForKey:#"key7"];
UIColor *color1 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData1];
NSData *colorData2 = [defaults1 objectForKey:#"key8"];
UIFont *color2 = [NSKeyedUnarchiver unarchiveObjectWithData:colorData2];
CGFloat x =(arc4random()%100)+100;
CGFloat y =(arc4random()%100)+250;
lbl = [[UILabel alloc] initWithFrame:CGRectMake(x, y, 100, 70)];
lbl.userInteractionEnabled=YES;
lbl.text=msg1;
lbl.backgroundColor=color;
lbl.textColor=color1;
lbl.font =color2;
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.numberOfLines = 50;
[self.view addSubview:lbl];
[viewArray addObject:lbl ];
viewArray is my NSMutableArray .All the data store in viewArray are in NSData formate.I try this code to attached viewArray data in E-mail.
- (IBAction)sendEmail {
if ([MFMailComposeViewController canSendMail])
{
NSArray *recipients = [NSArray arrayWithObject:#"example#yahoo.com"];
MFMailComposeViewController *controller = [[MFMailComposeViewController
alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Iphone Game"];
NSLog(#"viewArray: %#", viewArray);
NSString *string = [viewArray componentsJoinedByString:#"\n"];
NSString *emailBody = string;
NSLog(#"test=%#",emailBody);
[controller setMessageBody:emailBody isHTML:YES];
[controller setToRecipients:recipients];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Your device is not set up for email." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}
Here i see objects store in viewArray.in console its look like this..[2012-05-07 18:48:00.065 Note List[279:207] test=UILabel: 0x8250850; frame = (140 341; 56 19); text = 'Xxxxxxx'; clipsToBounds = YES; layer = > but in E-mail i see only this..>> please suggest any one how can i attached my viewArray data in E-mail.
]
in email attachement, you can only send NSData or string to email, now if you want to send it by string, then get all values you want to send email like, lable.text, lable.color, lable.alpha etc, with proper keys and place it in the body and parse there, else find some way to convert your object into NSData and attach it using mfmailcomposer attach data method
read this to convert NSArray into NSData
How to convert NSArray to NSData?
and this to convert back the NSData to NSArray
How can i convert a NSData to NSArray?
and then write this data to file as,
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(#"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(#"File %# doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(#"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
and finally attach it to the email using
- (void)addAttachmentData:(NSData *)attachment mimeType:(NSString *)mimeType fileName:(NSString *)filename
I'm downloading the images from the online image for cache when offline. When I open application, The image was downloaded all completely before UIAlertView pop. It's finish incorrectly. I want to make the UIAlertView pop before images download. Here there are my code below.
- (void) operatePopupUpdating {
myAlert = [[UIAlertView alloc] initWithTitle:#"Updating database.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[myAlert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(myAlert.bounds.size.width / 2, myAlert.bounds.size.height - 50);
[indicator startAnimating];
[myAlert addSubview:indicator];
[self operateUpdate];
[self updateImage];
[self operationCompleted];
}
In updateImage, operateUpdate and operationCompleted Method
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:ico_path]];;
[thedata writeToFile:localFilePath atomically:YES];
}
}
-(void) operationCompleted
{
[myAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message form System" message:#"Database was updated successful" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (void)operateUpdate {
NSString *filePath = [self dataFileSettingPath];
int updatedVer = 0;
int version = [self checkDatabase];
if (version == -1) {
updatedVer = [self createDataBase:0];
} else {
updatedVer = [self updateDataBase:version];
}
[self.settingInfo setObject:[NSString stringWithFormat:#"%d",updatedVer] forKey:#"DBVersion"];
[self.settingInfo writeToFile:filePath atomically:YES];
}
How I fix them and work correctly?
The alertView will show only after your image downloading complete. One Solution to solve this is,
Create another class ImageDownLoad.h
in .h
#property(nonatomic,assign)id delegate;
#property(nonatomic,retain) NSString *path;
in .m
#synthesize delegate;
#synthesize path;
Create a method namely,
-(void)startDownloadImageWithUrl:(NSURL*)imageUrl withLocalFilePath:(NSSTring*)filePath{
path = filePath;
receiveData = [NSMutableData data];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:imageUrl];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receiveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[(id)delegate performSelector:#selector(SaveData:inFilePath:) withObject:receiveData withObject:path];
}
This will create connection and start download your image in a separate class. Then in your mai ViewController add bit of code like below.
- (void)updateImage {
NSString *snake_ico_file = #"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:#"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
for (int i = 0; i < max_count; i++) {
NSString *path = #"http://exitosus.no.de/drngoo/image/";
path = [path stringByAppendingFormat:#"%d",i];
NSString *ico_path = [path stringByAppendingFormat:#"/ico"];
//icon
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [snake_ico_file stringByAppendingFormat:#"%d.jpg"];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
ImageDownLoad *imageDown = [[ImageDownLoad alloc]init];
imageDown.delegate = self;
[imageDown startDownloadImageWithUrl:[NSURL URLWithString:ico_path] withLocalFilePath:localFilePath];
}
}
This method will be called each time when image download completes.
-(void)SaveData:(NSData*)data inFilePath:(NSString*)filePath{
[data writeToFile:filePath atomically:YES];
}
Your UI wont delay by doing so :)