iphone,ios7,ios8,screen-orientation,interface-orientation , Restrict Interface Orientation in iOS 7 and iOS 8


Restrict Interface Orientation in iOS 7 and iOS 8

Question:

Tag: iphone,ios7,ios8,screen-orientation,interface-orientation

I am trying to implement something where I stuck at one point.

I want some orientation restrictions as follows:

I have tried all the combination of coding. Finally I got solution for iOS 8

**(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window  // iOS 6 autorotation fix
{**


        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){

            if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
            {
                if(IS_IPHONE_4_AND_OLDER){

                    printf("Device Type : iPhone 4,4s ");
                    return UIInterfaceOrientationMaskPortrait;
                }
                else if(IS_IPHONE_5){

                    printf("Device Type : iPhone 5,5S/iPod 5 ");
                    return UIInterfaceOrientationMaskPortrait;
                }
                else if(IS_IPHONE_6){

                    printf("Device Type : iPhone 6 ");
                    return UIInterfaceOrientationMaskPortrait;
                }
                else if(IS_IPHONE_6P){

                    printf("Device Type : iPhone 6+ ");
                    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
                }
            }
            return UIInterfaceOrientationMaskPortrait;
        }
        else{

            printf("Device Type : iPad");
            return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
        }
}

By using above code I manage for iOS 8 But it does not work in iOS 7 or less

Please help me to solve this ...

Thank you


Answer:

Simple but it work very fine. IOS 7.1 and 8

AppDelegate.h

@property () BOOL restrictRotation;

AppDelegate.m

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

if(self.restrictRotation)

    return UIInterfaceOrientationMaskPortrait;
else

    return UIInterfaceOrientationMaskAll;

}

ViewController

At top: To Detect Device Type

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

#define IS_IPHONE_5_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_IPHONE_6_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0f)
#define IS_IPHONE_6P_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS7 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0f)

#define IS_IPHONE_5_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 568.0f)
#define IS_IPHONE_6_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 667.0f)
#define IS_IPHONE_6P_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) == 736.0f)
#define IS_IPHONE_4_AND_OLDER_IOS8 (IS_IPHONE && ([[UIScreen mainScreen] nativeBounds].size.height/[[UIScreen mainScreen] nativeScale]) < 568.0f)

#define IS_IPHONE_5 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_5_IOS8 : IS_IPHONE_5_IOS7 )
#define IS_IPHONE_6 ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6_IOS8 : IS_IPHONE_6_IOS7 )
#define IS_IPHONE_6P ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_6P_IOS8 : IS_IPHONE_6P_IOS7 )
#define IS_IPHONE_4_AND_OLDER ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_IPHONE_4_AND_OLDER_IOS8 : IS_IPHONE_4_AND_OLDER_IOS7 )

Then Add Function Below:

-(void) restrictRotation:(BOOL) restriction{

AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.restrictRotation = restriction;}

viewDidLoad

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){

    if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
    {
        if(IS_IPHONE_6P){

            printf("Device Type : iPhone 6+ ");
            [self restrictRotation:NO];
        }
        else{

            printf("Device Type : iPhone 6 ");
            [self restrictRotation:YES];
        }
    }
}
else{

    printf("Device Type : iPad");
    [self restrictRotation:NO];
}

Related:


first tap not registering on collectionView Xcode


objective-c,xcode,ios7,uiviewcontroller,collectionview
I have a collectionView with an array populating it. I have it set up that when a cell is tapped a second modal view is presented. The problem is that the first tap is not recognized. The collectionView in storyboard, along with the cell and the image inside the cell...

iOS Swift: Sound not playing on iPhone Simulator


ios,iphone,swift,audio,ios-simulator
In my iOS Swift application, and i am trying to play sound on click of a button. func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.play() } I am running the application in iOS iPhone Simulator. I have doorbell.mp3...

Pass data in modal segue in storyboard?


