Menu
  • HOME
  • TAGS

UIAlertAction completion block not called - iOS

ios,objective-c,cocoa-touch,uiactionsheet,uialertcontroller

Don't attempt to dismiss the alert controller. It will be dismissed for you by the time your alert action's handler is called. Change the "cancel" action to: UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { NSLog(@"asdhfgjk"); }]; ...

Override UITabBarController Icon Selection

ios,objective-c,uitabbarcontroller

UITabBarControllerDelegate has a delegate method - tabBarController:shouldSelectViewController:, just implement it and check if user is logged in or not. e.g. - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController { if (isLogin) { return YES; } else{ //show your view controller here return NO; } } You can also check which view controller has...

Call method after asynchronous request obj-c

ios,objective-c,asynchronous,uiviewcontroller,nsobject

You'll have to 'remember' which UIViewController calls the object. This can be done for instance with a property. in .h @property (nonatomic) UIViewController *viewController; in your .m file @synthesize viewController; Before calling the method, set the property with anObject.viewController = self; Then, you'll be able to call [viewController finishedPost:self]; inside...

UIImage returns null first time, until reloaded? [duplicate]

ios,objective-c,uiimage,nsurl

The connection:didReceiveData: method is called repeatedly as the data is loaded incrementally. You probably want the connectionDidFinishLoading: method instead. By the way, you'll still likely need a connection:didReceiveData:, but rather than trying to create the image, you'll just be appending the new data to a buffer. Then in the connectionDidFinishLoading:...

Crash when processing `__Atom` class object in Objective C (using Objective C runtime )

objective-c,osx,objective-c-runtime

+[NSObject isSubclassOfClass:] is a class method for NSObject and not all classes are subclasses of NSObject. It seems as if you have find private class that is not a subclass of NSObject, so it requires a more delicate handling for checking for inheritance. Try: BOOL isSubclass(Class child, Class parent) {...

UINavigationItem setLeftBarButtonItems Delay

ios,objective-c,uinavigationitem

Every time you see a similar delay in UI, it is because you haven't updated the UI from the main thread. Always update UI only from the main thread. dispatch_async(dispatch_get_main_queue(), ^{ UIBarButtonItem *exclamationMark = [[UIBarButtonItem alloc]initWithTitle:@"!" style:UIBarButtonItemStyleDone target:self action:@selector(showConnectivityInfo)]; [exclamationMark setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:22]} forState:UIControlStateNormal];...

Xcode UIWebView not changing page with changed URL

ios,objective-c,xcode,uiwebview

[self.webView reload] - will reload the current page. This is probably happening before the loadRequest has finished. Try removing this line. Also, @joern's comment is correct; the 'event' is the user making a pan gesture. Lose the timer....

Objective-C AVCaptureDevice Front Camera

ios,objective-c,camera,avcapturedevice,avcapture

this code is returns an AVCaptureDevice instance for the default device of the given media type. AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; change this code to .... AVCaptureDevice *inputDevice = nil; NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for(AVCaptureDevice *camera in devices) { if([camera position] == AVCaptureDevicePositionFront) { // is front camera inputDevice...

Calling UIView from UIController

ios,objective-c,uiview

@implementation FirstScreen - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self didLoad]; } return self; } -(void) didLoad { f = [[FirstScreen alloc] initWithFrame:CGRectMake(0, 0, self.view.size.width, self.view.size.height)]; [self.view addSubview:f]; } This will be helpfull. Thanks in advanvce for upvoting....

Delete child SKSpriteNode

objective-c,iphone,sprite-kit,skspritenode

Here are some observations: You your code inside of a loop which only runs once. Why are you doing that? If you are creating an object, in your case a SKSpriteNode, and want to delete it later on, you will need to keep some kind of reference to it. There...

Height did not update when switch from portrait to Landscape?

ios,objective-c,iphone,landscape-portrait

Override didRotateFromInterfaceOrientation method on your ViewController and change the frame of the scrollView. - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; self.menuScrollView.frame=CGRectMake(0,yPosition,width,self.view.frame.size.height); } ...

NSPredicate crash with path which contains square brackets

objective-c,cocoa,nspredicate

If you need to match [ and ] you can use matches operator, which uses regular expressions. Example: NSArray *array = @[@"[apple]", @"[boy]", @"[dog]", @"cat"]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"self matches %@", @"\\[dog\\]"]; NSLog(@"%@", [array filteredArrayUsingPredicate:pred]); About your update: predicateWithFormat is not like stringWithFormat, as it does some additional jobs...

