Here is my code:
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
/* Add Content Loading Banner */
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[self.view addSubview:linkLoadView];
linkLoadView.alpha = 1.0;
}
/* Handle PDF Opening */
NSURL *url = [request URL];
NSString *urlString = [url absoluteString];
if([urlString rangeOfString:#".pdf"].location == NSNotFound){
return true;
} else {
NSURL *filePath = [NSURL URLWithString:urlString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:filePath];
[pdfViewer loadRequest:requestObj];
[self.view addSubview:topView];
[self.view addSubview:linkLoadView];
return false;
}
}
Basically what this does is detect a PDF link from within my UIWebView webView and loads it into an additional UIWebView pdfViewer (found on a View called topView). I then have a function as below:
- (void) webViewDidFinishLoad:(UIWebView *)theWebView{
//for webView
[UIView animateWithDuration:2
animations:^{
loadingView.alpha = 0.0;
linkLoadView.alpha = 0.0;
}
completion:^(BOOL finished){
[loadingView removeFromSuperview];
[linkLoadView removeFromSuperview];
}];
}
The above function doesn't fire at all for the pdfViewer web view, but does for the webView web view. How do I fix this?
Here is my setup settings for both webViews, on the viewDidLoad method.
//Options for
webView.delegate = self;
webView.scalesPageToFit = YES;
for (id subview in webView.subviews)
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
((UIScrollView *)subview).bounces = NO;
//Options for
pdfViewer.delegate = self;
pdfViewer.scalesPageToFit = YES;
for (id subview in pdfViewer.subviews)
if ([[subview class] isSubclassOfClass: [UIScrollView class]])
((UIScrollView *)subview).bounces = NO;
Make sure that the pdfViewer delegate is set properly and you will probably need to adjust the loading code.
- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
/* Add Content Loading Banner */
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[self.view addSubview:linkLoadView];
linkLoadView.alpha = 1.0;
}
/* Handle PDF Opening */
NSURL *url = [request URL];
NSString *urlString = [url absoluteString];
if(webview != pdfViewer)
{
if([urlString rangeOfString:#".pdf"].location == NSNotFound){
return true;
}
else {
NSURL *filePath = [NSURL URLWithString:urlString];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:filePath];
[pdfViewer loadRequest:requestObj];
[self.view addSubview:topView];
[self.view addSubview:linkLoadView];
return false;
}
}
return true;
}
Related
I am trying to load html page on a web view and i am having issue with scrolling the page.I tried to add javascript with overflow changed to scroll and no luck.What am i missing here?
-(WKWebView*) getWebViewForUrl:(NSString*)relativeUrl {
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 2, self.bounds.size.width-10, HEIGHT_WEBVIEW)];
webView.scrollView.scrollEnabled = TRUE;
webView.contentMode = UIViewContentModeScaleAspectFit;
webView.scrollView.bounces = NO;
webView.navigationDelegate = self;
NSString* endpoint = [NSUserDefaultsManager getObjectFromUserDeafults:PORTAL_ENDPOINT];
// NSString* url = [NSString stringWithFormat:#"%#/%#",endpoint,defect.html_description_source];
//NSString* url = #"http://www.yahoo.com";
NSString *url = [NSString stringWithFormat:#"%#%#.html?auth_token=%#&device_id=%#", endpoint, relativeUrl, [[NSUserDefaults standardUserDefaults] objectForKey:#"accessToken"], [DeviceManager getDeviceID]];
NSLog(#"the html %#",url);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
return webView;
}
- (void)webViewDidFinishLoad:(WKWebView *)webView {
NSString *jsString = #"document.querySelectorAll('*[style]').forEach(el => el.style.overflow = 'scroll');";
[webView evaluateJavaScript:jsString completionHandler:nil];
[self hideLoadingScreen];
}
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.
i have tried this code but it shows error like
Warning: Attempt to present <_UIDocumentActivityViewController:
0x16acdc00> on which is already
presenting <_UIDocumentActivityViewController: 0x16ae4800>
how to solve this??
-(IBAction)saveToInstagram:(id)sender {
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Test.ig"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
NSLog(#"JPG path %#", jpgPath);
NSLog(#"URL Path %#", igImageHookFile);
self.docFile.UTI = #"com.instagram.photo";
self.docFile = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.docFile=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://media?id=MEDIA_ID"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
}
else {
NSLog(#"No Instagram Found");
}
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
- (void)documentInteractionControllerWillPresentOpenInMenu:(UIDocumentInteractionController *)controller {
}
The problem is that while the first docfile is being presented you try to present the second one
// First presentation
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://media?id=MEDIA_ID"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
// Second presentation
[self.docFile presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
}
I don't really understand why do you need to use the same method twice, but if you really do, then for the first presentation use animated: NO. I would suggest some kind of completion code block, but it appears that there is no such method for UIDocumentInteractionController
Don't forget to add instagram in you plist array with key: LSApplicationQueriesSchemes.
#property (nonatomic, strong) UIDocumentInteractionController *docIC;
- (void)sharePhoto:(UIImage *)image caption:(NSString *)caption
{
NSURL *instagramURL = [NSURL URLWithString:#"instagram://"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
NSString *imgPath = [TUtil documentPath:#"Image.igo"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
[data writeToFile:imgPath atomically:YES];
NSURL *igImageHookFile = [NSURL fileURLWithPath:imgPath];
self.docIC = [UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.docIC setDelegate:self];
[self.docIC setUTI:#"com.instagram.exclusivegram"];
// Subject
[self.docIC setName:[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleDisplayName"]];
//http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing
//self.docIC.annotation = [NSDictionary dictionaryWithObjectsAndKeys:caption, #"InstagramCaption", nil];
[self.docIC presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
else
{
NSString *iTunesLink = #"itms-apps://itunes.apple.com/app/id389801252?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
}
}
I'm using a UIPageViewController to display items from a JSON file. It works fine except for the first page which displays nothing on loading, but if I come back, it works.
Code is as follows:
#import "SJPagesViewController.h"
#import "SJChildViewController.h"
#interface SJPagesViewController ()
#end
#implementation SJPagesViewController
#synthesize urlToFollow, data,articlesArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
...
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
CGFloat window_height = ([self window_height]-30.0);
CGFloat window_width = [self window_width];
CGRect pageFrame = CGRectMake(0.0f, 0.0f,window_width , window_height);
self.pageController.dataSource = self;
[[self.pageController view] setFrame:pageFrame];
SJChildViewController *initialViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:self.pageController];
[[self view] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
//Download JSON
NSError *error=nil;
NSURL *url = [NSURL URLWithString:urlToFollow];
data = [NSData dataWithContentsOfURL: url options:NSDataReadingMappedIfSafe error:&error];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *response = [dictionary objectForKey:#"items"];
articlesArray = [[NSArray alloc] initWithArray:response];
//NSLog(#"articlesArray = %#", articlesArray);
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSUInteger index = [(SJChildViewController *)viewController index];
if (index == 0) {
return nil;
}
index--;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
NSUInteger index = [(SJChildViewController *)viewController index];
index++;
if (index == articlesArray.count) {
return nil;
}
return [self viewControllerAtIndex:index];
}
- (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
- (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (SJChildViewController *)viewControllerAtIndex:(NSUInteger)index {
SJChildViewController *childViewController = [[SJChildViewController alloc] initWithNibName:#"SJChildViewController" bundle:nil];
childViewController.index = index;
childViewController.arrayCount = self.articlesArray.count;
childViewController.model = [[self.articlesArray objectAtIndex:index]objectForKey:#"modelo"];
childViewController.price = [[self.articlesArray objectAtIndex:index]objectForKey:#"precio"];
childViewController.make = [[self.articlesArray objectAtIndex:index]objectForKey:#"marca"];
childViewController.imageUrl = [[self.articlesArray objectAtIndex:index]objectForKey:#"photoUrl"];
return childViewController;
}
- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController {
// The number of items reflected in the page indicator.
if (articlesArray.count >5) {
return 5;
}else return [articlesArray count];
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
// The selected item reflected in the page indicator.
return 0;
}
#end
And ChildViewController to display items:
#implementation SJChildViewController
#synthesize activityIndicator,imageUrl,price,model,make;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
....
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Activity indicator
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
[self.view addSubview: activityIndicator];
[activityIndicator startAnimating];
}
-(void)viewDidAppear:(BOOL)animated{
self.scrrenNumber.text = [NSString stringWithFormat:#"Artículo %ld de %ld", ((long)self.index+1), (long)self.arrayCount];
self.lblMake.lineBreakMode = NSLineBreakByWordWrapping;
self.lblMake.text = [NSString stringWithFormat:#"%#",make];
//Donload image
//Download image from url
NSURL *url_1= [NSURL URLWithString:imageUrl];
NSURLRequest *request_1 = [NSURLRequest requestWithURL:url_1];
[NSURLConnection sendAsynchronousRequest:request_1
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
UIImage *img = [UIImage imageWithData:data];
[self.articleImage performSelectorOnMainThread:#selector(setImage:) withObject:img waitUntilDone:YES];
}];
//Activity indicator
self.lblPrice.text = [NSString stringWithFormat:#"%#",price];
self.lblModel.lineBreakMode = NSLineBreakByWordWrapping;
self.lblModel.text = [NSString stringWithFormat:#"%#",model];
[activityIndicator stopAnimating];
}
How can I make it work from the first moment?
Luis, I don't have access to xcode right now but it appears your issue is that you are instantiating childViewController while articlesArray is empty.
In viewDidLoad you are downloading your json file and populating articlesArray after you call your helper method viewControllerAtIndex.
Try downloading your json file and populating the array first like you have here.
//Download JSON
NSError *error=nil;
NSURL *url = [NSURL URLWithString:urlToFollow];
data = [NSData dataWithContentsOfURL: url options:NSDataReadingMappedIfSafe error:&error];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *response = [dictionary objectForKey:#"items"];
articlesArray = [[NSArray alloc] initWithArray:response];
Then create your pageViewController and populate it like you did here.
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
CGFloat window_height = ([self window_height]-30.0);
CGFloat window_width = [self window_width];
CGRect pageFrame = CGRectMake(0.0f, 0.0f,window_width , window_height);
self.pageController.dataSource = self;
[[self.pageController view] setFrame:pageFrame];
SJChildViewController *initialViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
[self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
[self addChildViewController:self.pageController];
[[self view] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
I would like to have both movies playing at once in their two separate sub views. They are both accessing different media.
this is on an ipad with a superview and two little views 320x240 right by eachother on the xib.
-(IBAction)playLeft:(id)sender{
if ([self.playerRight playbackState] == MPMoviePlaybackStatePlaying);
[self.playerRight stop];
[self.playerLeft play];
}
-(IBAction)playRight:(id)sender{
if ([self.playerLeft playbackState] == MPMoviePlaybackStatePlaying);
[self.playerLeft stop];
[self.playerRight play];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
self.playerLeft = [[MPMoviePlayerController alloc] init];
self.playerLeft.contentURL = [self movieURL];
NSLog(#"self.playerLeft %#", self.playerLeft);
self.playerRight = [[MPMoviePlayerController alloc] init];
self.playerRight.contentURL = [self movieURL2];
NSLog(#"self.playerRight %#", self.playerRight);
// START_HIGHLIGHT
self.playerLeft.view.frame = self.leftView.bounds;
self.playerLeft.view.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
self.playerRight.view.frame = self.rightView.bounds;
self.playerRight.view.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
[self.rightView addSubview:playerRight.view];
[self.leftView addSubview:playerLeft.view];
//[self.playerRight play];
//[self.playerLeft play];
//[self clickedOpenMovie:nil];
}
-(NSURL *)movieURL
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath =
[bundle
pathForResource:#"720p5994-prores-hq_iPhone_320x240 two"
ofType:#"m4v"];
//NSString *moviePath = [NSString stringWithFormat:#"http://localhost:1935/live/aStream/playlist.m3u8"];
if (moviePath) {
return [NSURL fileURLWithPath:moviePath];
//return [NSURL URLWithString:moviePath];
} else {
return nil;
}
}
-(NSURL *)movieURL2
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath =
[bundle
pathForResource:#"720p5994-prores-hq_iPhone_320x240"
ofType:#"m4v"];
if (moviePath) {
return [NSURL fileURLWithPath:moviePath];
} else {
return nil;
}
}
so the problem is that somewhere in the background MPMoviePlayerController responds to notifications and turns itself off if another MPMoviewPlayerController broadcasts that its going to start. Thus one can not have multiple MPMoviePlayerControllers playing at the same time.
you can see this by printing out the MPMoviePlayerPlaybackStateDidChangeNotification