Im trying to implement your implementation to my project as a button called 'Gallery" but receive an error when trying to run the project.
My implementation file looks like this.
-(IBAction) gallery{
NSMutableArray *photos = [[NSMutableArray alloc] init];
MWPhoto *photo;
{
photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:#"fans1" ofType:#"jpg"]];
photo.caption = #"My fans 1";
[photos addObject:photo];
photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:#"fans2" ofType:#"jpg"]];
photo.caption = #"My fans 2";
[photos addObject:photo];
photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:#"fans3" ofType:#"jpg"]];
photo.caption = #"Fans3";
[photos addObject:photo];
photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:#"fans4" ofType:#"jpg"]];
photo.caption = #"Fans4";
[photos addObject:photo];
}
self.photos = photos;
// Create browser
MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
browser.displayActionButton = YES;
//browser.wantsFullScreenLayout = NO;
//[browser setInitialPageIndex:2];
// Show
if (_segmentedControl.selectedSegmentIndex == 0) {
// Push
[self.navigationController pushViewController:browser animated:YES];
} else {
// Modal
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:nc animated:YES];
}
}
#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
return _photos.count;
}
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex: (NSUInteger)index {
if (index < _photos.count)
return [_photos objectAtIndex:index];
return nil;
}
When I run the project but the image gallery is not displayed. Im fairly new to ioS development.If you can please point me in the right direction i will deeply appreciate it. The main goal is to have the image gallery displayed when the user touches the Gallery button.
I copied and edited the code from the MWPhotoBrowser Demo Project File I don't receive any errors but I can't get the gallery to appear once button is touched. (BTW I assigned the IBACTION to the buttons). If there is another source code or alternative Framework I can use please advise. Thanks!
Some Ideas:
1) try using 'initWithPhotos'.
2) put a breakpoint at the place you are pushing, check that the push is called.
3) check that the navigationController is not null (0x0) in debugging.
4) remember to release 'browser'.
Related
I am trying to configure the photoeditorSDK for iOS, but am struggling.
My current issues are the following:
1. When a user clicks on the brush toolMenuItem, it does not do anything. Other toolMenuItems do what they are supposed to (e.g. Size).
Similarly, when a user adds text through the Text Menu Item, it works, however when they try to resize the text - they can't click it.
I believe these issues are related - that is why I opted them together.
Here's the code snippet used to configure the control:
NSError *dataCreationError;
NSURL *aLocalURL = [NSURL URLWithString:filepath];
NSData *imageData = [NSData dataWithContentsOfFile:aLocalURL.path options:0 error:&dataCreationError];
if (imageData && !dataCreationError) {
PESDKConfiguration *configuration = [[PESDKConfiguration alloc] initWithBuilder:^(PESDKConfigurationBuilder * _Nonnull builder) {
// See Configuration section
}];
NSMutableArray<PESDKPhotoEditMenuItem *> *menuItems = [[PESDKPhotoEditMenuItem defaultItems] mutableCopy];
[menuItems removeLastObject]; // Remove last menu item ('Magic')
PESDKPhotoEditViewController *photoEditViewController = [[PESDKPhotoEditViewController alloc] initWithData:imageData configuration:configuration];
photoEditViewController.delegate = self;
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:photoEditViewController];
dispatch_async(dispatch_get_main_queue(), ^{
[self.viewController presentViewController:navigationController animated:YES completion:nil];
});
} else if (dataCreationError) {
NSLog(#"Failed to open given path: %#", dataCreationError);
}
This is a bug on our side and will be fixed with the next release, which will go live this week. As a workaround, we updated your subscription. You just need to generate a new license file using our dashboard and replace the existing one in your app. This should fix both issues, but will add the Sticker tool to your menu items. You may remove it just like you did with the Magic tool.
If you have further questions, just let me know!
I'm no longer able to render collectionview cells after using data from Cloudkit via CKAssets. I was previously using images loaded in a folder on my desktop just for initial testing. I'm now using Cloudkit and I've created some test records via the CK dashboard using those same images. I was successfully able to query the CK database and retrieve the expected records. I then changed my code to populate the model data for the cells to use the CK data. That data previously came from the images retrieved locally. I can see from logging that I am getting the data from CK successfully, including the images. I can also see from logging that my custom CV cells are no longer getting initialed. From what I can tell, my code looks good based on examples I've seen online.
Can anyone help me with this? Thank you!
Designated initializer in the model...
- (instancetype)initImagesForSelection:(NSString *)selectionType {
self = [super init];
if (self) {
CKDatabase *publicDatabase = [[CKContainer defaultContainer] publicCloudDatabase];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ImageDescription = 'description'"];
CKQuery *query = [[CKQuery alloc] initWithRecordType:#"ImageData" predicate:predicate];
[publicDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {
// handle the error
if (error) {
NSLog(#"Error: there was an error querying the cloud... %#", error);
} else {
// any results?
if ([results count] > 0) {
NSLog(#"Success querying the cloud for %lu results!!!", (unsigned long)[results count]);
for (CKRecord *record in results) {
ImageData *imageData = [[ImageData alloc] init];
CKAsset *imageAsset = record[#"Image"];
imageData.imageURL = imageAsset.fileURL;
NSLog(#"asset URL: %#", imageData.imageURL);
imageData.imageName = record[#"ImageName"];
//imageData.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageAsset.fileURL]];
imageData.image = [UIImage imageWithContentsOfFile:imageAsset.fileURL.path];
NSLog(#"image size height:%f, width:%f", imageData.image.size.height, imageData.image.size.width);
[self.imageDataArray addObject:imageData];
}
NSLog(#"imageDataArray size %lu", (unsigned long)[self.imageDataArray count]);
}
}
}];
}
return self;
}
Collectionview viewcontroller which worked perfectly before pulling the data from Cloudkit...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell"; // string value identifier for cell reuse
ImageViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSLog(#"cellForItemAtIndexPath: section:%ld row:%ld", (long)indexPath.section, (long)indexPath.row);
cell.layer.borderWidth = 1.0;
cell.layer.borderColor = [UIColor grayColor].CGColor;
ImageData *imageData = [self.imageLoadManager imageDataForCell:indexPath.row];
cell.imageView.image = imageData.image;
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
return cell;
}
Ok, I figured this out. My code was actually working. The collectionview was not displaying due to a multithreading/asynchronous download issue with the data from cloudkit. I hit the camera button to take a pic, which refreshed the CV and everything in the CV appeared. I just need to use multithreading so things start rendering while the images are downloading.
This is my First Sprite game, and for some reason the only difficult I've been run to is the admob integration.
This is my ViewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
// showing for the first time my AdMob Interstitial
[self showAdmobFullscreen];
// Configure the view.
SKView * skView = (SKView *)self.view;
SKScene *mc = [GameScene01 sceneWithSize:skView.bounds.size];
mc.scaleMode = SKSceneScaleModeAspectFill;
[skView presentScene:mc];
}
and this is my Admob Settings:
-(void)showAdmobFullscreen{
NSLog(#" showAdmoBFullScreenCalled");
// self.interstitial_ = [[GADInterstitial alloc] init];
// self.interstitial.delegate = self;
// self.interstitial.adUnitID = ADMOB_FULLSCREEN_ID;
// [self.interstitial loadRequest:[self adMobrequest]];
interstitial_ = [[GADInterstitial alloc]init];
interstitial_.delegate = self;
interstitial_.adUnitID = #"ca-app-pub-1032576214759203/773434443";
[interstitial_ loadRequest:[self adMobrequest]];
}
- (GADRequest *)adMobrequest {
NSLog(#"requestHasBeenCalled");
GADRequest *request = [GADRequest request];
request.testDevices = #[
// TODO: Add your device/simulator test identifiers here. Your device identifier is printed to
// the console when the app is launched.
//#"9481d65c607d68c867a51229a3c61340"
];
return request;
}
So Far So Good, The admob is fire when the game load. now I want to fire it every time when the user lose in the game.
Right now the whole game run into my Sprite files, and what I tried todo is to call the 'showAdmobFullscreen' every time there's a GameOver
So in my Sprite.m file, I have a method called GameOver, I've added those lines :
-(void)GameOver
{
//Trying to make Admob shows whenever User loses a game
MyMainViewController *spVc = [[MyMainViewController alloc]init];
[spVc showAdmobFullscreen];
I can see the logs of my Admob are being called but no ads are showing up.
any suggestion will be appreciated .
Instead of
MyMainViewController *spVc = [[MyMainViewController alloc]init];
[spVc showAdmobFullscreen];
Try this
[self showAdmobFullscreen];
I am trying to create a PDF report from an iPad app using xcode 4.6. I know a valid pdf file is being created when run on the simulator, because I can dig it out and preview it. The commented out code does this. The problem is that I can't write it somewhere I can get at it on the iPad.
I've tried using UIGraphicsBeginPDFContextToData instead and trying to write the image out to the PhotoAlbum instead. The problem here is that when I convert the NSMutableData into an image it returns nil.
Here is the code. Thanks for any help you can give me.
- (IBAction)makePDF:(UIButton *)sender
{
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, (CFStringRef)self.labelCopyright.text, NULL);
if (currentText)
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
if (framesetter)
{
// NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, //NSUserDomainMask, YES) objectAtIndex:0];
// NSString *pdfPath = [rootPath stringByAppendingPathComponent:#"Nick.pdf"];
// NSLog(#"pdf is at %#",pdfPath);
// UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:100000];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);
CFRange currentRange = CFRangeMake(0, 0);
NSInteger currentPage = 0;
BOOL done = NO;
do
{
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
currentPage++;
// [self drawPageNumber:currentPage];
currentRange = [self renderPage:currentPage withTextRange:currentRange andFramesetter:framesetter];
if (currentRange.location == CFAttributedStringGetLength((CFAttributedStringRef)currentText)) done = YES;
}
while (!done);
UIGraphicsEndPDFContext();
UIImage* image = [UIImage imageWithData:data];
assert(image);
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
CFRelease(framesetter);
}
else NSLog(#"Could not create the framesetter needed to lay out the atrributed string.");
CFRelease(currentText);
}
else NSLog(#"Could not create the attributed string for the framesetter");
}
- (CFRange)renderPage:(NSInteger)pageNum withTextRange:(CFRange)currentRange andFramesetter:(CTFramesetterRef)framesetter
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
CGRect frameRect = CGRectMake(72, 72, 468, 648);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
CGContextTranslateCTM(currentContext, 0, 792);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CTFrameDraw(frameRef, currentContext);
currentRange = CTFrameGetVisibleStringRange(frameRef);
currentRange.location += currentRange.length;
currentRange.length = 0;
CFRelease(frameRef);
return currentRange;
}
Save the mutable data to your documents directory
[data writeToFile:filePath atomically:YES]
Here's an example:
+(void) saveData: (NSData*) data ToFileName: (NSString*) filename {
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent: filename];
// instructs the mutable data object to write its context to a file on disk
[data writeToFile:documentDirectoryFilename atomically:YES];
//NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
As for displaying the generated PDF on the device, the UIWebView object supports loading PDF files from NSData. Here is an example:
[self.webView loadData:pdfData MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil];
It is possible to attach an NSData object to an email as well. Here is an example:
//Check if we can send e-mails
if ([MFMailComposeViewController canSendMail]) {
//Create the Email view controller
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
//Set the subject and body
[controller setSubject:#"Email Subject"];
[controller setMessageBody:#"Email body" isHTML:NO];
//Set the email address
[controller setToRecipients:#"test#test.com"];
//Add the current PDF as an attachment
NSString *fileName = #"file.pdf";
[controller addAttachmentData:self.retrievedPDF mimeType:#"application/pdf" fileName:fileName];
// show the email controller modally
[self.navigationController presentModalViewController: controller animated: YES];
}
Instead of writing the PDF to an NSMutableData object, write it to a file using UIGraphicsBeginPDFContextToFile.
The first argument is the file path. The best place would be the Documents directory. There are then many different ways to get the file out of the app:
iTunes file sharing
Email
iCloud
Sending to a 3rd party server (Dropbox, Box, Google Drive, etc.)
Open in another iOS app using UIDocumentInteractionController.
UIBarButtonItem does not extend UIView, so there is nothing like a frame property.
But is there any way I can get what is it's CGRect frame, relative to the application UIWindow?
Do you like to use private APIs? If yes,
UIView* view = thatItem.view;
return [view convertRect:view.bounds toView:nil];
Of course no one wants this when targeting the AppStore. A more unreliable method, and also uses undocumented features, but will pass Apple's test, is to loop through the subviews to look for the corresponding button item.
NSMutableArray* buttons = [[NSMutableArray alloc] init];
for (UIControl* btn in theToolbarOrNavbar.subviews)
if ([btn isKindOfClass:[UIControl class]])
[buttons addObject:btn];
UIView* view = [buttons objectAtIndex:index];
[buttons release];
return [view convertRect:view.bounds toView:nil];
The index is the index to your bar item in the array of .items, after removing all blank items. This assumes the buttons are arranged in increasing order, which may not be. A more reliable method is to sort the buttons array in increasing .origin.x value. Of course this still assumes the bar button item must inherit the UIControl class, and are direct subviews of the toolbar/nav-bar, which again may not be.
As you can see, there are a lot of uncertainty when dealing with undocumented features. However, you just want to pop up something under the finger right? The UIBarButtonItem's .action can be a selector of the form:
-(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event;
note the event argument — you can obtain the position of touch with
[[event.allTouches anyObject] locationInView:theWindow]
or the button view with
[[event.allTouches anyObject] view]
Therefore, there's no need to iterate the subviews or use undocumented features for what you want to do.
I didn't see this option posted (which in my opinion is much simpler), so here it is:
UIView *barButtonView = [barButtonItem valueForKey:#"view"];
In iOS 3.2, there's a much easier way to show an Action Sheet popover from a toolbar button. Merely do something like this:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIActionSheet *popupSheet;
// Prepare your action sheet
[popupSheet showFromBarButtonItem:sender animated:YES];
}
This is the implementation I use for my WEPopover project: (https://github.com/werner77/WEPopover):
#implementation UIBarButtonItem(WEPopover)
- (CGRect)frameInView:(UIView *)v {
UIView *theView = self.customView;
if (!theView.superview && [self respondsToSelector:#selector(view)]) {
theView = [self performSelector:#selector(view)];
}
UIView *parentView = theView.superview;
NSArray *subviews = parentView.subviews;
NSUInteger indexOfView = [subviews indexOfObject:theView];
NSUInteger subviewCount = subviews.count;
if (subviewCount > 0 && indexOfView != NSNotFound) {
UIView *button = [parentView.subviews objectAtIndex:indexOfView];
return [button convertRect:button.bounds toView:v];
} else {
return CGRectZero;
}
}
#end
As long as UIBarButtonItem (and UITabBarItem) does not inherit from UIView—for historical reasons UIBarItem inherits from NSObject—this craziness continues (as of this writing, iOS 8.2 and counting ... )
The best answer in this thread is obviously #KennyTM's. Don't be silly and use the private API to find the view.
Here's a oneline Swift solution to get an origin.x sorted array (like Kenny's answer suggests):
let buttonFrames = myToolbar.subviews.filter({
$0 is UIControl
}).sorted({
$0.frame.origin.x < $1.frame.origin.x
}).map({
$0.convertRect($0.bounds, toView:nil)
})
The array is now origin.x sorted with the UIBarButtonItem frames.
(If you feel the need to read more about other people's struggles with UIBarButtonItem, I recommend Ash Furrow's blog post from 2012: Exploring UIBarButtonItem)
I was able to get Werner Altewischer's WEpopover to work by passing up the toolbar along with the
UIBarButton:
Mod is in WEPopoverController.m
- (void)presentPopoverFromBarButtonItem:(UIBarButtonItem *)item toolBar:(UIToolbar *)toolBar
permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections
animated:(BOOL)animated
{
self.currentUIControl = nil;
self.currentView = nil;
self.currentBarButtonItem = item;
self.currentArrowDirections = arrowDirections;
self.currentToolBar = toolBar;
UIView *v = [self keyView];
UIButton *button = nil;
for (UIView *subview in toolBar.subviews)
{
if ([[subview class].description isEqualToString:#"UIToolbarButton"])
{
for (id target in [(UIButton *)subview allTargets])
{
if (target == item)
{
button = (UIButton *)subview;
break;
}
}
if (button != nil) break;
}
}
CGRect rect = [button.superview convertRect:button.frame toView:v];
[self presentPopoverFromRect:rect inView:v permittedArrowDirections:arrowDirections animated:animated];
}
-(CGRect) getBarItemRc :(UIBarButtonItem *)item{
UIView *view = [item valueForKey:#"view"];
return [view frame];
}
You can get it from the UINavigationBar view. The navigationBar is a UIView which has 2 or 3 custom subviews for the parts on the bar.
If you know that the UIBarButtonItem is currently shown in the navbar on the right, you can get its frame from navbar's subviews array.
First you need the navigationBar which you can get from the navigationController which you can get from the UIViewController. Then find the right most subview:
UINavigationBar* navbar = curViewController.navigationController.navigationBar;
UIView* rightView = nil;
for (UIView* v in navbar.subviews) {
if (rightView==nil) {
rightView = v;
} else if (v.frame.origin.x > rightView.frame.origin.x) {
rightView = v; // this view is further right
}
}
// at this point rightView contains the right most subview of the navbar
I haven't compiled this code so YMMV.
This is not the best solution and from some point of view it's not right solution and we can't do like follow because we access to object inside UIBarBattonItem implicitly, but you can try to do something like:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[button setImage:[UIImage imageNamed:#"Menu_Icon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(didPressitem) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtonItem = item;
CGPoint point = [self.view convertPoint:button.center fromView:(UIView *)self.navigationItem.rightBarButtonItem];
//this is like view because we use UIButton like "base" obj for
//UIBarButtonItem, but u should note that UIBarButtonItem base class
//is NSObject class not UIView class, for hiding warning we implicity
//cast UIBarButtonItem created with UIButton to UIView
NSLog(#"point %#", NSStringFromCGPoint(point));
as result i got next:
point {289, 22}
Before implement this code, be sure to call [window makeKeyAndVisible] in your Applition delegate application:didFinishLaunchingWithOptions: method!
- (void) someMethod
{
CGRect rect = [barButtonItem convertRect:barButtonItem.customview.bounds toView:[self keyView]];
}
- (UIView *)keyView {
UIWindow *w = [[UIApplication sharedApplication] keyWindow];
if (w.subviews.count > 0) {
return [w.subviews objectAtIndex:0];
} else {
return w;
}
}
I handled it as follows:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIView* view = [sender valueForKey:#"view"]; //use KVO to return the view
CGRect rect = [view convertRect:view.bounds toView:self.view];
//do stuff with the rect
}