What is the best practice add video background view?

ios,objective-c,swift,video

First of all, you have two main choices: use a imageView with a GIF or use a video for background with AVPlayer or MPMoviePlayerController. You can find a lot of example for both ways, here's a few: use a GIF for cool background video cover iOS In reply to your...

Checking If One Array Contains An Object of Another Array In Objective C

ios,objective-c,arrays

OK, somehow I found the answer here NSArray containObjects method. According to what they say. The documentation states that the method "containsObject:" is used for comparing the reference of the objects, and not the value itself. No wonder the time when I passed a hardcoded NSString in the for loop,...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

ios,objective-c,multithreading,swift,grand-central-dispatch

This will not deadlock since the dispatched block can start running immediately - it's not a serial queue so it doesn't have to wait for the current block to finish. But it's still not a good idea. This will block one thread causing the OS to spin up a new...

In objective-c how can i get the “url” and “content” between tags using regular expression?

html,objective-c,regex

You also need to match the extra parameters present inside the anchor tag. "<a\\b[^>]*\\bhref=\"(.*?)\"[^>]*>(.*?)</a>" or "<a\\b[^>]*\\bhref=\"([^"]*)\"[^>]*>(.*?)</a>" Then get the strings you want from group index 1 and 2. Your regex matches all the following chars (ie, chars next to href attribute) because it looks for an > symbol just after...

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring

appendString: is from NSMutableString, stringByAppendingString: is from NSString. The first one mutates the existing NSMutableString. Adds to the end of the receiver the characters of a given string. The second one returns a new NSString which is a concatenation of the receiver and the parameter. Returns a new string made...

How to prevent duplicate entry on parse?

ios,objective-c,iphone,swift,parse.com

