Just wondering can I check if the device (iPhone, iPad, iPod i.e. iOS devices) has a Gyroscope ?
- (BOOL) isGyroscopeAvailable
{
#ifdef __IPHONE_4_0
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
BOOL gyroAvailable = motionManager.gyroAvailable;
[motionManager release];
return gyroAvailable;
#else
return NO;
#endif
}
See also my this blog entry to know you can check for different capabilities in iOS devices
http://www.makebetterthings.com/blogs/iphone/check-ios-device-capabilities/
CoreMotion's motion manager class has a property built in for checking hardware availability. Saurabh's method would require you to update your app every time a new device with a gyroscope is released (iPad 2, etc). Here's sample code using the Apple documented property for checking for gyroscope availability:
CMMotionManager *motionManager = [[[CMMotionManager alloc] init] autorelease];
if (motionManager.gyroAvailable)
{
motionManager.deviceMotionUpdateInterval = 1.0/60.0;
[motionManager startDeviceMotionUpdates];
}
See the documentation for more info.
I believe the answers from #Saurabh and #Andrew Theis are only partially correct.
This is a more complete solution:
- (BOOL) isGyroscopeAvailable
{
// If the iOS Deployment Target is greater than 4.0, then you
// can access the gyroAvailable property of CMMotionManager
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
BOOL gyroAvailable = motionManager.gyroAvailable;
[motionManager release];
return gyroAvailable;
// Otherwise, if you are supporting iOS versions < 4.0, you must check the
// the device's iOS version number before accessing gyroAvailable
#else
// Gyro wasn't available on any devices with iOS < 4.0
if ( SYSTEM_VERSION_LESS_THAN(#"4.0") )
return NO;
else
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
BOOL gyroAvailable = motionManager.gyroAvailable;
[motionManager release];
return gyroAvailable;
}
#endif
}
Where the SYSTEM_VERSION_LESS_THAN() is defined in this StackOverflow answer.
Related
I'm trying to implement deep linking in my iOS app (which I 'made' in Cocos Creator), and I want to implement this functionality
func application(_ application: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:] ) -> Bool {
// Determine who sent the URL.
let sendingAppID = options[.sourceApplication]
print("source application = \(sendingAppID ?? "Unknown")")
// Process the URL.
guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
let albumPath = components.path,
let params = components.queryItems else {
print("Invalid URL or album path missing")
return false
}
if let photoIndex = params.first(where: { $0.name == "index" })?.value {
print("albumPath = \(albumPath)")
print("photoIndex = \(photoIndex)")
return true
} else {
print("Photo index missing")
return false
}
}
... which is Swift code (?) and from here
https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app
in my AppController.mm
/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import "AppController.h"
#import "cocos2d.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "SDKWrapper.h"
#import "platform/ios/CCEAGLView-ios.h"
using namespace cocos2d;
#implementation AppController
Application* app = nullptr;
#synthesize window;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[SDKWrapper getInstance] application:application didFinishLaunchingWithOptions:launchOptions];
// Add the view controller's view to the window and display.
float scale = [[UIScreen mainScreen] scale];
CGRect bounds = [[UIScreen mainScreen] bounds];
window = [[UIWindow alloc] initWithFrame: bounds];
// cocos2d application instance
app = new AppDelegate(bounds.size.width * scale, bounds.size.height * scale);
app->setMultitouch(true);
// Use RootViewController to manage CCEAGLView
_viewController = [[RootViewController alloc]init];
#ifdef NSFoundationVersionNumber_iOS_7_0
_viewController.automaticallyAdjustsScrollViewInsets = NO;
_viewController.extendedLayoutIncludesOpaqueBars = NO;
_viewController.edgesForExtendedLayout = UIRectEdgeAll;
#else
_viewController.wantsFullScreenLayout = YES;
#endif
// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// warning: addSubView doesn't work on iOS6
[window addSubview: _viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:_viewController];
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
//run the cocos2d-x game scene
app->start();
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
app->onPause();
[[SDKWrapper getInstance] applicationWillResignActive:application];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
app->onResume();
[[SDKWrapper getInstance] applicationDidBecomeActive:application];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
[[SDKWrapper getInstance] applicationDidEnterBackground:application];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
[[SDKWrapper getInstance] applicationWillEnterForeground:application];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[[SDKWrapper getInstance] applicationWillTerminate:application];
delete app;
app = nil;
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
#end
... which is an Objective-C file?
Any ideas on how to achieve that would be fantastic! Thank you!
If I understood you right, I believe your question is to convert the above Swift function into Objective C
You can give this a go and see if it helps:
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
id sendingAppID
= [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
if (sendingAppID) {
NSLog(#"source application = %#", sendingAppID);
}
NSURLComponents *components
= [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
NSString *albumPath = components.path;
NSArray *params = components.queryItems;
if (!components && !albumPath && !params) {
NSLog(#"Invalid URL or album path missing");
return NO;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat: #"name = index"];
NSArray *filteredArray = [params filteredArrayUsingPredicate: predicate];
if ([filteredArray firstObject]) {
NSURLQueryItem *queryItem = [filteredArray firstObject];
NSString *photoIndex = queryItem.value;
NSLog(#"albumPath = %#", albumPath);
NSLog(#"photoIndex = %#", photoIndex);
return YES;
}
NSLog(#"Photo index missing");
return NO;
}
The bit I am not too sure about is the predicate bit which is supposed to replace the filter in Swift.
Let me know if this worked or not.
Update based on Willeke's recommendation
As suggested by Willeke in the comments, using indexOfObjectPassingTest: is better than using the predicate.
I believe this is how you would update the code
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
id sendingAppID
= [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
if (sendingAppID) {
NSLog(#"source application = %#", sendingAppID);
}
NSURLComponents *components
= [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
NSString *albumPath = components.path;
NSArray *params = components.queryItems;
if (!components && !albumPath && !params) {
NSLog(#"Invalid URL or album path missing");
return NO;
}
NSUInteger photoIndex = [params indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSURLQueryItem *queryItem = (NSURLQueryItem*) obj;
return [queryItem.name isEqual: #"index"];
}];
if (photoIndex != NSNotFound) {
NSURLQueryItem *queryItem = [params objectAtIndex: photoIndex];
NSString *photoIndex = queryItem.value;
NSLog(#"albumPath = %#", albumPath);
NSLog(#"photoIndex = %#", photoIndex);
return YES;
}
NSLog(#"Photo index missing");
return NO;
}
i have a problem, i want add different import file for iPhone and iPad, but for iPad doesnt' work, this is how i do:
#if TARGET_OS_IPHONE
#import "MyView_iPhone.h"
#elif TARGET_OS_IPAD
#import "MyView_iPad.h"
#endif
when in the code then i write for example:
MyView_iPhone *iphone = [MyView_iPhone alloc] init];
works, but:
MyView_iPad *iphone = [MyView_iPad alloc] init];
doens't work, give me an error, because doens't see the MyView_iPad.h, how i can do?
this is the error:
Unknown receiver 'MyView_iPad'; did you mean 'MyView_iPhone'?
<TargetConditionals.h> does not actually define a TARGET_OS_IPAD. You can't know at compile time whether you're executing for iphone or ipad! That is something you should check at runtime, importing both views and doing something like:
UIView *iphone;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
iphone = [[MyView_iPad alloc] init];
}
else{
iphone = [[MyView_iPhone alloc] init];
}
I've been using the next line in my constants
to differentiate between devices and get back the number of the device.
What's the appropriate way to identify iPhone 5 and still keep it in a one line format?
#define iPhoneType [[UIScreen mainScreen] scale]==2 || [UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad ? #"4" : #"3"
Thanks
Edit: A lot of good answers but my goal is to keep it in a one line format for all devices.
Edit:
Based on the comments, this question needs some clarification. Here are the requirements:
A single-line macro that returns either #"3", #"4", or #"5" depending on the iOS device.
The 4" devices (currently iPhone 5 and 5th gen iPod touch) should return #"5".
All iPads and all remaining retina iPhones and iPod touches should return #"4".
All remaining non-retina iPhones and iPod touches should return #"3".
According to your question I'm assuming you want to identify the hardware device, not the iOS version.
/*
Erica Sadun, http://ericasadun.com
iPhone Developer's Cookbook, 6.x Edition
BSD License, Use at your own risk
*/
#include <sys/sysctl.h>
NSString* getSysInfoByName(char* typeSpecifier) {
size_t size;
sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
char *answer = malloc(size);
sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
free(answer);
return results;
}
NSString* platform() {
return getSysInfoByName("hw.machine");
}
Import those functions in the .pch, then you are free to call this one liner:
BOOL isIphone5 = [platform() hasPrefix:#"iPhone5"];
It works for any device. See UIDevice-Hardware.m for a list of the strings returned.
Assuming the updated requirements are correct, the following should work:
#define iPhoneType (fabs((double)[UIScreen mainScreen].bounds.size.height - (double)568) < DBL_EPSILON) ? #"5" : ([UIScreen mainScreen].scale==2 || UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? #"4" : #"3")
This will return #"5" for the 4" screened iPhones and iPod touches. This will return #"4" for all iPads and retina iPhones and iPod touches. And it will return #"3" for non-retina iPhones and iPod touches.
Define Following Constants in .pch file of your project
#define IS_IPHONE5 ([[UIScreen mainScreen] bounds].size.width >= 568 || [[UIScreen mainScreen] bounds].size.height >= 568)?YES:NO
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)?YES:NO
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)?YES:NO
#define DeviceType ((IS_IPAD)?#"IPAD":(IS_IPHONE5)?#"IPHONE 5":#"IPHONE")
Now Check device type
NSLog(#"%# %#",DeviceType,[DeviceType isEqualToString:#"IPAD"]?#"YES":#"NO");
Use following sequence to Identify Device Type
if(IS_IPAD)
NSLog(#"IPAD");
else if(IS_IPHONE5)
NSLog(#"IPHONE 5");
else
NSLog(#"IPHONE");
The best way to identify the different iOS devices programatically is their screen resolution. I done same in my application it is working great. Please refer my code.
- (NSString *) getDeviceScreenWidth
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screenBounds);
NSNumber* number = [NSNumber numberWithFloat:width];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
NSString* commaString = [numberFormatter stringForObjectValue:number];
NSString *screenWidth = [NSString stringWithFormat:#"%#",commaString];
NSLog(#"screen Width is: %#",screenWidth);
return screenWidth;
}
- (NSString *) getDeviceScreenHeight
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat height = CGRectGetHeight(screenBounds);
NSNumber* number = [NSNumber numberWithFloat:height];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
NSString* commaString = [numberFormatter stringForObjectValue:number];
NSString *screenHeight = [NSString stringWithFormat:#"%#",commaString];
NSLog(#"screen height is: %#",screenHeight);
return screenHeight;
}
As sample you may found this code in cocos2d framework:
-(NSInteger) runningDevice
{
NSInteger ret=-1;
#ifdef __CC_PLATFORM_IOS
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
ret = (CC_CONTENT_SCALE_FACTOR() == 2) ? kCCDeviceiPadRetinaDisplay : kCCDeviceiPad;
}
else if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
{
// From http://stackoverflow.com/a/12535566
BOOL isiPhone5 = CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 1136));
if( CC_CONTENT_SCALE_FACTOR() == 2 ) {
ret = isiPhone5 ? kCCDeviceiPhone5RetinaDisplay : kCCDeviceiPhoneRetinaDisplay;
} else
ret = isiPhone5 ? kCCDeviceiPhone5 : kCCDeviceiPhone;
}
#elif defined(__CC_PLATFORM_MAC)
// XXX: Add here support for Mac Retina Display
ret = kCCDeviceMac;
#endif // __CC_PLATFORM_MAC
return ret;
}
I hope this code helps change your macro.
I'm trying to make a simple app utilizing gyroscope, where a character moves according to the rotation of the iPad 1.
My code is not working, so I tested to see the values of raw,pitch,yaw,
and they actually stay as zero however I move the device.
I'm sure iPad 1 supports CMMotionManager, so I'm not sure what's causing it...
My code is as follows
- (id) init{
if((self=[super init])){
self.isTouchEnabled = YES;
winSize = [[CCDirector sharedDirector] winSize];
[self createRabbitSprite];
self.motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 1.0/60.0;
if(motionManager.isDeviceMotionAvailable){
[motionManager startDeviceMotionUpdates];
}
[self scheduleUpdate];
//[self registerWithTouchDispatcher];
}
return self;
}
-(void)update:(ccTime)delta{
CMDeviceMotion *currentDeviceMotion = motionManager.deviceMotion;
CMAttitude *currentAttitude = currentDeviceMotion.attitude;
if(referenceFrame){
[currentAttitude multiplyByInverseOfAttitude:referenceFrame];
}
float roll = currentAttitude.roll;
float pitch = currentAttitude.pitch;
float yaw = currentAttitude.yaw;
NSLog(#"%.2f and %.2f and %.2f",roll,pitch,yaw);
rabbit.rotation = CC_RADIANS_TO_DEGREES(yaw);
}
Please help me out..
and thanx in advance.
(edit)
Apparently, motionManager.isDeviceMotionAvailable is returning FALSE...
which must mean that iPad 1 doesn't support CoreMotion???
Could it be something with the setting?
The iPad First generation does support CMMotionManager (as it has an accelerometer), but won't return any gyroscopic data - it doesn't have a gyroscope! You'll need to check the gyroAvailable property of a CMMotionManager instance.
is there any way to check video camera capability available on iPhone?
Most of the camera related availability support is exposed through the UIImagePickerController. A bit tricker thing is detection of Video Camera. You can detect the presence of a video camera in a iOS device using the following method.
- (BOOL) isVideoCameraAvailable
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
NSArray *sourceTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
[picker release];
if (![sourceTypes containsObject:(NSString *)kUTTypeMovie ]){
return NO;
}
return YES;
}
Found this code (based on UIDevice) which helped me with this issue:
https://github.com/MugunthKumar/DeviceHelper