How to Download a video using UIWebView - iphone

I want to download a the video using web-view but I am not getting how to download it?
my video link is here
the sample code for playing video which I am using is
-(void)embedYouTubeInWebView:(NSString*)url theWebView:(UIWebView *)aWebView {
   NSString* html = [NSString stringWithFormat:#"%#", url];
   [aWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:html]]];
}
- (void)viewDidLoad
{
   [super viewDidLoad];
   
  [self embedYouTubeInWebView:#"http://player.vimeo.com/video/32983838" theWebView:myWebView];
   // Do any additional setup after loading the view, typically from a nib.
}
can anyone please help me to download this video?

To download a file i used the following Code. Hope it will work for you too.
- (IBAction)getFileFromFtpServer:(UIView *)sender
{
NSString *stringURL = #"http://player.vimeo.com/video/32983838";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.mpeg4"];
[urlData writeToFile:filePath atomically:YES];
}
}

Try this here your video is playing..
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 380)];
webView.delegate=self;
[webView setOpaque:NO];
webView.backgroundColor=[UIColor clearColor];
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
CGFloat height = CGRectGetHeight(screen);
UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.frame=CGRectMake((width/2) - 10,(height/2) - 54, 20, 20);
activityIndicator.center=self.view.center;
[activityIndicator hidesWhenStopped];
[self playVideo];
}
-(void) playVideo
{
NSURL *url = [NSURL URLWithString:#"http://player.vimeo.com/video/32983838"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
[activityIndicator startAnimating];
[webView addSubview:activityIndicator];
}
/* WebViewDidStartLoad */
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[activityIndicator startAnimating];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
/* WebViewDidFinishLoad */
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicator stopAnimating];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
/* WebViewdidFailLoadWithError */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

If I understand correctly and in response to above, google has shut down several "converter sites" due to copyright infringements: http://www.real.com/resources/youtube-to-mp3-converter There are other sites available to download video content from (again, assuming you're abiding by the copyright guidelines) : This lists five sites where you can find and download online videos free. To make sure a video is legal to download, look for licensing information about the video. Typically, videos with a “Creative Commons” license are legal to download, but may have limitations on how you use the video. http://www.real.com/resources/download-one-video

Related

Download Multiple images using Native functionality IOS

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.

Foursquare integration in iPhone

I am trying to do the FourSquare integration in iPhone..i couldn't found any good guidelines through Goggling.... Can any one suggest me the Good guidelines or URLs for FourSquare integration in iPhone..
Thanks
Here is the foursquare api link
Example of Foursquare integration link.
Further code for Foursquare integration
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Foursquare";
//check the authentication
if ([Foursquare2 isNeedToAuthorize]) {
//If needed show the webview
webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
NSString *url = [NSString stringWithFormat:#"https://foursquare.com/oauth2/authenticate?display=touch&client_id=%#&response_type=code&redirect_uri=%#",OAUTH_KEY,REDIRECT_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[webView loadRequest:request];
[webView setDelegate:self];
[self.view addSubview:webView];
[webView release];
mTableView.hidden = YES;
}else{
//Show your view
mTableView.hidden = NO;
[Foursquare2 searchVenuesNearByLatitude:#"40.763" longitude:#"-73.990" accuracyLL:nil altitude:nil accuracyAlt:nil query:#"" limit:#"15" intent:#"" callback:^(BOOL success, id result){
if (success) {
tableData = [[FoursquareParser parseSearchVenuesResultsDictionary:(NSDictionary*)result] retain];
[mTableView reloadData];
}
}];
}
}

Why UIWebView work so slowly when loadHTMLString with UIWebView?

