Monday 22 June 2015

Check the URL Status Code & Download a PDF File in iOS

200 - Success
404 - Page Not Found
500 - Internel Server Error

.m File:
-(void)testing_function
{
    // Get the PDF Data from the url in a NSData Object
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/info.pdf"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse* response = nil;
    NSError* error = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"statusCode = %d", [response statusCode]);
    
    if ([response statusCode] == 200)
    {
        NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.example.com/info.pdf"]];
        
        // Store the Data locally as PDF File
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Result.pdf"];
        [pdfData writeToFile:filePath atomically:YES];
        
        // Now create Request for the file that was saved in your documents folder
        NSURL *url = [NSURL fileURLWithPath:filePath];
        docController = [UIDocumentInteractionController alloc];
        docController = [UIDocumentInteractionController interactionControllerWithURL:url];
        BOOL isValid = [docController presentOpenInMenuFromRect:pdfIcon.frame inView:self.view animated:YES];
        docController.delegate = self;
        
        if(isValid)
        {
            docController.delegate = self;
        }
        else
        {
            UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"Sorry" message:@"You need iBooks to view this file" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Install", nil];
            [alert show];
        }
    }
}

No comments: