How to load url, what come from popoverclass? [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This is probably is pretty easy, but I'm stuck with it today.
The idea is that in my browser, I've create uiwebview and I want to implimate address bar in popover with it own class.
I can get the url from UItextfield from popover class to webview class, but when I get it uiwebview get lazy and it doesn't load it.
When I check it, debuger says that webview is null.
This is ViewController.h
#import <UIKit/UIKit.h>
#import "AdressBar.h"
#import "mypopoverController.h"
#interface ViewController : UIViewController<AddressbarDelegate>
{
UIWebView* mWebView;
mypopoverController *popoverController;
}
#property (nonatomic, retain) IBOutlet UIWebView* webPage;
#end
This is ViewController.m:
#import "mypopoverController.h"
#import "MyOwnPopover.h"
#import "ViewController.h"
#import "AdressBar.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webPage = mWebView;
- (void)viewDidLoad
{
[super viewDidLoad];
addressBar = [[AdressBar alloc] init];
addressBar.delegate = self;
[edittext addTarget:self action:#selector(showPopoverAdressBar:forEvent:) forControlEvents:UIControlEventTouchUpInside];
NSURL *url = [NSURL URLWithString:#"http://www.google.lv"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[mWebView setScalesPageToFit:YES];
[mWebView setDelegate:self];
[mWebView loadRequest:request];
}
-(void)loadReceivedAddress:(NSURLRequest *)url{
NSLog(#"url= %#", url);//there url always is not null and mWebView should load it
if(mWebView != nil){
[mWebView loadRequest:url];
}else{
NSLog(#"mWebView is null");//...but there it say's that it's null
}}
-(void)showPopoverAdressBar:(id)sender forEvent:(UIEvent*)event
{
AdressBar *popoverControllesr = [[AdressBar alloc]init];
popoverControllesr.view.frame = CGRectMake(0,0, 600, 45);
popoverControllesr.view.backgroundColor = [UIColor whiteColor];
popoverController = [[mypopoverController alloc] initWithContentViewController:popoverControllesr];
popoverController.cornerRadius = 20;
if(_titles!=NULL){
popoverController.titleText = _titles;}else{
popoverController.titleText = #"Loading...";
}
popoverControllesr.address.text = absoluteString;
popoverController.popoverBaseColor = [UIColor orangeColor];
popoverController.popoverGradient= YES;
popoverController.arrowPosition = TSPopoverArrowPositionHorizontal;
[popoverController showPopoverWithTouch:event];
}
#end
This is AdressBar.h
#import <UIKit/UIKit.h>
#protocol AddressbarDelegate <NSObject>
#required
-(void)loadSomethingFromAddressBar:(NSURLRequest*)request;
#end
#interface AdressBar : UIViewController{
IBOutlet UIButton *cancel;
}
#property (nonatomic, retain) IBOutlet UITextField *address;
#property (nonatomic, retain) NSURLRequest *request;
#property(nonatomic, weak) id <AddressbarDelegate> delegate;
#end
This is AdressBar.m:
#import "AdressBar.h"
#import "ViewController.h"
#interface AdressBar ()
#end
#implementation AdressBar
#synthesize delegate = delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[_address setDelegate:self];
_address.clearButtonMode =
UITextFieldViewModeWhileEditing;
_address.keyboardType = UIKeyboardTypeURL;
[_address addTarget:self
action:#selector(loadAddresss)
forControlEvents:UIControlEventEditingDidEndOnExit];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)loadAddresss {
NSString* urlString = _address.text;
NSURL* url = [NSURL URLWithString:urlString];
if(!url.scheme)
{
NSString* modifiedURLString = [NSString stringWithFormat:#"http://%#", urlString];
url = [NSURL URLWithString:modifiedURLString];
}
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(#"request= %#", request);
NSLog(#"text= %#", urlString);
if (request!=nil) {
if(delegate!=nil)
{NSLog(#"delegate not nil");
[delegate loadSomethingFromAddressBar:request];
}else{
NSLog(#"delegate is nil");//There delegate always is nil
}
}
}
#end

Make sure that your web view Outlet & Delegate is correctly conncted.
There no space between URL Address because I also face the same issue. Try to open that url in web-Browser.

If this is your view hierarchy
---- In ViewController
---- Showing AddressBar View in POPOver
---- Remove POPover and display ViewController's web view
I suggest create a custom delegate method in AddressBar and when you remove the popOver trigger the delegate method. Implement the delegate in your ViewContrller and call loadSomethingFromAddressBar in that implemented delegate method
Note : make sure you have connected you webpage IBOutlet to your nib file.
// In Adressbar.h
#protocol AddressbarDelegate <NSObject>
#required
-(void)loadYourWebViewNow:(NSURLRequest*)request;
#end
#interface Addressbar : UIViewController
{
}
#property(nonatomic, weak) id <AddressbarDelegate>
// In Adressbar.m
- (void)loadAddresss {
NSString* urlString = _address.text; //geting text from UItextField
NSURL* url = [NSURL URLWithString:urlString];
if(!url.scheme)
{
NSString* modifiedURLString = [NSString stringWithFormat:#"http://%#", urlString];
url = [NSURL URLWithString:modifiedURLString];
}
NSURLRequest *request = [NSURLRequest requestWithURL:url];
if (request!=nil) {
NSLog(#"request is good");
if(_delegate!=nil)
{
[_delegate loadYourWebViewNow:request];
}
}
// In your ViewController.h
#interface ViewController : UIViewController<AddressbarDelegate>
{
//AdressBar *addressBar;
}
// In your ViewController.m implement the delegate method and set the delegate
#implementation ViewController
-(void)viewDidLoad
{
Remove these two below lines on viewDidLoad
//addressBar = [[Adressbar alloc] init];
//addressbar.delegate = self;
}
-(void)loadYourWebViewNow:(NSURLRequest*)request
{
[self loadSomethingFromAddressBar:request];
}
-(void)showPopoverAdressBar:(id)sender forEvent:(UIEvent*)event
{
AdressBar *popoverControllesr = [[AdressBar alloc]init];
popoverControllesr.delegate = self; // set the delegate here to this object.
popoverControllesr.view.frame = CGRectMake(0,0, 600, 45);
popoverControllesr.view.backgroundColor = [UIColor whiteColor];
popoverController = [[mypopoverController alloc] initWithContentViewController:popoverControllesr];
popoverController.cornerRadius = 20;
if(_titles!=NULL){
popoverController.titleText = _titles;}else{
popoverController.titleText = #"Loading...";
}
popoverControllesr.address.text = absoluteString;
popoverController.popoverBaseColor = [UIColor orangeColor];
popoverController.popoverGradient= YES;
popoverController.arrowPosition = TSPopoverArrowPositionHorizontal;
[popoverController showPopoverWithTouch:event];
}

Related

The UILabel is nil

I have a ContentPageViewController class, it has the IBOutlet stuff. I write my getter of ContentPageViewController in the ViewController like the following code.
ContentPageViewController.h
#interface ContentPageViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *busName;
#property (weak, nonatomic) IBOutlet UILabel *busTime;
#property (weak, nonatomic) IBOutlet UILabel *busType;
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// instantiation from a storyboard
ContentPageViewController *page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
self.page = page;
// send url request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://api.apb-shuttle.info/now" ]];
[self sendURLRequest:request];
// add the view of ContendPageViewController into ViewController
[self.view addSubview:self.page.view];
}
// It works if i remove the following code
- (ContentPageVC *)page
{
if (_page) _page = [[ContentPageViewController alloc] init];
return _page;
}
Nothing happened when I updated it. And it gave me a nil.
- (void)updateUI
{
// I got null here
NSLog("%#", self.page.busName)
// The spacing style font
NSDictionary *titleAttributes = #{
NSKernAttributeName: #10.0f
};
NSDictionary *attributes = #{
NSKernAttributeName: #5.0f
};
self.page.busName.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.name
attributes:titleAttributes];
self.page.busTime.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.depart
attributes:titleAttributes];
self.page.busType.attributedText = [[NSMutableAttributedString alloc] initWithString:bus.note
attributes:attributes];
}
The following code is when I called the updateUI:
- (void)sendURLRequest:(NSURLRequest *)requestObj
{
isLoading = YES;
[RequestHandler PerformRequestHandler:requestObj withCompletionHandler:^(NSDictionary *data, NSError *error) {
if (!error) {
bus = [JSONParser JSON2Bus:data];
// Add the bus object into the array.
[self.busArray addObject: bus];
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
[self updateUI];
isLoading = NO;
}];
} else {
NSLog(#"%#", [error localizedDescription]);
}
}];
}
But it worked if I removed the getter above.
I have no idea how it works, please give me some hint. Thanks.
Check your IBOutlet is connected.
Check the method you are calling isn't called before the view is created from the storyboard/nib
EDIT
The lines of code that you added, are overriding your getter. And every time you call self.page, your creating a new instance!
// It works if i remove the following code
- (ContentPageVC *)page
{
if (_page) _page = [[ContentPageViewController alloc] init];
return _page;
}
It should be like so:
// It works if i remove the following code
- (ContentPageVC *)page
{
if (!_page) _page = [[ContentPageViewController alloc] init]; // Added the ! mark, only if nil you would create a new instance.
return _page;
}
Plus you are calling alloc init on it, so Its not the same instance from storyboard!
So you should do this:
- (ContentPageVC *)page
{
if (!_page) _page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
return _page;
}
And remove this lines of code:
// instantiation from a storyboard
ContentPageViewController *page = [self.storyboard instantiateViewControllerWithIdentifier:#"ContentPageViewController"];
self.page = page;
Every time you call "self.page" the override getter function will call. and return the same instance.

cannot set a property

I am making a blog reader app. Everything works fine until I try to access the detailView from a cell. I receive this error,
[UINavigationController setPFeedURL:]: unrecognised selector sent to instance 0x7f96d5802800
below code is in the PRTableViewController.m
#import "PRTableViewController.h"
#import "PRFeedPost.h"
#import "PRDetailViewController.h"
This is where the code is where the crash happens
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showDetail"]){
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PRFeedPost *feed_Post = [self.polisenFeed objectAtIndex:indexPath.row];
[segue.destinationViewController setPFeedURL:feed_Post.url];
}
}
This is to help you understand what I am trying to setPFeedURL to. Also in PRViewTableController.m
self.polisenFeed = [NSMutableArray array];
NSArray *polisenFeedArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *postDictionary in polisenFeedArray) {
PRFeedPost *fp = [PRFeedPost feedWithTitle:[postDictionary objectForKey:#"title"]];
fp.author = [postDictionary objectForKey:#"author"];
fp.thumbnail = [postDictionary objectForKey:#"thumbnail"];
fp.date = [postDictionary objectForKey:#"date"];
fp.url = [NSURL URLWithString:[postDictionary objectForKey:#"url" ]];
[self.polisenFeed addObject:fp];
}
Now the PRDetailViewController.h,
This is where the property is I am trying to set is,
#property (strong, nonatomic) NSURL *pFeedURL;
#property (strong, nonatomic) id detailItem;
#property (strong, nonatomic) IBOutlet UIWebView *webView;
Here is the code in PRDetailViewController.m,
- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:self.pFeedURL];
[self.webView loadRequest:urlRequest];
I cannot seem to figure out why this is crashing. I know it has to do with this line ,
[segue.destinationViewController setPFeedURL:feed_Post.url];
(at leaset I think it is that line. I can't figure out why I cannot set it.
Thanks for your help guys!
Change This
PRDetailViewController *objPRDetailViewController = (PRDetailViewController *)[segue.destinationViewController topViewController];
objPRDetailViewController.pFeedURL=feed_Post.url;
And Also put bellow code in viewDidAppear
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:self.pFeedURL];
[self.webView loadRequest:urlRequest];
try this
[[((id)segue.destinationViewController) topViewController] setPFeedURL:feed_Post.url];
let me know if it works

iOS: Viewcontroller subclassed from MWPhotoBrowser-images are not loaded

I am trying to include MWPhotoBrowser in my project
When its used as given in the sample it working fine.
But when a new viewcontroller is subclassed from MWPhotoBrowser, photos are not loaded except empty black theme.
Delegate methods are not getting called. As the controller is subclass of MWPhotoBrowser, I assume there is no need to set it explicitly.
Storyboard is used and the nib class in it is set.
.h file
#interface MDRPhotoViewerController : MWPhotoBrowser
{
NSMutableArray *_selections;
}
#property (nonatomic, strong) NSMutableArray *photos;
#property (nonatomic, strong) NSMutableArray *thumbs;
#property (nonatomic, strong) NSMutableArray *assets;
#property (nonatomic, strong) NSMutableIndexSet *optionIndices;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) ALAssetsLibrary *ALAssetsLibrary;
- (void)loadAssets;
#end
**.m file **
- (void)viewWillAppear:(BOOL)animated
{
NSMutableArray *photos = [[NSMutableArray alloc] init];
NSMutableArray *thumbs = [[NSMutableArray alloc] init];
//mwphotobrowser options setup
BOOL displayActionButton = YES;
BOOL displaySelectionButtons = NO;
BOOL displayNavArrows = NO;
BOOL enableGrid = YES;
BOOL startOnGrid = NO;
BOOL autoPlayOnAppear = NO;
//loading data
NSArray *photosDataArray = [MDRDataController GetPhotos]; //creating array
for (NSString *urlString in photosDataArray) { //Formating the data source for images
NSString *urlFullString = [NSString stringWithFormat:#"%#%#",KBASEURL,urlString];
//Photos
[photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlFullString]]];
//thumbs
[thumbs addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlFullString]]];
}
// Options
self.photos = photos;
self.thumbs = thumbs;
// Create browser
self.displayActionButton = displayActionButton;
self.displayNavArrows = displayNavArrows;
self.displaySelectionButtons = displaySelectionButtons;
self.alwaysShowControls = displaySelectionButtons;
self.zoomPhotosToFill = YES;
self.enableGrid = enableGrid;
self.startOnGrid = startOnGrid;
self.enableSwipeToDismiss = NO;
self.autoPlayOnAppear = autoPlayOnAppear;
[self setCurrentPhotoIndex:0];
// Test custom selection images
// browser.customImageSelectedIconName = #"ImageSelected.png";
// browser.customImageSelectedSmallIconName = #"ImageSelectedSmall.png";
// Reset selections
if (displaySelectionButtons) {
_selections = [NSMutableArray new];
for (int i = 0; i < photos.count; i++) {
[_selections addObject:[NSNumber numberWithBool:NO]];
}
}
self.title = #"Phots";
//[self reloadData];
}
Debugging performed
Considering the image template of mwphotobrowser, tried reloading the code.
Shifted the code between viewwillappear and viewdidload.
Doesn't MWPhotoBrowser support this way or am i doing it wrong ?
For those who stumble upon this later...
If you look at MWPhotoBrowser.m you'll see various initializers:
- (id)init {
if ((self = [super init])) {
[self _initialisation];
}
return self;
}
- (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
if ((self = [self init])) {
_delegate = delegate;
}
return self;
}
- (id)initWithPhotos:(NSArray *)photosArray {
if ((self = [self init])) {
_fixedPhotosArray = photosArray;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
[self _initialisation];
}
return self;
}
The problem is there's no awakeFromNib initializer. Simplest solution is to fork the project and create the awakeFromNib initializer.

UILabel being referenced as an integer pointer in xcode [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The Goal and Problem:
After every passing second, the value of 'regularBubbleCount' - a variable of RWGameData - increases by 1. I am attempting to display this change in value by passing the new value of 'regularBubbleCount' to the 'regularBubLabel' UILabel in the PrimaryViewController. I am attempting to do this by using the following line of code,
_regularBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].regularBubbleCount];
Obviously this does not work because 'regularBubLabel' is not an object of the RWGameData class where the 'timerCalled' method resides. How can I change the value of the 'regularBubLabel' from inside the RWGameData class?
RWGameData.h
#import <Foundation/Foundation.h>
#interface RWGameData : NSObject <NSCoding>
#property (assign, nonatomic) long regularBubbleCount;
#property (assign, nonatomic) BOOL dataIsInitialized;
+(instancetype)sharedGameData;
-(void)reset;
-(void)save;
-(void)timerSetup;
-(void)timerCalled;
#end
RWGameData.m
#import "RWGameData.h"
#implementation RWGameData
static NSString* const SSGameDataRegularBubbleCountKey = #"regularBubbleCount";
static NSString* const SSGameDataIsInitializedKey = #"dataIsInitializedKey";
+ (instancetype)sharedGameData {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [self loadInstance];
});
return sharedInstance;
}
-(void)reset {
self.regularBubbleCount = 0;
self.dataIsInitialized = true;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeDouble:self.regularBubbleCount forKey: SSGameDataRegularBubbleCountKey];
[encoder encodeBool:self.dataIsInitialized forKey: SSGameDataIsInitializedKey];
}
- (instancetype)initWithCoder:(NSCoder *)decoder
{
self = [self init];
if (self) {
_regularBubbleCount = [decoder decodeDoubleForKey: SSGameDataRegularBubbleCountKey];
_dataIsInitialized = [decoder decodeBoolForKey: SSGameDataIsInitializedKey];
}
return self;
}
+(NSString*)filePath
{
static NSString* filePath = nil;
if (!filePath) {
filePath =
[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
stringByAppendingPathComponent:#"gamedata"];
}
return filePath;
}
+(instancetype)loadInstance
{
NSData* decodedData = [NSData dataWithContentsOfFile: [RWGameData filePath]];
if (decodedData) {
RWGameData* gameData = [NSKeyedUnarchiver unarchiveObjectWithData:decodedData];
return gameData;
}
return [[RWGameData alloc] init];
}
-(void)save
{
NSData* encodedData = [NSKeyedArchiver archivedDataWithRootObject: self];
[encodedData writeToFile:[RWGameData filePath] atomically:YES];
}
- (void)timerSetup { // to be called from delegate didFinishLaunching….
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timerCalled) userInfo:nil repeats:YES];
}
-(void)timerCalled
{
[RWGameData sharedGameData].regularBubbleCount++;
/* THE ISSUE IS HERE */
_regularBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].regularBubbleCount];
[[RWGameData sharedGameData] save];
} NSLog(#"Regular Bubble Count: %li", [RWGameData sharedGameData].regularBubbleCount);
}
#end
PrimaryViewController.h
#import <UIKit/UIKit.h>
#import "RWGameData.h"
#interface PrimaryViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *regularBubLabel;
#end
PrimaryViewController.m
#import "PrimaryViewController.h"
#interface PrimaryViewController ()
#end
#implementation PrimaryViewController
{
NSString *bubbleImage;
UIImage *backgroundImage;
UIImageView *backgroundImageView;
int r;
int i;
}
- (void)viewDidLoad {
[super viewDidLoad];
backgroundImage = [UIImage imageNamed:#"background_new.png"];
backgroundImageView=[[UIImageView alloc]initWithFrame:self.view.frame];
backgroundImageView.image=backgroundImage;
[self.view insertSubview:backgroundImageView atIndex:0];
}
- (void)viewDidAppear:(BOOL)animated {
_regularBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].regularBubbleCount];
_premiumBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].premiumBubbleCount];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)increment {
if ([RWGameData sharedGameData].megaBubblePopValue == 0) {
[RWGameData sharedGameData].megaBubblePopValue++;
[[RWGameData sharedGameData] save];
}
if ([#"mysterybubble.png" isEqual:bubbleImage]) {
[RWGameData sharedGameData].premiumBubbleCount += 2;
_premiumBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].premiumBubbleCount];
} else if ([#"megaBubbleLarge30.png" isEqual:bubbleImage]) {
[RWGameData sharedGameData].regularBubbleCount += [RWGameData sharedGameData].megaBubblePopValue;
_regularBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].regularBubbleCount];
} i++;
}
- (IBAction)save {
[[RWGameData sharedGameData] save];
}
- (IBAction)setBubbleStatus {
r = arc4random_uniform(400);
if (r <= 1) {
bubbleImage = #"mysterybubble.png";
[_megaBubbleButton setImage:[UIImage imageNamed:bubbleImage] forState:UIControlStateNormal];
NSLog(#"Roll SUCCESS. [%i] %i", i, r);
} else {
bubbleImage = #"megaBubbleLarge30.png";
[_megaBubbleButton setImage:[UIImage imageNamed:bubbleImage] forState:UIControlStateNormal];
NSLog(#"Roll FAIL. [%i] %i", i, r);
}
}
#end
It makes no sense to have an IBOutlet in your RWGameData class, since it's a subclass of NSObject. That class has no instance (and no view) in the storyboard, so you can't hook up an IBOutlet. One way to accomplish your goal would be to make PrimaryViewController a delegate of RWGameData, and call a delegate method inside the timer's action method that would pass whatever data you need so PrimaryViewController can update its own label.
I am going to make the following assumptions:
Assumption #1 -RWGameData is instantiated inside the ApplicationDelegate when the application is loaded and can be referenced in the application delegate as self.gameData
Assumption #2 - PrimaryViewController is, as you have named it, the primary view controller in your storyboard.
Assumption #3 - You're using an NSTimer to update this count every 1 second.
Assumption #4 - Your Storyboard file is called Mainstorybaord
RWGameData
Add this to your RWGameData.h before your class definition.
#class RWGameData;
#protocol RWGameStateProtocol <NSObject>
-(void)StateUpdateForGameData:(RWGameData*)data;
#end
Inside RWGameData.h add a delegate in your class definition.
#interface RWGameData : NSObject
#property(weak)id<RWGameStateProtocol> delegate;
#end
In your selector timerCalled add a call to your delegate informing it the data has changed.
-(void)timerCalled
{
[RWGameData sharedGameData].regularBubbleCount++;
/* THE ISSUE IS HERE */
_regularBubLabel.text = [NSString stringWithFormat:#"%li", [RWGameData sharedGameData].regularBubbleCount];
[[RWGameData sharedGameData] save];
} NSLog(#"Regular Bubble Count: %li", [RWGameData sharedGameData].regularBubbleCount);
/* Inform the delegate */
[self.delegate StateUpdateForGameData:self];
}
PrimaryViewController
Once you have your protocol defined have your PrimaryViewcontroller conform to this protocol with something similar to the following.
-(void)StateUpateforGameData:(RWGameData*)data
{
self.regularBubLabel.text = [[NSString alloc]initWithFormat:#"%i",data.regularBubbleCount];
}
Application Delegate
All that remains is to set the delegate on your RWGameData instance. You can do this by asking storyboard to provide you an instance of your primary view controller. If you're using storyboard then by default this method is empty. However, since we are going to modify the primary view controller before it is shown then we need to make a few changes and perform some of the work Storyboard already does for you.
In your ApplicationDelegate's header file create a property for a UIWindow and RWGameData.
#interface YourAppDelegate : UIResponder <UIApplicationDelegate>
#property(strong,nonatomic) UIWindow *window;
#property(strong,nonatomic) RWGameData *gameData;
#end
Now that we have the properties setup you need to perform some additional work. Note that normally you don't have to perform this step when using storyboard.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/// Screen Information
CGFloat scale = [[UIScreen mainScreen]scale];
CGRect frame = [[UIScreen mainScreen]bounds];
UIWindow* window = [[UIWindow alloc]initWithFrame:frame];
self.window = window;
self.window.contentScaleFactor = scale;
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
PrimaryViewController *vc = (PrimaryViewController*)[sb instantiateInitialViewController];
RWGameData *gameData = [[RWGameData alloc]init];
gameData.delegate = vc;
self.gameData = gameData;
[window setRootViewController:vc];
[window makeKeyAndVisible];
return YES;
}
This approach doesn't require you to tightly couple your label and game data. Instead any update to your game data can now inform your view and allows your view to select which labels need to be updated.

xcode osx webview new window

I have a problem with webview.
I made a simple webbrowser for Osx, within I have to hide nvigation bar , menu amd right click and the user can go only in one specific url..
all this is ok but I need that allow _blank target.. i mean .. I have some link woth target _blank, so to open in a new window, but it does no work and i don't know hot to allow this.
this is my code for DataOAppDelegate.h:
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#interface DataOAppDelegate : NSObject <NSApplicationDelegate,NSWindowDelegate>
{WebView *WebView;
//other instance variable
}
#property (assign) IBOutlet NSWindow *window;
#property (retain, nonatomic) IBOutlet WebView *myWebView;
#end
and code for DataOAppDelegate.m
#import "DataOAppDelegate.h"
//#import <WebKit/WebKit.h>
#implementation DataOAppDelegate
#synthesize window;
#synthesize myWebView;
//your function etc
-(void)awakeFromNib{
NSString *urlText = #"http://website.com";
[[myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
[myWebView setDrawsBackground:NO];
[window setDelegate:self];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[myWebView setUIDelegate:self];
NSString *urlText = #"http://website.com";
[[myWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];
}
- (WebView *)myWebView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request
{
NSLog(#"sss%#",sender);
NSUInteger windowStyleMask = NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask |
NSTitledWindowMask;
NSWindow* webWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:windowStyleMask backing:NSBackingStoreBuffered defer:NO];
WebView* newWebView = [[WebView alloc] initWithFrame:[webWindow contentRectForFrameRect:webWindow.frame]];
[newWebView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
[webWindow setContentView:newWebView];
[webWindow center];
[webWindow makeKeyAndOrderFront:self];
[[newWebView mainFrame] loadRequest:request];
return newWebView;
}
- (void)launchSoftWithBundleID:(NSString *)softPath
{
NSBundle *softBundle = [NSBundle bundleWithPath:softPath];
NSString *bundleID = [softBundle bundleIdentifier];
//
NSTask *softTask = [[NSTask alloc] init];
[softTask setLaunchPath:softPath];
[softTask launch];
//
NSArray *array = [NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID];
if ([array count] > 0)
{
NSRunningApplication *runningApp = [array objectAtIndex:0];
[runningApp activateWithOptions:NSApplicationActivateIgnoringOtherApps];
}
}
WebViews have delegate methods to do so: decidePolicyForNavigationAction and decidePolicyForNewWindowAction (documentation).
- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id)listener {
if ([sender isEqual:self.YourVebView]) {
[listener use];
}
else {
[[NSWorkspace sharedWorkspace] openURL:[actionInformation objectForKey:WebActionOriginalURLKey]];
[listener ignore];
}
}
- (void)webView:(WebView *)sender decidePolicyForNewWindowAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request newFrameName:(NSString *)frameName decisionListener:(id<WebPolicyDecisionListener>)listener {
[[NSWorkspace sharedWorkspace] openURL:[actionInformation objectForKey:WebActionOriginalURLKey]];
[listener ignore];
}
Note: don't forget to set the policy delegate for your WebView.

Resources