UIPageViewController NavigationItem issues due to viewControllerBeforeViewController - ios

So I have a view pager that is suppose to allow users to slide through photos the way a user would expect to slide through a album of photos , but the issue comes in when a user slides around and trys to press the "share" button in the navigation bar. It works fine if a user just opens a photo from the album and never trys to slide right or left , but if they do try to slide in either direction and then try to save the photo they have slid to it returns the photo after the photo the user is currently viewing. Ive eliminated this down to something having to do with viewControllerBeforeViewController and viewControllerAfterViewController being called AFTER the current viewcontroller s callehere is my class:
#import "APPChildViewController.h"
#import "CommentsViewController.h"
#import "ViewPhotosPagerVC.h"
#interface ViewPhotosPagerVC ()
#end
#implementation ViewPhotosPagerVC
- (void)viewDidLoad {
[super viewDidLoad];
// [self.navigationController setNavigationBarHidden:YES animated:YES];
self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageController.dataSource = self;
[[self.pageController view] setFrame:CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height)];
CommentsViewController *initialViewController = [self viewControllerAtIndex:0];
NSDictionary *dict =[_photoArray objectAtIndex:_startingIndex];
NSLog(#"DICT:%#",dict);
NSString *msg_id=[dict objectForKey:#"msg_id"];
NSLog(#"MSG_ID:%#",msg_id);
initialViewController.msg_id=msg_id;
initialViewController.navItem=self.navigationItem;
initialViewController.delegate=self;
initialViewController.theIndex=_startingIndex;
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];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CommentsViewController *)viewControllerAtIndex:(NSUInteger)index {
NSLog(#"CommentVC_INDEX:%zd",index);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.navItem=self.navigationItem;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSLog(#"BEFORE_PAGEVIEWCONTROL_CALLED");
NSUInteger index = [(CommentsViewController *)viewController theIndex];
if (index == 0) {
NSInteger newIndex=_photoArray.count;
newIndex--;
return [self viewControllerAtIndex:newIndex];
}
// Decrease the index by 1 to return
index--;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
NSLog(#"AFTER_PAGEVIEWCONTROL_CALLED");
NSUInteger index = [(CommentsViewController *)viewController theIndex];
index++;
if(_photoArray.count<=index){
index=0;
}
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
CommentsViewController *childViewController=[storyboard instantiateViewControllerWithIdentifier:#"pagerPhotoComments"];
if(_photoArray<=index){
index=0;
}
NSDictionary *dict =[_photoArray objectAtIndex:index];
NSString *msg_id=[dict objectForKey:#"msg_id"];
childViewController.msg_id=msg_id;
childViewController.delegate=self;
childViewController.theIndex = index;
return childViewController;
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)sharePhoto:(UIImage *)shareImage andText:(NSString *)shareText withDict:(NSDictionary *)dict{
//NSLog(#"SHARE_IMG_UPDATE_DICT:%#",dict);
NSString *ALBUM_ID= [dict objectForKey:#"ALBUM_ID"];
NSString *combinedShareText;
if(![ALBUM_ID isEqualToString:#"0"]){
NSArray *album_array=[dict objectForKey:#"album_info"];
NSDictionary *album_dict=[album_array objectAtIndex:0];
//NSLog(#"ALBUM_DICT:%#",album_dict);
NSString *album_title=[album_dict objectForKey:#"title"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *first_name= [defaults objectForKey:#"first_name"];
NSString *album_photo_count=[dict objectForKey:#"album_img_count"];
combinedShareText= [NSString stringWithFormat:#"%# shared a photo w. you from the event album:%#(%# photos) ~view the rest of this album on for IOS",first_name, album_title,album_photo_count];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
}else{
NSString *first_name=[dict objectForKey:#"first_name"];
NSString *last_name=[dict objectForKey:#"last_name"];
NSString *message =[dict objectForKey:#"message"];
NSString *created_string=[dict objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
combinedShareText= [NSString stringWithFormat:#"'%#'~ posted by %# %# %# | You'll thank me later: www.buhz.com",message,first_name,last_name,ago];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
}
if(![ALBUM_ID isEqualToString:#"0"]){
UIImage *backgroundImage = shareImage;
UIImage *watermarkImage = [UIImage imageNamed:#"ios_watermark_logo.png"];
UIGraphicsBeginImageContext(backgroundImage.size);
[backgroundImage drawInRect:CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height)];
[watermarkImage drawInRect:CGRectMake(backgroundImage.size.width - 240, backgroundImage.size.height - 110, 230, 100)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText,result]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}else{
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText,shareImage]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
}
-(UIImage*) drawText:(NSString*) text
inImage:(UIImage*) image
atPoint:(CGPoint) point
{
NSMutableAttributedString *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#",text]];
// text color
[textStyle addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, textStyle.length)];
// text font
[textStyle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, textStyle.length)];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width-(point.x*2), image.size.height);
[[UIColor whiteColor] set];
// add text onto the image
[textStyle drawInRect:CGRectIntegral(rect)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)shareUpdate:(NSString *)shareText withDict:(NSDictionary *)dict{
NSLog(#"SHARE_TEXT_UPDATE_DICT:%#",dict);
NSString *first_name=[dict objectForKey:#"first_name"];
NSString *last_name=[dict objectForKey:#"last_name"];
NSString *message =[dict objectForKey:#"message"];
NSString *created_string=[dict objectForKey:#"created"];
double created_double = created_string.doubleValue;
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:created_double];
NSString *ago = [date timeAgo];
NSString *combinedShareText= [NSString stringWithFormat:#"'%#'~ posted by %# %# %# | Join me on www..com",message,first_name,last_name,ago];
NSLog(#"SHARE_TEXT:%#",combinedShareText);
UIActivityViewController *controller =
[[UIActivityViewController alloc]
initWithActivityItems:#[combinedShareText]
applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
#end

Related

iOS 11 only crash issue - when I tap a tab bar App is crashing

I am getting following crash error when I tap a particular tab bar only from hometabviewcontroller. This Happens only in iOS 11. Please help me to solve this issue.
2017-10-23 16:48:57.000890+0400 FixtrProvider[2520:910402] desc: -[UIView refreshControl]: unrecognized selector sent to instance 0x10af090d0
2017-10-23 16:48:57.001223+0400 FixtrProvider[2520:910402] name: NSInvalidArgumentException
2017-10-23 16:48:57.001308+0400 FixtrProvider[2520:910402] user info: (null)
2017-10-23 16:48:57.001441+0400 FixtrProvider[2520:910402] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView refreshControl]: unrecognized selector sent to instance 0x10af090d0'
Following is the whole Page of my HomeTabView Controller according to the request.
#interface HomeTabBarController ()
{
ChatSocketIOClient *socket;
}
#property (strong, nonatomic) UIButton *onTheJobOffTheJobButton;
#property (strong, nonatomic) NSString *status;
#property LocationTracker * locationTracker;
#property (nonatomic) NSTimer* locationUpdateTimer;
#end
#implementation HomeTabBarController
- (void)viewDidLoad {
[super viewDidLoad];
// Crash bug fixing
self.automaticallyAdjustsScrollViewInsets = NO;
if (!socket) {
socket =[ChatSocketIOClient sharedInstance];
}
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self tabbarImages];
}
-(void)tabbarImages
{
NSString *homeunselect;
NSString *homeselect;
NSString *historyunselect;
NSString *historyselect;
NSString *scheduleunselect;
NSString *scheduleselect;
NSString *earnunselect;
NSString *earnselect;
NSString *proilfeunselect;
NSString *profileselect;
UITabBar *tabBar = self.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
if ([UIScreen mainScreen].bounds.size.height <= 568) {
homeunselect = #"provider_popup_home_btn";
homeselect = #"provider_popup_home_btn_selector";
historyunselect = #"provider_popup_history_btn";
historyselect = #"provider_popup_history_btn_selector";
scheduleunselect = #"provider_popup_schedule_btn";
scheduleselect = #"provider_popup_selector_btn_selector";
earnunselect = #"provider_popup_earnings_btn";
earnselect = #"provider_popup_earnings_btn_selector";
proilfeunselect = #"provider_popup_profile_btn";
profileselect = #"provider_popup_profile_btn_selector";
}else if ([UIScreen mainScreen].bounds.size.height == 667){
homeunselect = #"6provider_popup_home_btn";
homeselect = #"6provider_popup_home_btn_selector";
historyunselect = #"6provider_popup_history_btn";
historyselect = #"6provider_popup_history_btn_selector";
scheduleunselect = #"6provider_popup_schedule_btn";
scheduleselect = #"6provider_popup_selector_btn_selector";
earnunselect = #"6provider_popup_earnings_btn";
earnselect = #"6provider_popup_earnings_btn_selector";
proilfeunselect = #"6provider_popup_profile_btn";
profileselect = #"6provider_popup_profile_btn_selector";
}else if ([UIScreen mainScreen].bounds.size.height >= 736){
homeunselect = #"6pprovider_popup_home_btn";
homeselect = #"6pprovider_popup_home_btn_selector";
historyunselect = #"6pprovider_popup_history_btn";
historyselect = #"6pprovider_popup_history_btn_selector";
scheduleunselect = #"6pprovider_popup_schedule_btn";
scheduleselect = #"6pprovider_popup_selector_btn_selector";
earnunselect = #"6pprovider_popup_earnings_btn";
earnselect = #"6pprovider_popup_earnings_btn_selector";
proilfeunselect = #"6pprovider_popup_profile_btn";
profileselect = #"6pprovider_popup_profile_btn_selector";
}
tabBarItem1.selectedImage = [[UIImage imageNamed:homeselect] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.image = [[UIImage imageNamed:homeunselect] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.selectedImage = [[UIImage imageNamed:historyselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.image = [[UIImage imageNamed:historyunselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.selectedImage = [[UIImage imageNamed:scheduleselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.image = [[UIImage imageNamed:scheduleunselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem4.selectedImage = [[UIImage imageNamed:earnselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem4.image = [[UIImage imageNamed:earnunselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem5.selectedImage = [[UIImage imageNamed:profileselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem5.image = [[UIImage imageNamed:proilfeunselect]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
}
-(void)viewWillAppear:(BOOL)animated{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"OnChatController"];
[[NSUserDefaults standardUserDefaults]synchronize];
self.tabBarController.tabBar.hidden = NO;
[UIApplication sharedApplication].idleTimerDisabled = YES;
}
-(void)viewDidDisappear:(BOOL)animated{
}
This App getting crashed when I tapped tabbar-4 in iOS 11 only. I don't understand what's the wrong with my code. I didn't get any code related to refreshController either on Hometabviewcontroller or accountscontroller. but I got the following when I search entire code base.
- (void)refresh:(UIRefreshControl *)refreshControl
{
[refreshControl endRefreshing];
}
Following is the viewloads code of the particular tabview controller.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_paymentLogs.selected = YES;
self.automaticallyAdjustsScrollViewInsets = NO;
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName: UIColorFromRGB(0XfEAA26)};
}
-(void)getFinancialData{
UIWindow *window = [[UIApplication sharedApplication]keyWindow];
[[ProgressIndicator sharedInstance] showPIOnWindow:window withMessge:NSLocalizedString(#"Loading...",#"Loading...")];
_pastCycle = [[NSMutableArray alloc]init];
NSDictionary *dict =#{
#"ent_sess_token": [[NSUserDefaults standardUserDefaults] objectForKey:KDAcheckUserSessionToken],
#"ent_dev_id": [[NSUserDefaults standardUserDefaults] objectForKey:kPMDDeviceIdKey],
#"ent_date_time":[Helper getCurrentDateTime],
#"ent_pro_id": [[NSUserDefaults standardUserDefaults] objectForKey:#"ProviderId"]
};
NetworkHandler *handler =[NetworkHandler sharedInstance];
[handler composeRequestWithMethod:#"GetFinancialData"
paramas:dict
onComplition:^(BOOL succeeded, NSDictionary *response) {
if (succeeded) {
_pastCycle = [response[#"pastCycle"] mutableCopy];
_currentCycle = response[#"currentCycle"];
NSLog(#"financial data %#",response);
[self.currentTableView reloadData];
[self.pastTableView reloadData];
[[ProgressIndicator sharedInstance] hideProgressIndicator];
}
}];
}
-(void)viewWillAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(userSessionTokenExpire) name:#"HandleAcceptAndRejectFromAdmin" object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"HandleAcceptAndRejectFromAdmin" object:nil];
}
-(void)userSessionTokenExpire{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:KDAcheckUserSessionToken];
[[NSUserDefaults standardUserDefaults] synchronize];
ProgressIndicator *pi = [ProgressIndicator sharedInstance];
[pi hideProgressIndicator];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
#"Main" bundle:[NSBundle mainBundle]];
iServeSplashController *splah = [storyboard instantiateViewControllerWithIdentifier:#"splash"];
self.navigationController.viewControllers = [NSArray arrayWithObjects:splah, nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)viewDidAppear:(BOOL)animated {
_pastCycle = [[NSMutableArray alloc]init];
[self getFinancialData];
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(accountDeactivated) name:#"accountDeactivated" object:nil];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
You can track where the unrecognized selector sent to instance comes from. Something in your code is calling it.
Do a text search in hometabviewcontroller or entire project for refreshControl and see where and what is calling it and make sure it's what you want.
If that does not help we need more code (preferably hometabviewcontroller) to help you.

UIPageViewController does not show its view controllers views

I have a UIPageViewController in a UIViewController , I am having a problem where the pageviewcontroller's inner view are not shown [Although I am sure they are loaded from the server]!
Some helpful notes:
UIPageViewController (called :pageController)
Outer UIViewController (called :OfferDetailsViewController)
each viewController inside the pageController is of type OfferBannerPageViewController
Here is my code related to the problem , Please ask for any other blocks of code if you think it will help finding the problem source
some of :OfferDetailsViewController.m :
- (void)viewDidLoad {
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
if(_offerId)
{
_offer = [[Offer alloc]init];
[delegate setUpAConnectionToGetADetailedOffer:_offerId];
//first: load the offer
[self loadOffer];
[self startTimer];
}
}
-(void) loadOffer{
NSMutableString * pathPattern = [NSMutableString stringWithString: #"api/Offers/"];
[pathPattern appendString:_offerId];
[[RKObjectManager sharedManager]getObjectsAtPath:pathPattern parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if(mappingResult){
_offer = (Offer *)[mappingResult.array firstObject];
//second load the offer banners images
[self setOfferView];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadOfferBanners];
});
}else{
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
}
-(void)loadOfferBanners {
_offer.OfferPannerImagesObjects = [[NSMutableArray alloc]init];
for(int index = 0 ; index<_offer.OfferPannerImages.count ;index++){
NSURL *imageURL =[NSURL URLWithString:_offer.OfferPannerImages[index]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
//[UIImage imageWithData:imageData];
if(image){
[_offer.OfferPannerImagesObjects addObject: image];
}
}
if(_offer.OfferPannerImagesObjects.count>0){
[self setUpOfferBanners];
}
}
-(void)setUpOfferBanners {
self.pageController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageController.dataSource = self;
CGRect rect = [self.pagesView bounds];
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
OfferBannerPageViewController * initialBanner = [self viewControllerAtIndex: 0];
[self.pageController setViewControllers:[NSArray arrayWithObjects:initialBanner, nil] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil ];
[self addChildViewController:self.pageController];
[[self pagesView] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
self.pagesView.clipsToBounds=YES;
self.pagesView.layer.cornerRadius= 6;
}
here is the ViewControllerAtIndex method I debug it and found that index is always whereas when I hover in it after stopping at a break point I see its value as 0!
- (OfferBannerPageViewController *)viewControllerAtIndex:(NSUInteger)index {
OfferBannerPageViewController *offerBannerPageViewController = [[OfferBannerPageViewController alloc] initWithNibName:#"OfferBannerPageViewController" bundle:nil];
offerBannerPageViewController.bannerView = _offer.OfferPannerImagesObjects[index];
offerBannerPageViewController.index = [NSNumber numberWithLong:(long)index];
NSLog(#"____________________ [INDEX = %ld] ___________________",(long)index);
[offerBannerPageViewController.bannerView setImage:_offer.OfferPannerImagesObjects[index]];
return offerBannerPageViewController;
}
any help will be extremely appreciated, Thank you.
update
- (NSInteger)presentationCountForPageViewController: (UIPageViewController*)pageViewController {
// The number of items reflected in the page indicator.
return [_offer.OfferPannerImages count];
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
// The selected item reflected in the page indicator.
return 0;
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index >= _offer.OfferPannerImagesObjects.count){
return nil;
}
index ++;
return [self viewControllerAtIndex:index];
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index == 0)
return nil;
index--;
return [self viewControllerAtIndex:index];
}
update 2: OfferBannerPageViewController.h
#interface OfferBannerPageViewController : UIViewController
#property (strong,nonatomic) NSNumber * index;
#property (strong,nonatomic)IBOutlet UIImageView * bannerView;
#end
Not sure about this, but maybe you should use autoresizing masks to make sure OfferBannerPageViewController's view resizes width and height along with the superview. It might happen that when you set the frame of pageController.view based on bounds of superview, the bounds are 0 width and height and then doesn't resize.
So try:
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
[[self.pageController view] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Have you implemented presentationCountForPageViewController, presentationIndexForPageViewController, viewControllerBeforeViewController and viewControllerAfterViewController methods?
Please, show them.

UIActivityViewController local Image

How do i share image from imageView. Here is my code for imageView:
UIImage *myImage = [UIImage imageNamed:[NSString stringWithFormat:
#"image%d.jpg", i]];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
[myImageView setFrame:CGRectMake(xOrigin, 0,
self.view.frame.size.width,
self.view.frame.size.height)];
_postImage.image = myImage;
}
- (IBAction)shareButtonPressed:(id)sender {
NSArray *activityItems;
if (_postImage.image != nil) {
activityItems = #[_postImage.image];
}
UIActivityViewController *activityVC = [[UIActivityViewController alloc]
initWithActivityItems:activityItems
applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];
}
I get error - No share action available.Thanks in advance.
You probably forgot to initialize _postImage. Try to replace:
_postImage.image = myImage;
with:
_postImage = [[UIImageView alloc] initWithImage:myImage];
To get your image on activityViewController you need to create your custom Activity with that image which you want to show. Following are step's to create and show your custom activity with your image.
1.Create a new file subclassing UIActivity namely, "CustomActivity". Then in the CustomActivity.m file you need to write down following method.
- (NSString *)activityType {
return #"yourappname.Review.App"; //type
}
- (NSString *)activityTitle {
return #"Review App"; //title for activity
}
- (UIImage *)activityImage {
return [UIImage imageNamed:#"Icon.png"]; //image
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems {
NSLog(#"%s", __FUNCTION__);
return YES;
}
- (void)prepareWithActivityItems:(NSArray *)activityItems {
NSLog(#"%s",__FUNCTION__);
}
- (UIViewController *)activityViewController {
NSLog(#"%s",__FUNCTION__);
return nil;
}
- (void)performActivity {
//What your cust activity woudl perform when user tap onto it.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.apple.com/"]];
[self activityDidFinish:YES];
}
Then in your mainVC you could import this class and add below lines to use this custom activity.
NSString *textItem = #"provide your string";
UIImage *imageToShare = [UIImage imageNamed:#"Icon.png"]; //Provide your activity image
NSArray *items = [NSArray arrayWithObjects:textItem,imageToShare,nil];
custAct = [[CustomActivity alloc]init];
UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:#[custAct]];
[self presentViewController:controller animated:YES completion:nil];
Now you would be able to see your image with activity that you want to perform.
If my understanding is wrong, do correct me.

icon grey custom UIActivityViewController

I create a custom UIActivityViewController but when I load the icons that I do makes me see gray and you are pretty much loaded correctly, someone did it happen? how you have remedied?
ActivityViewCustomActivity *ca = [[ActivityViewCustomActivity alloc]init];
ca.service = #"avanti";
ca.image = image;
ca.act = #"com.avanti.app";
ActivityViewCustomActivity *fa = [[ActivityViewCustomActivity alloc]init];
fa.service = #"facebook";
fa.image = image;//[UIImage imageNamed:#"icon-facebook.jpg"];
fa.act = #"com.facebook.app";
ActivityViewCustomActivity *tw = [[ActivityViewCustomActivity alloc]init];
tw.service = #"twitter";
tw.image = image;
tw.act = #"com.twitter.app";
UIActivityViewController *activityVC =
[[UIActivityViewController alloc] initWithActivityItems:items
applicationActivities:#[ca,fa,tw]];
activityVC.excludedActivityTypes = #[UIActivityTypePostToTwitter,UIActivityTypePostToFacebook,UIActivityTypeMail,UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeSaveToCameraRoll];
activityVC.completionHandler = ^(NSString *activityType, BOOL completed)
{
if ([activityType isEqualToString:#"com.avanti.app"]) {
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
NSString *name = [q objectAtIndex:indexPath.row];
UIStoryboard *storyboar = [UIStoryboard storyboardWithName:#"Main_iPhone" bundle:nil];
ListViewController *list = [storyboar instantiateViewControllerWithIdentifier:#"ListViewController"];
list.ide = ide;
list.canale = name;
[self.navigationController pushViewController:list animated:YES];
}
else if ([activityType isEqualToString:#"com.facebook.app"]){
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
UIActionSheet *action = [[UIActionSheet alloc]initWithTitle:#"Facebook" delegate:self cancelButtonTitle:#"Annulla" destructiveButtonTitle:#"Vuoi pubblicarlo ?" otherButtonTitles:#"ok", nil];
action.actionSheetStyle = UIActionSheetStyleDefault;
[self actionSheet:action clickedButtonAtIndex:2];
[action showInView:[self.view window]];
}
else if ([activityType isEqualToString:#"com.twitter.app"]){
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
[self shareTwitter];
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
NSLog(#"ipad");
}
else
{
[self presentViewController:activityVC animated:YES completion:nil];
}
}
e l'activity è così
- (NSString *)activityType
{
return act;
}
- (NSString *)activityTitle
{
return service;
}
- (UIImage *)activityImage
{
// CGRect rect = CGRectMake(0.0f, 0.0f, 85.0f, 85.0f);
// UIGraphicsBeginImageContext(rect.size);
//
// rect = CGRectInset(rect, 15.0f, 15.0f);
// UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10.0f];
// [path stroke];
//
// rect = CGRectInset(rect, 0.0f, 10.0f);
// [service drawInRect:rect withFont:[UIFont fontWithName:#"Futura" size:15.0f] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
//
// UIImage *imag = UIGraphicsGetImageFromCurrentImageContext();
//
// UIGraphicsEndImageContext();
// //UIImage *ima = [UIImage imageNamed:#"facebook.jpg"];
// return imag;
UIImage *ima = [UIImage imageNamed:#"Icon_Facebook.png"];
return ima;
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
// {
// return [UIImage imageNamed:#"Facebook_43x43"];
// }
// else
// {
// return image;
// }
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
NSLog(#"%s", __FUNCTION__);
for (id obj in activityItems) {
if ([obj isKindOfClass:[NSString class]]) {
return YES;
}
}
return NO;
}
- (void)prepareWithActivityItems:(NSArray *)activityItems
{
NSLog(#"%s",__FUNCTION__);
}
- (UIViewController *)activityViewController
{
NSLog(#"%s",__FUNCTION__);
return nil;
}
- (void)performActivity
{
// This is where you can do anything you want, and is the whole reason for creating a custom
// UIActivity
[self activityDidFinish:YES];
}
+ (UIActivityCategory)activityCategory
{
return UIActivityCategoryShare;
}
and the screenshot is here http://i57.tinypic.com/332vtjo.png
and .h is
#import <UIKit/UIKit.h>
#interface ActivityViewCustomActivity : UIActivity
#property (nonatomic, strong) NSString *service;
#property (nonatomic, strong) UIImage *image;
#property (nonatomic, strong) NSString *act;
- (NSString *)activityType;
- (NSString *)activityTitle;
- (UIImage *)activityImage;
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems;
- (void)prepareWithActivityItems:(NSArray *)activityItems;
- (UIViewController *)activityViewController;
- (void)performActivity;
+ (UIActivityCategory)activityCategory;
#end
Try to add _ to your activityImage function
Something like
- (UIImage *)_activityImage
{
return [UIImage imageNamed:#"Icon_Facebook.png"];
}

UITableViewController with UIPageViewController in UIViewController

What I m Thinking to do is ? there is one MainViewController in which there are two UIViews one loaded UITableViewController and other UIPageViewController.
In TableViewController, there are list of pdf's names. But when i click of the pdf list, it does not loads the PageViewController with new pdf in context.
Pdf file names are store in .plist file, Pdfs are fetch from NSBundle or NSDocumentDirectory
In TableViewController
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Play *play = (Play *)[[self.sectionInfoArray objectAtIndex:indexPath.section] play];
Quotation *qute = [play.Details objectAtIndex:indexPath.row];
if ([qute.Key isEqualToString:#"ABC"])
{
AppDelegate *app = [[UIApplication sharedApplication]delegate];
app.strpdfname = qute.Value;
MiddleViewController *mid = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
ContentViewController *cvc = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
[mid viewDidLoad];
[cvc viewDidLoad];
}
else
{
MainViewController *vc = [[MainViewController alloc] initWithNibName:#"MainViewController" bundle:nil];
[vc viewDidLoad];
}
}
In PageViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.modelArray = [[NSMutableArray alloc] init];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
NSURL *targetURL = [NSURL fileURLWithPath:path];
originalPDF = CGPDFDocumentCreateWithURL((__bridge CFURLRef)targetURL);
numberOfPages = CGPDFDocumentGetNumberOfPages(originalPDF);
for (int index = 0; index < numberOfPages ; index++)
{
[self.modelArray addObject:[NSString stringWithFormat:#"%d",index]];
}
self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageViewController.delegate = self;
self.pageViewController.dataSource = self;
contentViewController = [[ContentViewController alloc] initWithNibName:#"ContentViewController" bundle:nil];
contentViewController.labelContents = [self.modelArray objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:contentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
CGRect pageViewRect = self.view.frame;
pageViewRect = CGRectInset(pageViewRect, 0.0, 0.0);
self.pageViewController.view.frame = pageViewRect;
self.view.gestureRecognizers = self.pageViewController.gestureRecognizers;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerBeforeViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == 0)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex - 1];
return contentViewController;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController
viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger currentIndex = [self.modelArray indexOfObject:[(ContentViewController *)viewController labelContents]];
if(currentIndex == self.modelArray.count-1)
{
return nil;
}
contentViewController = [[ContentViewController alloc] init];
contentViewController.labelContents = [self.modelArray objectAtIndex:currentIndex + 1];
return contentViewController;
}
- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController
spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation
{
UIViewController *currentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSArray *viewControllers = [NSArray arrayWithObject:currentViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:NULL];
self.pageViewController.doubleSided = NO;
return UIPageViewControllerSpineLocationMin;
}
In ContentViewController of PageViewController
-(UIImage*) imageFromPDF:(CGPDFDocumentRef)pdf withPageNumber:(NSUInteger)pageNumber withScale:(CGFloat)scale
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf,pageNumber);
CGRect tmpRect = CGPDFPageGetBoxRect(pdfPage,kCGPDFMediaBox);
CGRect rect = CGRectMake(tmpRect.origin.x,tmpRect.origin.y,tmpRect.size.width*scale,tmpRect.size.height*scale);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context,-50,rect.size.height-30);
CGContextScaleCTM(context,scale,-scale);
CGContextDrawPDFPage(context,pdfPage);
UIImage* pdfImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return pdfImage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *app = [[UIApplication sharedApplication] delegate];
self.pdfName = app.strpdfname;
i = [labelContents intValue];
NSString *path = [[NSBundle mainBundle] pathForResource:pdfName ofType:nil];
if (i!=0)
{
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path]);
UIImage *img = [[UIImage alloc] init];
img = [self imageFromPDF:pdf withPageNumber:i withScale:1];
UIImageView *imgview1 = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgview1];
}
else
{
UIImage *imgmain = [UIImage imageNamed:#"Diary4.png"];
UIImageView *imgvmain = [[UIImageView alloc] initWithImage:imgmain];
imgvmain.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y,580,self.view.frame.size.height);
[self.view addSubview:imgvmain];
}
}
In MainViewController
-(void)viewDidload
{
leftView = [[UIView alloc] initWithFrame:CGRectMake(5,25, 200,715)];
leftView.backgroundColor = [UIColor clearColor];
tvc = [[TableViewController alloc] initWithStyle:UITableViewStylePlain];
tvc.plays = self.plays;
tvc.view.frame = leftView.frame;
leftView.clipsToBounds = YES;
[leftView addSubview:tvc.view];
[self.view addSubview:leftView];
middleView = [[UIView alloc] initWithFrame:CGRectMake(107, 30, 575, 670)];
mvc = [[MiddleViewController alloc] initWithNibName:#"MiddleViewController" bundle:nil];
[mvc.view setFrame:middleView.frame];
[middleView addSubview:mvc.view];
[self.view addSubview:middleView];
}
As there is no reload data method for UIPageViewController. I was using UIPageViewController in UIViewController instead of that I use UINavigationController in which the UIPageViewController can be reloaded with dynamic data.So on click of UITableViewController, data is sends to UINavigationController-->UIPageViewController. This has solved the above issue.

Resources