MPMoviePlayerController endless loading (filepicker) - objective-c

I am trying to stream a video uploaded on filepicker, but it keeps loading without playing the video.
The link is: https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv
The page is a video/mp4 page, but as you can see there is no extension for the page.
The Code:
#interface RTVideo()
#property (nonatomic,strong) MPMoviePlayerController *moviePlayer;
#end
#implementation RTVideo
UIView *frame;
-(void)play
{
NSNumber *adId = 5 ;
NSString *session = [[NSUserDefaults standardUserDefaults]stringForKey:#"sessionID"];
NSString *type = #"video";
[NetworkManagerCenter retrievePageWithtype:type
Id:adId
session:session
success:^(RT *ad) {
[self playAD];
} failure:^(NSError *error) {
[self removeFromSuperview];
}];
}
-(void)playAD
{
frame = self;
NSURL *movieURL = [NSURL URLWithString: #"https://www.filepicker.io/api/file/fLayj5bYTWuso1TVNknv"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
[frame addSubview:self.moviePlayer.view];
self.moviePlayer.fullscreen = YES;
self.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
self.moviePlayer.initialPlaybackTime = -1.0;
[self.moviePlayer prepareToPlay];
[self.moviePlayer play];
}
#end
Is this not working because there is no extension and how can I solve this?

Related

How to login With instagram and share wtih instagram Using IOS ? Objective c

1) Register to Instagram
To create Application using the Instagram API, you must have an account with Instagram.
After creating your account in Instagram, login with Instagram account and open the URL: http://instagram.com/developer/
Go to “Register your application” and click on the “Register New Client” button.
You will be asked to provide Application Name, Description of your application, website and oAuth redirect_url. Here, the oAuth redirect_url specifies where to redirect users after they have chosen whether or not to authenticate your application.
After successfully registering new client, Instagram will provide CLIENT INFO like CLIENT ID, CLIENT SECRET, WEBSITE URL, REDIRECT URI. Save CLIENT ID,CLIENT SECRET, REDIRECT URI to your application constants class as you will need this for authenticating to Instagram.
Lets see how can we authenticate…
Step 1.
At First set the authentication URL
Create a header file and provide the header file name is ConstantHandle
and set the all authentication URL
#ifndef ConstantHandler_h
#define ConstantHandler_h
//set User authentication and url
#define INSTAGRAM_AUTHURL #"https://api.instagram.com/oauth/authorize/"
#define INSTAGRAM_APIURl #"https://api.instagram.com/v1/users/"
#define INSTAGRAM_CLIENT_ID #"Client Id"
#define INSTAGRAM_CLIENTSERCRET #"Clients Secret"
#define INSTAGRAM_REDIRECT_URL #"Redirect URL"
#define INSTAGRAM_ACCESS_TOKEN #"access_token"
#define INSTAGRAM_SCOPE   #"likes+comments+relationships+basic"
//Contant Url
#define ACCESS_TOKEN #"#access_token="
#define UNSIGNED #"UNSIGNED"
#define CODE #"code="
#define END_POINT_URL #"https://api.instagram.com/oauth/access_token"
#define HTTP_METHOD #"POST"
#define CONTENT_LENGTH #"Content-Length"
#define REQUEST_DATA #"application/x-www-form-urlencoded"
#define CONTENT_TYPE #"Content-Type"
//share Photo Constant
#define DOCUMENT_FILE_PATH #"Documents/originalImage.ig"
#define APP_URL #"instagram://app"
#define UTI_URL #"com.instagram.exclusivegram"
#define MESSAGE #"Instagram not installed in this device!\nTo share image please install instagram."
#endif /* ConstantHandler_h */
At first set the all micro
Step 2.
Add a file in your project
Provide the file name is
InstagramController
create a file inherit with UIViewController
Add the this code in InstagramController.h file
#import <UIKit/UIKit.h>
#import "ConstantHandler.h"
#interface InstagramController : UIViewController
- (void)loginWithInstagramWithParsentViewController:(UIViewController *)controller completionHandler:(void(^)(NSDictionary *userProfileInformation))completionHanlder failureHandler:(void(^)(NSDictionary *errorDetail))failureHandler;
- (void)sharePhotoWithInstagaramWithImage:(UIImage *)image parsentViewcontroller:(UIViewController *)controller;;
#end
Add the this code in InstagramController.m file
#import "InstagramController.h"
#interface InstagramController ()<UIWebViewDelegate,UIDocumentInteractionControllerDelegate>
{
UIView *_progressView;
UIWebView *_webView;
UIViewController *_controller;
UIActivityIndicatorView *_activitiyIndicator;
}
#property(strong,nonatomic)NSString *typeOfAuthentication;
#property (nonatomic, strong) void(^completionHandler)(NSDictionary *);
#property (nonatomic, strong) void(^failureHandler)(NSDictionary *);
#property(nonatomic,strong)UIDocumentInteractionController *docFile;
#end
#pragma mark - View Controller Life Cycle Method
#implementation InstagramController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
//Add the cancel Button
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 70, 20)];
[button setTitle:#"Cancel" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
//Setup The UIWebView
[super viewDidAppear: animated];
_webView = [UIWebView new];
CGRect frame = self.view.frame;
frame.origin.y = 64;
_webView.frame = frame;
_webView.delegate = self;
[self.view addSubview:_webView];
//Hit instagaram API;
NSString* authURL = nil;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
[storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
if ([_typeOfAuthentication isEqualToString:UNSIGNED])
{
authURL = [NSString stringWithFormat: #"%#?client_id=%#&redirect_uri=%#&response_type=token&scope=%#&DEBUG=True",
INSTAGRAM_AUTHURL,
INSTAGRAM_CLIENT_ID,
INSTAGRAM_REDIRECT_URL,
INSTAGRAM_SCOPE];
}
else
{
authURL = [NSString stringWithFormat: #"%#?client_id=%#&redirect_uri=%#&response_type=code&scope=%#&DEBUG=True",
INSTAGRAM_AUTHURL,
INSTAGRAM_CLIENT_ID,
INSTAGRAM_REDIRECT_URL,
INSTAGRAM_SCOPE];
}
[_webView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: authURL]]];
}
#pragma mark - Local Method
/*!
Setup The genral Indicator View
#retur void
*/
- (void)addIndicatorView {
_progressView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 62)];
_progressView.layer.cornerRadius = 10;
_progressView.layer.masksToBounds = YES;
_progressView.backgroundColor = [UIColor blackColor];
_progressView.alpha = 0.7;
UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10,43, 80, 15)];
lable.textColor = [UIColor grayColor];
[lable setTextAlignment:NSTextAlignmentCenter];
lable.font = [UIFont italicSystemFontOfSize:15.0f];
lable.text = #"progress...";
[_progressView addSubview:lable];
_activitiyIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[_activitiyIndicator setCenter:CGPointMake(_progressView.frame.size.width/2.0, _progressView.frame.size.height/2.3)]; // I do this because I'm in landscape mode
[_progressView addSubview:_activitiyIndicator];
[_activitiyIndicator startAnimating];
_progressView.center = self.view.center;
[_webView addSubview:_progressView];
}
/*!
This method is used to request to call back Url and check the authenTication
#param NSURLRequest is the check the request URl;
#return BOOLk
*/
- (BOOL) checkRequestForCallbackURL: (NSURLRequest*) request
{
NSString* urlString = [[request URL] absoluteString];
if ([_typeOfAuthentication isEqualToString:UNSIGNED])
{
// check, if auth was succesfull (check for redirect URL)
if([urlString hasPrefix: INSTAGRAM_REDIRECT_URL])
{
// extract and handle access token
NSRange range = [urlString rangeOfString: ACCESS_TOKEN ];
[self handleAuth:[urlString substringFromIndex: range.location+range.length] withProfileInfo:nil];
return NO;
}
}
else
{
if([urlString hasPrefix: INSTAGRAM_REDIRECT_URL])
{
// extract and handle code
NSRange range = [urlString rangeOfString: CODE];
[self makePostRequest:[urlString substringFromIndex: range.location+range.length]];
return NO;
}
}
return YES;
}
/*!
This method is used to get the User profile information
#param NSString is a authToken
#return void;
*/
-(void)makePostRequest:(NSString *)authToken
{
NSString *post = [NSString stringWithFormat:#"client_id=%#&client_secret=%#&grant_type=authorization_code&redirect_uri=%#&code=%#",INSTAGRAM_CLIENT_ID,INSTAGRAM_CLIENTSERCRET,INSTAGRAM_REDIRECT_URL,authToken];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// URL of the endpoint we're going to contact.
NSURL *url = [NSURL URLWithString:END_POINT_URL];
// Create a POST request with our JSON as a request body.
NSMutableURLRequest *requestData = [NSMutableURLRequest requestWithURL:url];
requestData.HTTPMethod = HTTP_METHOD;
[requestData setValue:postLength forHTTPHeaderField:CONTENT_LENGTH];
[requestData setValue:REQUEST_DATA forHTTPHeaderField:CONTENT_TYPE];
requestData.HTTPBody = postData;
// Create a task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:requestData
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (!error)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self handleAuth:[dictionary valueForKey:#"access_token"] withProfileInfo:dictionary];
} else{
NSLog(#"Error: %#", error.localizedDescription);
[self handleAuth:nil withProfileInfo:nil];
}
}];
// Start the task.
[task resume];
}
/*!
This method is used to get The profile information is the request is completed
#param NSSTring authetication key
#return void
*/
- (void) handleAuth: (NSString*)authToken withProfileInfo:(NSDictionary *)dictionary
{
NSLog(#"successfully logged in with Tocken == %#",authToken);
if (dictionary) {
_completionHandler(dictionary);
} else _failureHandler(dictionary);
// [self makePostRequest:authToken];
[self cancelLogin];
}
- (void)cancelLogin {
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *vc = [_controller.childViewControllers lastObject];
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
});
}
#pragma mark -WebView Delegate Method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
return [self checkRequestForCallbackURL: request];
}
- (void) webViewDidStartLoad:(UIWebView *)webView
{
[self addIndicatorView];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[_progressView removeFromSuperview];
_progressView = nil;
[_activitiyIndicator stopAnimating];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self webViewDidFinishLoad: webView];
}
#pragma mark - user Define Method
- (void)loginWithInstagramWithParsentViewController:(UIViewController *)controller completionHandler:(void(^)(NSDictionary *userProfileInformation))completionHanlder failureHandler:(void(^)(NSDictionary *errorDetail))failureHandler {
_controller = controller;
[controller addChildViewController:self];
self.view.frame = controller.view.frame;
[controller.view addSubview:self.view];
[self didMoveToParentViewController:controller];
_completionHandler = completionHanlder;
_failureHandler = failureHandler;
}
- (void)sharePhotoWithInstagaramWithImage:(UIImage *)image parsentViewcontroller:(UIViewController *)controller{
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:DOCUMENT_FILE_PATH];
if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
NSFileManager *fielManager = [NSFileManager defaultManager];
[fielManager removeItemAtPath:savePath error:nil];
}
BOOL save = [UIImagePNGRepresentation(image) writeToFile:savePath atomically:YES];
NSURL *instagramURL = [NSURL URLWithString:APP_URL];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL] && save) {
self.docFile = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:savePath]];
self.docFile.UTI = UTI_URL;
self.docFile.delegate = self;
[self.docFile presentOpenInMenuFromRect:CGRectZero inView:controller.view animated:YES];
} else {
NSLog(#"%#",MESSAGE);
}
}
#pragma mark - UIDocumentInteractionController delegateMethod
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
#pragma mark - selector method
-(void)cancel:(UIButton *)button {
[self cancelLogin];
}
#end
Step 3:
Finally import "ConstantHandler.h" file in ViewController
Add the Login and share Button in ViewController and the this code
#import "ViewController.h"
#import "InstagramController.h"
#interface ViewController ()
#property(nonatomic,strong) InstagramController *instagramHandler ;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)loginWithInstagram:(id)sender {
_instagramHandler = [InstagramController new];
[_instagramHandler loginWithInstagramWithParsentViewController:self completionHandler:^(NSDictionary *userProfileInformation) {
NSLog(#"%#",userProfileInformation);
} failureHandler:^(NSDictionary *errorDetail) {
NSLog(#"%#",errorDetail);
}];
}
- (IBAction)shareWithInstagram:(id)sender {
_instagramHandler = [InstagramController new];
UIImage *image = [UIImage imageNamed:#"flower-197343_960_720.jpg"];
[_instagramHandler sharePhotoWithInstagaramWithImage:image parsentViewcontroller:self];
}
#end
Step 4.
Build and run the project
Delete NSHTTPCookieStorage and Use App Transport Security.
And add webView delegate before webView request. After use method, dealloc and set webView delegate to nil.

Which third party Imageview class should i used?

My requirement is :
Need to show image in imageview from server URL & save it for offline use also.
But There may be chances that same URL image can be updated.
I tried EGOImageview,AsyncImageview,FXImageview,Haneke thsese all classes i tried.
my first part of requirement is achieved. but not second..i.e if "xxxxx" link image is shown for first time....if on that same link image is upadated ,app shows old image only...
You can use the below class that will full fill your requirement
DImageView.h
#import <UIKit/UIKit.h>
#interface DImageView : UIImageView
#property (nonatomic, strong) UIActivityIndicatorView *activityView;
- (void)processImageDataWithURLString:(NSString *)urlString;
+ (UIImage *)getSavedImage :(NSString *)fileName;
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData;
DImageView.m
#import "DImageView.h"
#define IMAGES_FOLDER_NAME #"DImages"
#implementation DImageView
#pragma mark - App Life Cycle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
}
return self;
}
- (void)dealloc
{
self.activityView = nil;
[super dealloc];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initWithFrame:[self frame]];
}
return self;
}
#pragma mark - Download images
- (void)processImageDataWithURLString:(NSString *)urlString //andBlock:(void (^)(UIImage * img))processImage
{
#autoreleasepool
{
UIImage * saveImg = [DImageView getSavedImage:urlString];
if (saveImg)
{
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_async(callerQueue, ^{
#autoreleasepool
{
[self setImage:saveImg];
}
});
}
else
{
[self showActivityIndicator];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
__block NSError* error = nil;
dispatch_async(downloadQueue, ^{
NSData * imageData = [[[NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error] retain] autorelease];
if (error)
{
NSLog(#"DImg Error %#", [error debugDescription]);
}
else
{
dispatch_async(callerQueue, ^{
#autoreleasepool
{
UIImage *image = [UIImage imageWithData:imageData];
[self setImage:image];
[self hideActivityIndicator];
/* Below code is to save image*/
[DImageView saveImageWithFolderName:IMAGES_FOLDER_NAME AndFileName:urlString AndImage:imageData];
}
});
}
});
dispatch_release(downloadQueue);
}
}
}
#pragma mark - File Save methods
+ (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData
{
#autoreleasepool
{
NSFileManager *fileManger = [NSFileManager defaultManager] ;
NSString *directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],folderName] ;
if (![fileManger fileExistsAtPath:directoryPath])
{
NSError *error = nil;
[fileManger createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
}
fileName = [DImageView fileNameValidate:fileName];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
BOOL isSaved = [imageData writeToFile:filePath atomically:YES];
if (!isSaved)
{
NSLog(#" ** Img Not Saved");
}
}
}
+ (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
+ (UIImage *)getSavedImage :(NSString *)fileName
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
fileName = [DImageView fileNameValidate:fileName];
NSFileManager * fileManger = [NSFileManager defaultManager] ;
NSString * directoryPath = [NSString stringWithFormat:#"%#/%#",[DImageView applicationDocumentsDirectory],IMAGES_FOLDER_NAME] ;
NSString * filePath = [NSString stringWithFormat:#"%#/%#",directoryPath,fileName] ;
if ([fileManger fileExistsAtPath:directoryPath])
{
UIImage *image = [UIImage imageWithContentsOfFile:filePath] ;
if (image)
{
return image;
}
else
{
NSLog(#"** Img Not Found **");
return nil;
}
}
[pool release];
return nil;
}
+ (NSString*) fileNameValidate : (NSString*) name
{
name = [name stringByReplacingOccurrencesOfString:#"://" withString:#"##"];
name = [name stringByReplacingOccurrencesOfString:#"/" withString:#"#"];
name = [name stringByReplacingOccurrencesOfString:#"%20" withString:#""];
return name;
}
#pragma mark - Activity Methods
- (void) showActivityIndicator
{
self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
self.activityView.hidesWhenStopped = TRUE;
self.activityView.backgroundColor = [UIColor clearColor];
self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[self addSubview:self.activityView];
[self.activityView startAnimating];
}
- (void) hideActivityIndicator
{
CAAnimation *animation = [NSClassFromString(#"CATransition") animation];
[animation setValue:#"kCATransitionFade" forKey:#"type"];
animation.duration = 0.4;;
[self.layer addAnimation:animation forKey:nil];
[self.activityView stopAnimating];
[self.activityView removeFromSuperview];
for (UIView * view in self.subviews)
{
if([view isKindOfClass:[UIActivityIndicatorView class]])
[view removeFromSuperview];
}
}
What will this class do ?
It will download images from server and save it to application document directory And get it from local if its available.
How to use that ?
Set DImageView class in your nib file for UIImageView.
Then you can simply use it as below in your .m file.
[imgViewName processImageDataWithURLString:imageURl];
You should take a look at SDWebImage. It's one of the most used UIImageView category right now and offers a lot of features, including caching.
Have a look at this part of the documentation to learn how to refresh your cache with it: Handle image refresh

Cannot load files in UIDocumentInteractionController

I am building an app that allows the opening of a PDF, and handles this like so:
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url sourceApplication:(NSString *)source annotation:(id)annotation
{
if (url != nil && [url isFileURL])
{
if ([[url pathExtension] isEqualToString:#"pdf"])
{
FilePreviewViewController *filePreviewController = [[FilePreviewViewController alloc] init];
[filePreviewController setURL:url];
[self.navController pushViewController:filePreviewController animated:NO];
return YES;
}
}
return NO;
}
And then in FilePreviewController.m:
-(void) setURL:(NSURL *) URL
{
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:URL];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentPreviewAnimated:NO];
}
However, when I open a file and the view transitions, I get these messages:
Unbalanced calls to begin/end appearance transitions for <QLRemotePreviewContentController: 0x1581fe00>.
Couldn't issue file extension for path: /private/var/mobile/Containers/Data/Application/6399D00B-47A1-4F33-B34C-3F0B07B648AE/Documents/Inbox/pdf-8.pdf
And the file itself does not load. I'm not sure what I'm doing wrong because this works fine on the simulator (i.e. the PDF loads and displays perfectly).
use this code to view/read pdf format file.
.h
<UIDocumentInteractionControllerDelegate>
UIDocumentInteractionController *controller;
.m
NSString *File_name=[NSString stringWithFormat:#"%#",URL];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",docDir,[File_name lastPathComponent]];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:URL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (pdfData) {
[pdfData writeToFile:pngFilePath atomically:YES];
controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:pngFilePath]];
controller.delegate = self;
CGRect rect = CGRectMake(0, 0, appDelegate.wVal, appDelegate.hVal);
[controller presentOptionsMenuFromRect:rect inView:self.view animated:YES];
}
});
});

AVAudioPlayer iOS no sound

Seems to be similar questions asked but none of the solutions seem to work for me. Cant for the life of me understand why my code doesnt work so here it is.
I dont get any errors but also get no sound.
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setVolume:100.0f];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
}
#end
*********vvvvvvvvv Amended Code that works vvvvvvvvv**********
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.audioPlayer setVolume:100.0f];
if (self.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[self.audioPlayer play];
}
#end
I am execute your code on my iPhone. It is work properly.Please Select a device and run your code. I hope it will execute properly with sound.
You got to segregate the functionalities..
Loading audio file in viewDidLoad and play it on play action, some thing like this
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
{
AVAudioPlayer *_audioPlayer;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:#"%#/sound.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playSoundTapped:(id)sender
{
// When button is tapped, play sound
[_audioPlayer play];
}

How to Open Youtube video in MPMoviePlayerController and Play it

i use this method before 1 time. but Now i can not get video from this URL that direct-play YouTube video in MPMoviePlayerController.
URL = http://www.youtube.com/watch?v=JPUWNcGDyvM&feature=player_embedded
- (void)viewDidLoad
{
player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.youtube.com/watch?v=JPUWNcGDyvM&feature=player_embedded"]]];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
//---play movie---
[player prepareToPlay];
[player pause];
player.view.frame = CGRectMake(0, 0, 320, 367);
[self.view addSubview:player.view];
[super viewDidLoad];
}
and My movieFinishedCallback is as Under ...
- (void) movieFinishedCallback:(NSNotification*) aNotification
{
player = [aNotification object];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
}
Create a custom uiwebview: please follow instruction
1) Create a interface .h file named "YouTubeView.h"
#import <UIKit/UIKit.h>
#interface YouTubeView : UIWebView
{
}
- (YouTubeView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame mimeSubType:(NSString *)mimeType;
#end
2) in to .m file
#import "YouTubeView.h"
#implementation YouTubeView
- (YouTubeView *)initWithStringAsURL:(NSString *)urlString frame:(CGRect)frame mimeSubType:(NSString *)mimeType
{
NSString *strMimeType;
if([mimeType length]>0)
{
strMimeType = mimeType;
}
else
{
strMimeType =#"x-shockwave-flash"; //#"x-shockwave-mp4";
}
if (self = [super init])
{
// Create webview with requested frame size
self = [[UIWebView alloc] initWithFrame:frame];
// HTML to embed YouTube video
NSString *youTubeVideoHTML = #"<html><head>\
<body style=\"margin:0\">\
<embed id=\"yt\" src=\"%#\" type=\"application/%#\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
// Populate HTML with the URL and requested frame size
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, urlString,strMimeType, frame.size.width, frame.size.height];
// Load the html into the webview
[self loadHTMLString:html baseURL:nil];
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
#end
3) Import the youtubeview file in the controller where you want to play you tube video and create uiview like the code below
YouTubeView *videoVw = [[YouTubeView alloc] initWithStringAsURL:[NSString
stringWithFormat:#"%#",strNormalVdoURL] frame:CGRectMake(0,0,320,480) mimeSubType:#"x-shockwave-
flash"];
[self.view addSubview:videoVw];
[videoVw release];
videoVw = nil;
Note: Video will play in device only so check in device
if possible to open your URL into UIWebview then take a button in your class and redirect it on to the WebsiteViewController class may be it helps u
WebsiteViewController.h ///----
#interface WebsiteViewController : UIViewController <UIWebViewDelegate>
{
IBOutlet UIWebView *webView;
}
#property(nonatomic,retain) IBOutlet UIWebView *webView;
WebsiteViewController.m ///---
-(void)viewDidLoad {
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:#"url"];
[self.webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
[request release];
}