Я хочу сохранить свой PDF в моем Iphone, URL-адрес PDF со мной через анализ - PullRequest
0 голосов
/ 18 октября 2011

Я проанализировал мой xml и получил несколько изображений и соответствующие им URL-адреса pdf с сервера. Поэтому всякий раз, когда я нажимаю на изображение, у меня появляется соответствующий URL-адрес pdf . Я выдаю alertView при щелчке изображений и когда пользователь выбирает кнопку загрузки alertView, он должен загрузить PDF-файл с URL-адреса в мое устройство iphone

КОД: -

@implementation SecondViewController

@synthesize scrollView,receivedData;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{   
    [receivedData appendData:data]; 
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

    [myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    myIndicator.hidesWhenStopped = YES;
    [myIndicator startAnimating];

    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"iphone_landscape.png"]];
    self.view.backgroundColor = background;
    [background release];   

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:150.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        receivedData = [[NSMutableData data] retain];
    }

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    int x=20,y=50;

    appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];

    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 45,320, 480)];   
    scrollView.contentSize = CGSizeMake(320,5000);
    scrollView.showsVerticalScrollIndicator = YES;

    for (Litofinter *lito in appDelegate.bookArray) {
        if([appDelegate.currentButtonPressed isEqualToString:lito.cName])
        {
            NSLog(@"Count == %d ===",[lito.productsArray count]);
            for (Products *prod in lito.productsArray) {

                NSString * urlString = [prod.thumbnail stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                NSURL * imageURL = [NSURL URLWithString:urlString];

                NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
                UIImage * image = [UIImage imageWithData:imageData];

                [myIndicator stopAnimating];
                [myIndicator removeFromSuperview];

                UIButton *imageButton = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
                [imageButton setFrame:CGRectMake(x, y, 150, 200)];
                [imageButton setImage:image forState:UIControlStateNormal];
                [imageButton setTitle:prod.pdf forState:UIControlStateNormal];
                [imageButton addTarget:self action:@selector(onTapBook:) forControlEvents:UIControlEventTouchUpInside];

                [scrollView addSubview:imageButton];

                x = x + 150;

                if(x >300)
                {
                    y = y +250;
                    x = 20;

                }
            }
        }
    }
    [self.view addSubview:scrollView];

    [connection release];
    [receivedData release];


}

-(void)onTapBook:(id)sender{

    UIButton *button = (UIButton *) sender;
    appDelegate.currentBookPressed = [button currentTitle];

//  viewController2 = [[PdfShowViewController alloc]initWithNibName:@"PdfShowViewController" bundle:nil];
//  [self presentModalViewController:viewController2 animated:YES];

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Ver Catalogo!" message:@"" delegate:self cancelButtonTitle:@"Cancelar" otherButtonTitles:@"Ver on-line",@"Descargar",nil];
    [alert show];

     /*[NSString stringWithFormat:@"%@",appDelegate.currentBookPressed] */ 
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
{  

    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];  

    if([title isEqualToString:@"Ver on-line"])  
    { 
        // i will show the pdf online here

    }  
    else if([title isEqualToString:@"Descargar"])  
    {           

        // what to write to download the pdf
    }  

} 

-(IBAction)onTapBack{
    [self dismissModalViewControllerAnimated:YES];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}


- (void)dealloc {
    [super dealloc];
    [scrollView release];
}


@end

1 Ответ

1 голос
/ 18 октября 2011

Я бы сделал это с NSURLConnection, а затем я бы использовал тот же код выше, потому что он уже объявлен правильно.

Сохраните данные в NSData, а затем с помощью writeToFile сохраните их в основной комплект.

Итак, вот еще несколько объяснений, как мне это сделать.

Есть несколько способов сделать это.

Вот как это сделать с NSData

NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"your_url"]]; [myFile writeToFile:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"yourfilename.pdf"] atomically:YES];

Также вы можете использовать библиотеку ASIHTTPRequest, которая была прекращена автором, но все еще работает, как и должно.

ASIHTTPRequest *myDownloadRequest = [ASIHTTPRequest requestWithURL:fileUrl];
[request setDownloadDestinationPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"yourfilename.pdf"]];

Но, возможно, самый простой способ, потому что, как я вижу, вы уже отобразили pdf, поэтому это содержимоенаходятся в receiveData, это просто вызов

[receivedData writeToFile:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"yourfilename.pdf"] atomically:YES];

Так что на самом деле вы можете повторно использовать код, который вы уже написали в viewDidLoad, при необходимости заменить url и после закрытия соединения сохранить файл на диск.

 NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:150.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        receivedData = [[NSMutableData data] retain];
    }
...