It take about 10s to loadHTMLString in my APP, who can point out what's the problem?
- (void)viewDidLoad {
[super viewDidLoad];
webView = [[UIWebView alloc]initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH, 480)];
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
webView.delegate = self;
[scrollView addSubview:webView];
}
After enter the view, If I receive message:
- (void)updateJournalView:(NSArray *)journals {
NSString *descHtml = [self getHtmlDesc:journals];
[webView loadHTMLString:descHtml baseURL:nil];
}
getHtmlDesc method will return the html string quickly.
from load log, you can see it take about 5s to load.
2012-11-26 20:34:35.322 test[8456:c07] ====start load 2012-11-26 12:34:35 +0000:
2012-11-26 20:34:39.890 test[8456:c07] ====finish load 2012-11-26 12:34:39 +0000:
Following is UIWebViewDelegate method:
- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
CGRect frame = aWebView.frame;
frame.size.height = 1;
aWebView.frame = frame;
CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
aWebView.frame = frame;
scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, fittingSize.height);
NSLog(#"====finish load %#:", [NSDate date]);
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
if ([[url scheme] isEqualToString:#"redirect"] &&
[[url host] isEqualToString:#"opp_detail"]) {
NSString *oppIdStr = [[url path] stringByReplacingOccurrencesOfString:#"/player_id=" withString:#""];
if (oppIdStr && [oppIdStr length]) {
NSNumber *oppId = [NSNumber numberWithInt:[oppIdStr intValue]];
if ([oppId intValue] != gcontext.me.id) {
[screenNav gotoOppDetailScreen:[oppId intValue]];
}
}
}
return YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
if ([[url scheme] isEqualToString:#"redirect"] &&
[[url host] isEqualToString:#"opp_detail"]) {
NSString *oppIdStr = [[url path] stringByReplacingOccurrencesOfString:#"/player_id=" withString:#""];
if (oppIdStr && [oppIdStr length]) {
NSNumber *oppId = [NSNumber numberWithInt:[oppIdStr intValue]];
if ([oppId intValue] != gcontext.me.id) {
[screenNav gotoOppDetailScreen:[oppId intValue]];
}
}
}
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(#"====start load %#:", [NSDate date]);
}
Please give me a hand, why it is so slow when loadHTMLString with UIWebView?
If there is nothing heavy to render, then it's possible that all about slow disk operations, that are performing when you're reading your html string.
https://stackoverflow.com/a/3400892/1851930

No audio played using MPMoviePlayerController

I have been using MPMoviePlayerController to play mp4 file. Video is playing fine but there is no audio at all.
I have downloaded first in one function and played using another. Please check the code below. Am I doing anything wrong here...
- (void) download_file : (NSString *) msg_url
{
if (msg_url != nil) {
// Download and play
NSURL *url = [NSURL URLWithString:msg_url];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
char file_path[512] = {0};
get_app_data_path(OFI_VC_MAILBOX_PATH, file_path); // Give document path.
NSString *filePath = [NSString stringWithFormat:#"%s/%#", file_path,#"mailbox.mp4"];
[urlData writeToFile:filePath atomically:YES];
[self performSelectorOnMainThread:#selector(play_mp4_file:) withObject:filePath waitUntilDone:NO];
}
}
}
- (void) play_mp4_file : (NSString *) filepath
{
if (is_same_view == true) {
[self.view setUserInteractionEnabled:YES];
if (filepath != nil) {
NSURL *file_url = [NSURL fileURLWithPath:filepath];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:file_url];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
moviePlayer.useApplicationAudioSession = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
}
}
Thanks for your helps
I have fixed the issue. Problem is with .mp4 extension, I have used .mov. Its playing audio now.

i want to save my pdf into my iphone, pdfs url are with me through parsing

I have parsed my xml and i got some images and their corresponding urls of pdf from server.so whenever i click on image i have their corresponding url of pdf.I am giving an alertView on click of images and when user select the download button of alertView it should download the pdf from url into my iphone device
CODE:-
#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
I would do it with NSURLConnection and then I would reuse same code above, because you have it already declared properly.
Save data to NSData and then with writeToFile save it to main bundle.
So here is some more explanation how I would do it.
There are several ways to do it.
Here is how to do it with NSData
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]]; [myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
Also you can use ASIHTTPRequest library which has been discontinued by author, but still works like it should.
ASIHTTPRequest *myDownloadRequest = [ASIHTTPRequest requestWithURL:fileUrl];
[request setDownloadDestinationPath:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"]];
But maybe easiest way of all because as I can see you have displayed pdf already, so it's contents are in receivedData is just to call
[receivedData writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
So actually you can reuse code that you have already wrote in viewDidLoad, replace url if necessary and after connection is closed save file to disk.
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];
}