I suggest to implement a simple beforeSave trigger, on Parse Cloud code, in order to check if the new entry song already exist (basically you're going to make one or more field uniques. For example: Parse.Cloud.beforeSave("Musics", function(request, response) { var newEntrySong = request.object; var querySongs = new Parse.Query("Musics"); querySongs.equalTo("title", newEntrySong.get("title"));...

drawing views after time intervals

ios,objective-c

Create this method: -(void) drawViewsEvery5Seconds { if(!lastView)//should be a member variable { lastView = [[UIView alloc] initWithFrame:CGRectMake(0, 580, 16, 25)]; } else { lastView = [[UIView alloc] initWithFrame:CGRectMake(lastView.frame.origin.x+16, 580, 16, 25)]; } lastView.backgroundColor = [UIColor blackColor]; [self.view addSubview:lastView]; [self performSelector:@selector(drawViewsEvery5Seconds) withObject:nil afterDelay:5]; } and then just call [self drawViewsEvery5Seconds]; UPDATE...

How can i use MapKit View in Xcode 6.3?

ios,objective-c,iphone

Make sure you have added MapKit Framework in your project and try to follow some basic tutorial IOS8 Mapkit tutorial...

Assigning a variable from another class

ios,objective-c,methods,protocols

viewClass.h @protocol ViewClassDelegate -(void)buttonWasClicked:(NSString *)aString; @end viewClass.m [submitButton addTarget:self action:@selector(submitButtonTapped) forControlEvents: UIControlEventTouchUpInside]; - (void)submitButtonTapped { [self.delegate buttonWasClicked:@"this is a string"]; } mainVC.m // Imported and called the delegate in mainVC.h. Then in .m I set the delegate -(void)buttonWasClicked:(NSString *)aString { // aString = this is a string } ...

Initializing a xib view as a subview of another NSView

objective-c,osx,cocoa,xib,nib

You could use the loadNibNamed:owner:topLevelObjects: method. Here's an example: NSArray *views = nil; [[NSBundle mainBundle] loadNibNamed:@"TestView1" owner:nil topLevelObjects:&views]; [self.view addSubview:[views lastObject]]; The above code will load the top-level contents of the XIB into an array. Per the documentation: Load a nib from this bundle with the specified file name and...

Blocking a Loop Using UIAlertController

ios,objective-c,swift,uialertcontroller

Use Recursive Function rather than loop Example var name:[String] = ["abcd","efgh","ijkl","mnop","qrst","uvwx"] self.friendReuqest(name, index: 0) func friendReuqest(name:[String],index:Int) { if index < name.count { let alertController = UIAlertController(title: name[index], message: "Would you like to accept this friend request?", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel){ (action: UIAlertAction!) -> Void...

KVO. ObserveValueForKeyPAth is not called

objective-c,nsmutablearray,key-value-observing

The problem was that I was trying to observe an array which was not possible that way.

Trying to dismiss a popover view controller with a table view inside of it

ios,objective-c,uipopovercontroller

You have to set the delegate of your AssistanceNeededAtPopOverViewController that pops the controllerview, as the new GlobalPageSideDetailViewController. Here you're setting the delegate of a controller you just instantiate and not the one which poped the controller. ...

Copying Variable Names

objective-c

The correct modern style is to use ARC (automatic reference counting) in your project, which is the default for new projects (and has been for a few years). Then you do not need to, and are not allowed to, send the release message. The choice of initWithString: vs. stringWithString: makes...

Navigation Bar disappeared when rotate the device

objective-c

Check the Navigation Controller properties in the interface builder, and make sure that Hide Bar When Vertically Compact is unchecked ...

How to know a file is writing via NSFileManager

ios,objective-c,iphone,nsfilemanager

NSFileCoordinator and NSFilePresenter are created just for that. You may find interesting Advanced iCloud Document Storage video from wwdc that covers the usage of this classes. Building a Document-based App will be great to watch too.

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch

dispatch_sync will block the caller thread until execution completes, a concurrent queue has multiple threads so it will only block one of those on that queue, the other threads will still execute. Here is what Apple says about this: Submits a block to a dispatch queue for synchronous execution. Unlike...

remote data fetching inside model object in objective c using AFNetworking

ios,objective-c,rest,model-view-controller,afnetworking-2

I dont have anything to say about your MVC(Model–view–controller) correct? I just want to add something that may be useful approach avoiding unwanted crashes.. First is under [[MyAPI sharedInstance] POST:@"auth/" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) { if([responseObject objectForKey:@"id"]) { [[NSUserDefaults standardUserDefaults] setObject:(NSDictionary*) responseObject forKey:USER_KEY]; [[NSUserDefaults standardUserDefaults] synchronize]; result = [responseObject...

Objective C - bold and change string text size for drawing text onto pdf

objective-c,xcode,pdf,size,bold

Solved it by making a separate method as below (I used + since I have this inside an NSObject and is a class method rather than in a UIViewController): +(void)addText:(NSString*)text withFrame:(CGRect)frame withFont:(UIFont*)font; { [text drawInRect:frame withFont:font]; } Outside the method, declaring inputs and calling it: UIFont *font = [UIFont fontWithName:@Helvetica-Bold"...

I am doing demo for video streaming as same as source code from git hub but I am getting errors?

ios,objective-c,iphone

It seems the included library are not compiled for i386 (or simulators) so you must run code on real device. See author comment here and here

Size Class Initially Unknown

ios,objective-c,storyboard,size-classes

There are two to prevent this problem (1) Load your entire method in -(void)viewDidAppear:(BOOL)animated { } (2) Do the following step Go to file Inspector Uncheck "Use size classed ...

Set NSObject property - EXC_BAD_ACCESS

ios,objective-c,exc-bad-access,nsobject

Verify that [dict objectForKey:@"infos"] is not NSNull - Crash can be here. Other code looks OK. Also add -(void)deallocto your object and put a break point there to verify that the object is not being released before the assignment. ...

VoIP limiting the number of frames in rendercallback

ios,objective-c,audio,core-audio,audiounit

You can (and should) use kAudioUnitProperty_MaximumFramesPerSlice to specify the maximum number of samples per frame, not the preferred number; please refer to Apple's Technical Q&A QA1533 and QA1606. To set the preferred number of samples per frame, use the setPreferredIOBufferDuration:error: method of AVAudioSession. For example, if the sample rate is...

Is there a strong case against making my TyphoonAssembly a singleton? If so, why? If not, is there a recommended way to do so?

ios,objective-c,dependency-injection,typhoon

I don't think anything will break if you make your assembly a singleton, but it should never be necessary. Your assemblies contain recipes or blueprints to instantiate objects, and at startup, behind the scenes, all of this information goes into a TyphoonComponentFactory. The assemblies themselves, at this point, have essentially...

Xcode referencing old copies of files

ios,objective-c,xcode,file-management

Xcode does not keep the source files, it just points to them. Most likely you are editing a copy Xcode is not using. In Xcode check the location of the file it is using: ...

How to do a “show (e.g Push)” segue programatically without animation?

ios,objective-c,swift,storyboard,segue

What the show (e.g. Push) segue does internally is to call -[UIViewController showViewController:sender:] Calling this method on your view controller itself, will trigger the appropriate way of presenting the view controller you are passing. // Swift self.showViewController(viewControllerToShow, sender: self) // Objective-C [self showViewController: viewControllerToShow sender: self]; The animation can be...

Cursor doesn't update in NSTextField as it autoresizes when resizing the enclosing NSWindow

objective-c,cocoa,nstextfield,autoresize,nscursor

Interesting question, I've never applied auto-layout to a text field so I was curious myself. My solution was to listen for the NSWindowDelegate method, -windowDidResize. Upon that, I would check to see if the text field was the first responder. If it was, I set it to be first responder...

NSString to NSDate doesn't work

ios,objective-c,nsdateformatter

You have to set the date format as the string NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; NSDate *date = [dateFormatter dateFromString:myDate]; //Set New Date Format as you want [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSLog(@"%@",[dateFormatter stringFromDate:date]); ...

NS_ENUM as property in protocol

ios,objective-c,automatic-ref-counting

You needs to synthesize the property: @implementation Application @synthesize applicationState = _ applicationState; @end or declare the property again: @interface Application : NSObject <ApplicationProtocol> @property (nonatomic) ApplicationState applicationState; @end ...

Set background color of .xib launch image background

objective-c

For the launch .xib you won't be able to change the color programmatically. You can input hex values in the side menu. Click on background color, choose the second object from the left, and you can input hex values along with RGB values. User the color hex website to convert...

Using sockets to build real time chat for iOS?

ios,objective-c,sockets,chat,real-time

Assuming you've got your server side things setup, you can use Square's Socket Rocket to implement the client side https://github.com/square/SocketRocket If you're using socket.io at the backend, there are plenty of iOS libraries available for those as well. SIOSocket is one such library....

Setting up NSPredicate with a phrase and number sequence

objective-c,nspredicate

You can use an NSPredicate with a regular expression. NSArray *testArray = @[@"SPOT1234", @"SPOT0483", @"SPAT1234", @"spot1234", @"SPOT123", @"SPOT1233232"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '^SPOT\\\\d{4}$'"]; NSArray *resultsArray = [testArray filteredArrayUsingPredicate:predicate]; The resultsArray will contain two strings: SPOT1234, SPOT0483...

UIToolbar with UISegmentedControl AutoLayout (/full width)

ios,objective-c,autolayout,uisegmentedcontrol,uitoolbar

I created a toolbar with a segmented control inside, then made the segmented control 320 wide. I then set flexible layout guides on each side to force the segmented control into the center. This looks fine in portrait, but the segmented control will not stretch out for landscape. Portrait (includes...

Is it possible to highlight ObjC code in Intellij IDEA?

objective-c,intellij-idea,syntax-highlighting

I found this, but it is only syntax highlighting, not auto-complete. For that I'am afraid you will have to use AppCode or Xcode. https://github.com/jkaving/intellij-colors-solarized...

Filter array based on coordinate from mapview frame in objective C

ios,objective-c,xcode,annotations,mkmapview

What you could do is: A) get the annotations directly: MKMapRect visibleMapRect = mapView.visibleMapRect; NSSet *visibleAnnotations = [mapView annotationsInMapRect:visibleMapRect]; B) Loop through your array and check whether the point is inside: MKMapRect mapRect = mapView.visibleMapRect; for (NSDictionary *item in array) { CLLocation *location = item[@"location"]; // Or what ever you...

starting to work with iOS push notifications

ios,objective-c,push-notification

You are using the API wrongly. First of all the Push Notification API has changed after iOS 8.0. My answer will assume that you want to still supporting iOS 7.x and later // Checks if the application responds to the API introduced in iOS 8. if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) { //...

AVCaptureOutput didOutputSampleBuffer stops getting called

ios,objective-c,avfoundation,avcapturesession

Your problem is actually referenced in the Docs, Specifically; If your application is causing samples to be dropped by retaining the provided CMSampleBufferRef objects for too long, but it needs access to the sample data for a long period of time, consider copying the data into a new buffer and...

UIButton with pushViewController that is declared in another class

ios,objective-c,uiviewcontroller,uibutton

Probably the addTopBarToScreen is in another class, that is unrelated to the HomeViewController and doesn't have the productSheetsButtonFunction defined. You can do this in several ways, but the simplest one, reusing your structure, is to pass the target in the addTopBarToScreen method, like this: - (void)addTopBarToScreen:(UIView *)screen target:(id)target Then, in...

iOS - Automatically Have Keyboard Toggled On ViewController

ios,objective-c,keyboard

in the ViewDidAppear: [yourTextField becomeFirstResponder]; ...

how i can solve Image auto resize in iphone 4 5 6 6+

ios,objective-c,iphone,objective

understand the autoresize concept , the following image is the description that how to we use the autoresizing on Left, right , top and bottom. So, I used to think according to this snapshot: Scenario 1: (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight) // it automatically set the width, height, left and bottom: Scenario...

After an insert into the UITableView : custom the cell

ios,objective-c,uitableview

You need to use UITextField instead of UILabel. When you insert a new cell, set this UITextField's enabled property to true. When loading all the other cells remember to set it to false to disable editing (the same cell maybe used at more than one place)....

Call function on Server from iOS app - Objective C

ios,objective-c,json,server,backend

You just need to POST data to your server. Port could be anything you want, should be 80. Host your script with a domain url so that you can make network request publicly. You can try this function: -(NSData *)post:(NSString *)postString url:(NSString*)urlString{ //Response data object NSData *returnData = [[NSData alloc]init];...

how to share screenshot to Facebook

objective-c,facebook,facebook-sdk-4.0,social-media

I believe you want to FBSDKSharePhotoContent and FBSDKShareDialog. You need to setup your content as a photo(s): UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext(); FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init]; content.photos = @[[FBSDKSharePhoto photoWithImage:screengrab userGenerated:YES]]; // Assuming self implements <FBSDKSharingDelegate> [FBSDKShareAPI shareWithContent:content delegate:self]; ...

Set color CFAttributedStringRef

ios,objective-c

Based on the comments on the question, you mentioned that the words will never change. You could potentially create a whole bunch of if/else statements checking every word selected against every word in an array. I have put this down as a more efficient alternative and it should hopefully work....

iPhone - get amplitude of audio at current point

ios,objective-c,iphone,avaudioplayer

I'm not sure if I'm interpreting your code correctly, but it looks like you might be instantiating your player every frame with would explain the slowness. You need to set your player up ahead of time. Then on your timer, call updateMeters right before you get averagePowerForChannel. I'm not familiar...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

ios,objective-c,swift

How about -searchBarTextDidEndEditing: in UISearchBarDelegate?

Does NSURLSession Take place in a separate thread?

ios,objective-c,grand-central-dispatch,nsurlsession

Yes, NSURLSession does it's work in a background thread. The download ALWAYS takes place on a background thread. You can control whether it's completion methods are executed on a background thread or not by the queue you pass in in the delegateQueue parameter to the init method. If you pass...

How to push a view from project that based on Tab Bar Controller

objective-c

What you need to do is to put the TableViewController inside UINavigationController so that you can push a new ViewController [self.navigationController pushViewController:prue animated:YES]; That came be done either in the storyboard by adding the NavigationController into the TabViewController and put your ViewController as its root http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1 Or in code as...

iOS: Programmatically called segue not working

ios,objective-c,swrevealviewcontroller

Always perform a segue in the main queue. Your callback is executing in the separate NSOperationQueue, you need to wrap performSegueWithIdentifier in dispatch_async(dispatch_get_main_queue,.... Plus, as @rory-mckinnel mentioned in the comments, remove unnecessary [super viewDidLoad] calls as in may lead to unexpected results....

Updating Core Data Model using two separate View Controllers

ios,objective-c,uitableview,core-data

I resolved this. Here is what was done. First off there was serious cleanup of files, arrangement, etc. There were some objects, attributes, etc., that didnt make sense. Renaming things helped a lot as I was causing a lot of confusion. There was a one-to-one relationship between my List and...

Auto Rotation iOS 8 Navigation Controller

objective-c,iphone,ios8,uinavigationcontroller,autorotate

Just subclass UINavigationController and override appropriate methods: .h File: @interface CustomUINavigationController : UINavigationController @property BOOL canRotate; @end .m File: @implementation CustomUINavigationController - (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...

__createApplicationIconFromImage_block_invoke: Error: unable to create icon mask image from image named “AppIconMask.png” at scale 2.0

ios,objective-c,cordova,phonegap-plugins

This solved me issue. It is working fine now after following below steps https://discussions.apple.com/thread/6742087?start=0&tstart=0 To troubleshoot this issue where your iPhone is unresponsive, please follow the steps outlined below: 1. If a single application is not responding or stops responding when it opens, you can force it to close. 2....

Fit a UIImageView to a UIImage

ios,objective-c,uiimageview,autolayout

Based on this Stack Overflow answer, we can get the size of a UIImage by accessing its size property. So, from here, the easiest way to proceed is using autolayout. Set up your storyboard or xib with your image view on it. Go ahead and give your image view an...

How can I find out the Objective-C generics type?

ios,objective-c,xcode,generics

The lightweight generics introduced in Xcode 7 are just compile time hints to help the compiler raise warnings, but at run time you get the same old behavior with your variable being just NSArrays of ids. Source: WWDC '15 "Swift and Objective-C Interoperability" session See the transcript of the talk:...

Indent second line of UILabel

ios,objective-c,uilabel

Use an NSAttributedString for your label, and set the headIndent of its paragraph style: NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; style.headIndent = 14; NSDictionary *attributes = @{ NSParagraphStyleAttributeName: style }; NSAttributedString *richText = [[NSAttributedString alloc] initWithString:@"So this UILabel walks into a bar…" attributes:attributes]; self.narrowLabel.attributedText = richText; self.wideLabel.attributedText = richText; Result:...

Slide in an UIButton and push other UIButton when a certain distance is reached

ios,objective-c,uiviewanimation,nslayoutconstraint

Since you would expect the orange button to move at some point, you can't force it to be centered. Lower the priority from 1000 to something lower. This means: I would really like it to be centered, but it doesn't have to be. Add a horizontal distance (leading/trailing) constraint...

When replicating UIAlertView; background is not the same

ios,objective-c,uiview,uialertview

Try adding backgroundView into self.view.window, not self.view.

UIWebView path depends on previous pressed button Xcode

ios,objective-c,iphone,xcode,uiviewcontroller

in your ClassA.m - (IBAction)button1:(UIButton *)sender{ path=[[NSBundle mainBundle] pathForResource:@"filename" ofType:@"pdf"]; [self performSegueWithIdentifier:@"yourIdentifierName" sender:self]; } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"yourIdentifierName"]) { classB *clsB =segue.destinationViewController; clsB.typeofSelect=path; } } in your class B.h @property (nonatomic, weak) NSString *typeofSelect; in your Class B.m @synthesize typeofSelect;...

Load images from “HTTPS” type of url and display in UIImageview

ios,objective-c,https,uiimageview,xcode6

Issue resolved by modifying some parameters into the framework for webservice calling created by me. All those changes were as per the server which I was calling to. Thanks...

Unexpected NSWindow becomes key window

objective-c,cocoa,nswindow,keywindow

Somewhat predictably this was fixed by swapping the order of the last two lines: [self.previousWindow orderOut:self]; [newWindow makeKeyAndOrderFront:self]; I initially had concerns that doing things in this order in an application where applicationShouldTerminateAfterLastWindowClosed returns YES might cause the application to close prematurely but this does not seem to be the...

SceneKit + Collada + animation

objective-c,animation,blender,scenekit,collada

3DSMax + OpenCollada exporter works great.

CFNotificationCenterRemoveEveryObserver not removing the observer

ios,objective-c

providing an identifier for your observer. CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), "observer identifier", ringerSwitched, CFSTR("com.apple.springboard.ringerstate"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately); CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetDarwinNotifyCenter(), @"observer identifier"); ...

Get warning when convert double to NSDecimalNumber

ios,objective-c,methods,double,nsdecimalnumber

numberWithDouble: method of NSDecimalNumber returns NSNumber. In your method you want to return decimal so its OK if you allocate a new NSDecimalNumber with the decimal value (amount in your example). May use the following way to get rid of the error: -(NSDecimalNumber *)myMethod { double amount = 42; ......

NSTimer firing more than it should

ios,objective-c,selector,nstimer

You are failing to track existing timers and are, instead, creating multiple timers, which is why you are getting them firing multiple times. Use instance variables, and only create a timer if it's currently invalid: case blinkingGreen: self.greenLamp = YES; self.yellowLamp = NO; self.redLamp = NO; [self createBlinkingTimer]; break; case...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

ios,objective-c,swift,uitextfield,uilabel

You can register your textField for value change event: [textField addTarget: self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged]; and in textFieldDidChange function update your label: - (void)textFieldDidChange { label.text = textField.text; } The function shouldChangeCharactersInRange is needed more for taking desisions whether to allow upcoming change or not...

Facebook logout iOS SDK

ios,objective-c,iphone,facebook

try this one : FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logOut]; ...

How can I get my iPhone to listen for sound frequencies above a certain threshold?

ios,objective-c,iphone,audio

The fact that I wrote that code helps me answering this question but the answer probably only applies to this code. You can easily limit the frequencies you listen to just by trimming that output array to a piece that contains only the range you need. In details: To be...

objective c - click table row and go to another page

ios,objective-c,tablerow

Try the method didSelectRowAtIndexPath - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self performSegueWithIdentifier:@"ShowDetail" sender:tableView]; } If you want to pass a variable or perform an action before it segues, do the following: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"ShowDetail"]) { //Do something Detail *detailController = (Detail*)segue.destinationViewController; } } If you...

Multiple ways to present UIViewController's view [closed]

ios,objective-c,uiview,uiviewcontroller

Really there are only 2 options to display ViewControllerB from ViewControllerA, and which you use will depend on what you want to achieve - Option 1: Modal presentation Use this if ViewControllerB should take focus away from ViewControllerA entirely until it is dismissed. [self presentViewController:viewControllerB animated:YES completion:nil]; There are a...

NSExpression custom variables inside expression

ios,objective-c,swift,expression

let myInt = 4 let myFormulaInt = "5 + 4 + myInt * 5" let intElements = ["myInt": myInt] let myResultInt = NSExpression(format: myFormulaInt).expressionValueWithObject(intElements, context: nil).integerValue println(myResultInt) // 29 let myDouble = 2.5 let myFormulaDouble = "5 + 4 + myDouble * 5" let doubleElements = ["myDouble": myDouble] let myResultDouble...

Build error after I localized Info.plist

ios,objective-c,xcode,swift,localization

Roll back those changes, add a InfoPlist.strings file to your project, localize it and then add the needed keys to it. For example: "CFBundleDisplayName" = "App display name"; "CFBundleName" = "App bundle name"; ...

Multiple NSURLSessions Causing UITableView Problems

ios,objective-c,uitableview,nsurlsession

Besides assuming that your network requests aren't erroring (you should at least log if there are network errors), there are threading issues. Your NSURLSession callback probably runs on a background thread. This makes it unsafe to call UIKit (aka - [_tableView reloadData]). UIKit isn't thread safe. This means invoking any...

Programmatically using constraints to center a UIIMageView

ios,objective-c,uiimageview,autolayout,xib

Try that : // Width constraint [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.logoImage attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0]]; // Height constraint [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.logoImage attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.backgroundImageView attribute:NSLayoutAttributeHeight multiplier:0.5...

Read plist inside ~/Library/Preferences/

objective-c,xcode,osx

You need to use NSString method: stringByExpandingTildeInPath to expand the ~ into the full path. NSString *resPath = [@"~/Library/Preferences/" stringByExpandingTildeInPath]; NSLog(@"resPath: %@", resPath); Output: resPath: /Volumes/User/me/Library/Preferences ...

How do you work with views in MainMenu.xib?

objective-c,xcode,osx,cocoa

So the default is that your main application window is an outlet in the app delegate. You should keep MainMenu.xib's owner as the app delegate. A common alternative, if you are creating your own custom window controller, is to create a property in the AppDelegate of type CustomWindowController, then in...

Call textFieldDidEndEditing of UITextField when press UIButton

objective-c,uitextfield

In the button handler method, call: [self.view endEditing:YES]; This will force the keyboard to disappear and whatever the current text field had the focus will resign first responder and the textFieldDidEndEditing: method will be called for it. The above assumes the button handler is in the view controller class. Since...

pushviewcontroller doesn't work?

ios,objective-c,pushviewcontroller

Update your AppDelegate.m file with following code self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; ExampleViewController *exampleViewController = [ExampleViewController new]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:exampleViewController]; self.window.rootViewController = navController; //self.window.backgroundColor = [UIColor lightGrayColor]; [self.window makeKeyAndVisible]; The problem is that you are not initializing rootViewController from...

iOS Bring UIView up before keyboard?

ios,objective-c,uiview,keyboard

Instead of doing this manually. use TPKeyboardAvoidingScrollView. Its easy to use. First take UIScrollView and put ur all views inside it. For use with UITableViewController classes, drop TPKeyboardAvoidingTableView.m and TPKeyboardAvoidingTableView.h into your project, and make your UITableView a TPKeyboardAvoidingTableView in the xib. If you're not using a xib with your...

Setting delegates (for protocols) only works in prepareForSegue?

ios,objective-c,delegates,protocols

When instantiated from a storyboard, the initWithCoder: methid is called, not the init method. DestinationViewController *destinationVC = [[destinationViewController alloc] init]; destinationVC.delegate = self; is how you do when your controller is not from a storyboard: you init it from the code. After that you have to manually handle the transition...

Dispatch group and NSNotification

objective-c,grand-central-dispatch,nsnotificationcenter,nsnotification

Thanks @Sega-Zero for your guidance. Here is the solution I implemented. _operationQueue = [[NSOperationQueue alloc] init]; _semaphore = dispatch_semaphore_create(0); NSOperation *uploadOperation = [NSBlockOperation blockOperationWithBlock:^{ [self doFirstTask]; }]; NSOperation *downloadOperation = [NSBlockOperation blockOperationWithBlock:^{ dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); }]; NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{ [self doNextMethod]; }]; [completionOperation...

Google Drive API (GTL) - Create multiple folder paths in order?

ios,objective-c,swift,google-drive-sdk,google-api-objc-client

Avoid using a synchronous for loop. The createFolder function should call back when it's complete; that callback should start the next loop iteration.

iPod Touch (5th gen) 'Source type 1 not available' crash when using UIImagePickerControllerSourceTypeCamera

ios,objective-c,ipod-touch

First, You should always validate if the resource is available or not, try using: if(IS_IPAD && imagePicker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){ if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { // present the popover } else { // HEY, YOU CAN'T USE THIS } } From the official docs: Because a media source may not be present...

UITableView(grouped) adds extra empty header at the bottom

ios,objective-c,uitableview

Instead of returning a CGRectZero view for the footer, simply return nil. - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { return nil; } Also you do not seem to have implemented heightForFooterInSection:section. That should return 0.0. This seems to have come up before and it would seem iOS often pads the bottom...

CPU & Memory steadily increase & FPS drops all because of vector movement

ios,objective-c,sprite-kit

I have figured out my own problem. During character movement through touch, the SKScene's -(void)update:(NSTimeInterval)currentTime method runs that characters class method [_player GPS:currentTime]; which tracks speed and distance. Here's the hiccup, that method sets the character texture according to the direction he is facing. Every frame the same texture continues...

Progressive HMAC SHA256 in Objective-C

javascript,objective-c,cryptography,hmac,cryptojs

HMAC-SHA256 sample code: + (NSData *)hmacSha256:(NSData *)dataIn key:(NSData *)key { NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; CCHmac( kCCHmacAlgSHA256, key.bytes, key.length, dataIn.bytes, dataIn.length, macOut.mutableBytes); return macOut; } Notes: Add Security.framework to the project Common Crypto must be included: #import <CommonCrypto/CommonCrypto.h> This is data in and out, add any conversions to desired representations...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error

ios,objective-c,swift

If you look at the method you have defined in Objective C image category, it is instance method and you are trying to call it using UIImage class in swift. You can basically use either one of the following two approaches, Either, self.backgroundImageView.image = self.someImage.applyDarkEffect() // notice the method does...