ios,objective-c,iphone,storyboard,modalviewcontroller
My real problem is i want to pass data from childViewController to parentViewController in storyboard by modal segue. Code parentViewController.h @property (strong, nonatomic)NSMutableArray *address; childViewController.m parentViewController *parent=(parentViewController *)self.presentingViewController; [email protected]"Hello World"; This code throw exception like Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainTabbarViewController setAddress:]: unrecognized selector sent to instance...

Is it possible to obtain an unique iCloud user ID on cocoa?


ios,iphone,cocoa,ipad,icloud
My iOS app is currently on beta in TestFlight, and as a way to retribute to the nice people who helped me test it I would like to offer them some goodies such as, for instance, the full final version of the app for free. For this, I was thinking...

How to know a file is writing via NSFileManager


ios,objective-c,iphone,nsfilemanager
I got a problem , How to know the file is accessible ??? For example , the file is writing , but not finish yet. And I check the file again , I use [[NSFileManager defaultManager] fileExistsAtPath:filePath]; It return true ... but the file is not accessible . How to...

iPhone - get amplitude of audio at current point


ios,objective-c,iphone,avaudioplayer
First off: I don't know much about audio processing. I know with Core Audio, you can get the info about a playing track. My goal is to have a node in SpriteKit with the current amplitude/loudness of the current song from iTunes being its scale (say, scale should be at...

Objective c - ios : How to pick video from Camera Roll?


ios,objective-c,iphone,xcode,uiimagepickercontroller
I try this : UIImagePickerController *videoPicker = [[UIImagePickerController alloc] init]; videoPicker.delegate = self; videoPicker.modalPresentationStyle = UIModalPresentationCurrentContext; videoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; videoPicker.mediaTypes = @[(NSString*)kUTTypeMovie, (NSString*)kUTTypeAVIMovie, (NSString*)kUTTypeVideo, (NSString*)kUTTypeMPEG4]; videoPicker.videoQuality = UIImagePickerControllerQualityTypeHigh; [self presentViewController:videoPicker animated:YES...

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


ios,objective-c,iphone,audio
I'm interested in getting my iOS app to turn on the microphone and only listen for frequencies above 17000 hz. If it hears something in that range, I'd like the app to call a method. I was able to find a repository that detects frequency: https://github.com/krafter/DetectingAudioFrequency And here is a...

Orientation of screen?


ios,iphone,swift,sprite-kit
How do I make sure that the only orientations allowed are Portrait or Upside down portrait? I made the change in the project settings, but I'm having trouble making the change in my GameViewController. I need to make the change in this function: override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if...

UIButton with single press and long press events swift


ios,iphone,swift,uibutton
I want to trigger two action on button click and button long click. I have add a UIbutton in my interface builder. How can i trigger two action using IBAction can somebody tell me how to archive this ? this is the code i have used for a button click...

change Auto Layout dynamically


ios,iphone,xcode,storyboard,autolayout
I have to show 3 Labels like LABEL1 | LABEL2 | Label3 //Horizontally I want these 3labels width are equally divided according to Screen size width How can I achieve this with nib file directly? Thanks Question 2 Label1 | Label2 | Lable3 //All Labels widths are equally //All Labels...

How to change element title inside UITableViewCell?


ios,objective-c,iphone,swift,uitableview
I have a button on custom tableviewcell. I've been able add action to this button by add target like below code: var playButton = cell.contentView.viewWithTag(5) as? UIButton var sender : UIButton = UIButton() playButton?.addTarget(self, action: "playPost:", forControlEvents: UIControlEvents.TouchUpInside) playButton?.layer.setValue(object["previewUrl"] as? String, forKey: "songUrl") playButton?.layer.setValue(indexPath.row, forKey: "index") But, how can I...

Height did not update when switch from portrait to Landscape?


ios,objective-c,iphone,landscape-portrait
I create a UIScrollView, added other data in it, added subview to self.view. The problem is that when i switch my phone from portrait to landscape or vice versa it do not update the height so my scrollview do not work as i need to. here is the code: UIScrollView...

Which Image will be used on iPhone 6 device


ios,objective-c,iphone,uiimageview
I have added @1x, @2x, & @3x images in asset catalog. @2x will be used in iPhone 4/4s, iPhone 5. @3x will be used in iPhone 6 Plus. So in iPhone 6 which image will be used? ...

Fatal error when unwrapping CLLocation Location Coordinate


ios,iphone,swift,ios8,optional
I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off. I get a fatal error (unexpectedly found nil when unwrapping option value) When...

iOS gradient effect over UILabel


ios,objective-c,iphone,uilabel
I want to add gradient effect on a UILabel so it look like: Please note the gradient effect on left and right corner.I've no clue how to do that.any help or suggestion would be appreciated. Edit: - I tried with this code- UIColor *endColor = [UIColor colorWithRed:20/255.0 green:157/255.0 blue:189/255.0 alpha:1.0];...

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


ios,objective-c,iphone
[1]: https://github.com/slavavdovichenko/MediaLibDemos3x From this link I downloaded source code and I am running it in X-Code 6.3.2 but I am getting two errors can any one check it please give me a solution. Error 1- Undefined symbols for architecture i386: "_OBJC_CLASS_$_BroadcastStreamClient", referenced from: objc-class-ref in ViewController.o Error 2- ld: symbol(s)...

AFNetworking file upload


ios,iphone,xcode
I'm trying to upload file with AFNetworking and it is working with iOS Simulator but not working Real devices, i tried 2 different way but same. Can some one help me to solve this issue please Thank you very much. this is first code NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask,...

Coco2dx - Changing To Background Image


ios,iphone,xcode,xcode6,ios-simulator
I need someone's help. Actually I have no idea what to replace to get a custom background image. I'm just can't do it anymore. -(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super's" return value if( (self=[super initWithColor:ccc4(219,31,94, 999)]) ) { ws=[[CCDirector...

trying to do a rate us UIAlertController


ios,iphone,swift,uialertcontroller
Whenever I run my app the following error is called Warning: Attempt to present "The alert" on "MenuViewController" whose view is not in the window hierarchy! what exactly does this mean and how do I fix it? I only have one UIViewController and here it is class MenuViewController: UIViewController {...

Underline in attributed text not working in iPhone 6+


ios,iphone,nsattributedstring
I want to create a method that returns me attributed text. here is the code that i am using - (NSAttributedString *)getUnderlineAttributedStringForText:(NSString *)strWholeString andTextToHaveLink:(NSString *)strLink TextColor:(UIColor *)textColor LinkColor:(UIColor *)linkColor withFont:(UIFont*)font { NSRange stringRange = NSMakeRange(0, strWholeString.length); NSRange linkRange = [strWholeString rangeOfString:strLink]; NSLog(@"String Link :: %@",[strWholeString substringWithRange:linkRange]); NSMutableAttributedString *attributedString =...

How to prevent duplicate entry on parse?


ios,objective-c,iphone,swift,parse.com
I' trying to save song info to parse, but if the song already exist in parse I want my code just do nothing. I've tried this code below: var Music = PFObject(className:"Musics") var query = PFQuery(className:"Musics") query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil {...

Facebook logout iOS SDK


ios,objective-c,iphone,facebook
In the latest SDK of Facebook for iOS 8, the login button itself changes to logout once the user logs in successfully. I have a separate logout button in my applications. When the user is successfully logged in using my own server credentials, google+ or facebook, the app takes the...

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


ios,objective-c,iphone,objective
I give three types of image like image.png [email protected] [email protected] but not working image autoresize in all device....

How to justify label text?


ios,objective-c,iphone
My code to justify label text is given below:- -(void)justifyToLabel:(UILabel*)label withStr:(NSString*)str{ NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init]; paragraphStyles.alignment = NSTextAlignmentJustified; NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyles}; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString: str attributes: attributes]; label.attributedText = attributedString; } I don't know that why its not working. Please give a best...

How to transfer files from iPhone to EC2 instance or EBS?


ios,iphone,amazon-ec2,amazon-s3,amazon-ebs
I am trying to create an iOS app, which will transfer the files from an iPhone to a server, process them there, and return the result to the app instantly. I have noticed that AWS offers an SDK to transfer files from iOS app to S3, but not to EC2...

GCM support for ios application when application in background or killed


ios,iphone,xcode,android-gcm
Hello all i am integrating GCM in iOS application using following link https://developers.google.com/cloud-messaging/ios/start. I have also uploaded the certificates when configuring the file on defined steps. I have also succeeded for getting notification,but the problem is that i am not getting the notification when the application is killed or in...

How can i use MapKit View in Xcode 6.3?


ios,objective-c,iphone
I am unable to use MapKit in Xcode 6.3. It is showing an error when I am create property for that. The Error is- Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named MKMapView'

UIWebView path depends on previous pressed button Xcode


ios,objective-c,iphone,xcode,uiviewcontroller
I have a ViewController (A), containing n buttons. all buttons map to other ViewController(B) containing a WebView to show a different PDF. Instead of creating n ViewController, I would know how to change path according to which button was pressed. my wrong tries: 1- use tags of buttons in ClassB...

How to Screenshare of my iPad on Mac


iphone,ipad,airplay,screensharing
I have a big demo of my iPad application to my client,i tried AirServer, Bomgar but those are not working to share my iPad Screen on the Mac. Can any one help me which tool i should use for screenshare of my iPad to Mac. If i can share my...

How can I show ONLY the date (and not the time) using NSDateFormatter?


ios,iphone,swift
I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

Delete child SKSpriteNode


objective-c,iphone,sprite-kit,skspritenode
Basically I am trying to make it so that when the user hits a fuel tank the old tank disappears and a new one is spawned in a random location. Right now it's detecting the collision but I can't get rid of the child. It will just add a new...

NSMutableArrays store only 2 objects


ios,iphone,swift,nsmutablearray,nsuserdefaults
I have a weird problem - my mutable array stores only 2 objects - its count is 1,2,2,2 and doesn't change. My only observation is that it always replaces old values f.x. I have: value1 - 2, value2 - 4 and I add next object f.x. 66 and my array...

make autoplay work on IPAD and IPHONE


ios,iphone,ipad,video
I have fullscreen video background, here is my code: <div id="video-container"> <video id="video" autoplay loop> <source src="ocean.mp4" type="video/mp4"> <source src="ocean.ogv" type="video/ogg"> <source src="ocean.webm" type="video/webm"> </video> </div> how you see it has autoplay attrubute, but on IPAD, IPHONE,etc.. it doesn't work untill you click on play button, but when I add...

Splash screen not visible for iPad, only a black screen gets shown


ios,ios7
I have an universal app. The splash screen loads fine for iPhone but the same is not visible on the iPad. Instead a black screen appears in its place. I have gone through the questions posted in this regard and have followed the steps but to no avail. I am...

Check UITextfield have only Alphabet not numeric value


ios,iphone,ios7
I am creating one form I want to check in Name Field if any one enter Number then show alert. Here is the code: NSString *str = abc.text; NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet]; BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""]; if (!(valid)) { NSLog(@"number present"); } else { NSLog(@"number not present");...

Autolayout works great on iOS 8, crashes on iOS 7


ios,ios7,ios8,autolayout
I have an issue where a screen with autolayout that works great on iOS 8 - but crashes on iOS 7. All subviews are configured in the XIB. The error message is: Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference...

coordinate deprecated as of iOS 7


ios,iphone,swift
I am trying to grab the latitude and longitude of a users location. I have a code which worked prior to deprecation, and I cannot figure out how to fix it. The error is on the coordinate section of latestLocation.coordinate.latitude and latestLocation.coordinate.longitude, and the error states: 'coordinate' is unavailable: APIs...

CBCentralManager not calling didDiscoverPeripheral method when iPhone is locked


ios,iphone,cbcentralmanager,ios-bluetooth,cbperipheralmanager
I am working on an app that scans for a specific peripheral, ones peripheral is found it should send the small amount of data. App works in the foreground and also in background. I have also add this code in the plist UIBackgroundModes bluetooth-central When iPhone is locked and peripheral...

create a popup window with just a textview/string and a button SWIFT ios 8


iphone,swift,ios8,popup,xcode6
I am very new to ios 8 and swift but I have not found a way to make a simple popup window whenever a button is pushed. I payed for tutorials and they still don't cover it. All i would like is for when the user pushes a button (the...

Managing user login segues in swift iOS


ios,iphone,swift,view
I am trying to build an initial user login system for an iPhone app. I have created an API which holds all the user data. I have successfully made a HTTP connection from my swift code to my API, where I sent the users login details the API authenticates the...

Customisable iOS Interface


ios,iphone,xcode,user-interface,customization
I am currently developing an iOS app that can be used by different clients keeping pretty much the same interface for all of them. I would like to make this interface somehow “customisable” without having to change the storyboard for every client but I am not sure how to do...

Change database of Live App without Data Lose


ios,iphone,sqlite,core-data
I want to update the database of my existing app(for new version) which is live on the app store. So I need to delete my existing database before using app or I can change the name of the database. After it If data exists in my old database I have...

Dealing with graphical assets for iPhone 5/5S/6/6 Plus


ios,iphone,xcode6,iphone-6,iphone-6-plus
Since the induction of 6 and 6 plus its the first time I'm starting to work on a new app. Now I'm a bit confused about the use of graphical assets for my app. See for 5/5S things were pretty simple. If I have to make an image view of...

Magical Record, cannot save an object: contextDidSave == NO, error = nil


ios,objective-c,iphone,core-data,magicalrecord
I'm trying to persist new entities: - (void)updateStorageWithQuizzess:(NSArray *)quizzess completion:(void(^)(NSArray *quizzess, BOOL succes, NSError *error))completion { NSMutableArray *mutableArray = [NSMutableArray array]; [Quiz MR_truncateAll]; [[NSManagedObjectContext MR_context] MR_saveWithBlock:^(NSManagedObjectContext *localContext) { for (NSDictionary *dictionary in quizzess) { Quiz *quiz = [Quiz MR_createEntity]; [quiz fromDictionary:dictionary]; [mutableArray addObject:quiz]; } } completion:^(BOOL contextDidSave, NSError *error) {...

Setting Autolayout Constraints on UIButton in Swift


ios,iphone,swift,constraints
I'm still trying to get my head around Swift Autolayouts here in XCode 6.3. I have set up a View Controller that I stuck a couple of labels on in Interface Builder. I have added a UITextView and UIImageView programmatically, and am trying to add a UIButton at the bottom...

How to use tests in Xcode (iOS application)


ios,objective-c,iphone,xcode,testing
In every new project I see the file with the content (and this file belongs to different target ProjectNameTests): - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown...

Update Text Field While Automating iPhone App


iphone,xpath,textbox
I am automating an iPhone App. The scenario is Login Logout and re-Login. But while re-login the username and password field is displaying the details. I am trying to list that xpath as a WebElement and clear() that field if(Webelement.gettext() !="") But it is not happening as in the existing...

Auto Rotation iOS 8 Navigation Controller


objective-c,iphone,ios8,uinavigationcontroller,autorotate
I have certain viewControllers which are managed by a UINavigationController (push and pop). I want to restrict different viewControllers to different orientations like the first one should be only in Portrait, second in portrait, third in landscape and fourth can be portrait and landscape both. I set a ViewController on...