iOS 5 conversion UIAccelerometer - ios5

I'm using xcode 4.2 (and going to be upgrading soon) and these lines of code
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / kAccelerometerFrequency)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
the code works but I have a yellow warning saying that the code is deprecated and I looked at the new references and CoreMotion now does the Accelerometer. I was wondering what is the new way to write something like the above..?

Start accelerometer.
- (void)startAccelerometerData {
motionManager = [[CMMotionManager alloc] init];
motionManager.accelerometerUpdateInterval = 1/60.0;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
NSLog(#"x:= %f y:= %f z:= %f", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
} ];
}
stop accelerometer
- (void)viewDidUnload {
[motionManager stopAccelerometerUpdates];
motionManager = nil;
[super viewDidUnload];
}

Related

Failing to authenticate local player iOS6

I'm building a Game Center game in iOS6 and am continuously running into problems with it. The current one has me stumped - Every single time my game tries to authenticate the local player it fails. Every time it is triggering my "disable game center" function and it's driving me crazy.
- (void) disableGameCenter
{
// Write something to disable gamecenter.
// gameCenterAvailable = FALSE;
}
-(void)showAuthenticationDialogWhenReasonable:(UIViewController *)viewController
{
// Pause Tasks Here
// [[[(AppDelegate *)[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:viewController animated:YES completion:nil];
}
- (void) authenticateLocalPlayer
{
localPlayer = [GKLocalPlayer localPlayer];
__weak GKLocalPlayer* weakLocalPlayer = localPlayer;
weakLocalPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error)
{
if (viewController != nil)
{
[self showAuthenticationDialogWhenReasonable: viewController];
}
else if (weakLocalPlayer.isAuthenticated)
{
self.localPlayer = weakLocalPlayer;
}
else
{
[self disableGameCenter];
}
};
}
Forgive me if I'm wrong, but I don't think you are running the authenticate method.
Try this method instead:
- (void) authenticateLocalPlayer
{
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
[localPlayer authenticateWithCompletionHandler:^(NSError *error) {
if (localPlayer.isAuthenticated)
{
NSLog(#"Authenticated");
}
else
{
NSLog(#"Not Authenticated");
}
}];
}

Not getting the correct accelerometer data in background using core motion

I am implementing accelerometer data in background using coremotion. I am getting the data in the background but value of x,y,z coordinates are not correct.
Here is my code.
- (void)applicationWillResignActive:(UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
if (isInBackground)
{
[self sendBackgroundLocationToServer:newLocation];
}
}
-(void) sendBackgroundLocationToServer:(CLLocation *)location
{
UIApplication *application = [UIApplication sharedApplication];//Get the shared application instance
__block UIBackgroundTaskIdentifier background_task; //Create a task object
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
NSAssert(background_task == UIBackgroundTaskInvalid, nil);
[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
}];
NSOperationQueue *theQueue = [[NSOperationQueue alloc] init];
CMAccelerometerData *_returnedData = [[CMAccelerometerData alloc] init];
CMMotionManager *_motionManager = [[CMMotionManager alloc] init];
[_motionManager startAccelerometerUpdatesToQueue:theQueue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
int x = _motionManager.accelerometerData.acceleration.x;
int y = _motionManager.accelerometerData.acceleration.y;
int z = _motionManager.accelerometerData.acceleration.z;
NSLog(#"X: %i, Y: %i, z: %i", x, y,z);
//[self changeFilter:[HighpassFilter class]];
//[filter addAcceleration:acceleration];
const float violence = 1.20;
float magnitudeOfAcceleration = sqrt (x*x + y*y + z*z);
//float magnitudeOfAcceleration = sqrt (filter.x*filter.x + filter.y * filter.y + filter.z * filter.z);
BOOL shake = magnitudeOfAcceleration > violence;
if (shake)
{
step++;
NSLog(#"---------------");
}
NSUserDefaults *defalut = [NSUserDefaults standardUserDefaults];
NSLog(#"steps in background: %i",step );
if([defalut objectForKey:#"Stepscounting"]){
int f = [[defalut objectForKey:#"Stepscounting"] intValue];
step+=f;
}
[defalut setObject:[NSString stringWithFormat:#"%i",step] forKey:#"Stepscounting"];
}];
// AFTER ALL THE UPDATES, close the task
if (background_task != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:background_task];
background_task = UIBackgroundTaskInvalid;
}
}
Using this i am getting the co-ordinates but values are not correct. Can any one tell me what is the reason behind this. I am not able to understand why is this happing.
Thanks in advance.
perhaps you should use float instead of int for your x,y,z.

Issues regarding gamecenter+ios

I am not knowing anything about gamecentre.I am working on the COCO application
I had gone through gamecenter guide and get able to integrate the game center in my application.
1)
Now the i am able enter the score in the gamecentre through my application.
By doing this:-
- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category] autorelease];
scoreReporter.value = score;
[scoreReporter reportScoreWithCompletionHandler: ^(NSError *error)
{
[self callDelegateOnMainThread: #selector(scoreReported:) withArg: NULL error: error];
}];
}
I is working properly uptil yesterday.But now if i tried to update the score it is not updating.Please any one know the reason y the score is not updating in the game center
I had tried to search out but not get anything.
2)I want to send the current latitude & longitude of one player to another.
I came to know that it is possible by GKMATCH
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 1;
request.maxPlayers = 1;
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request
withCompletionHandler:^(GKMatch *match, NSError *error) {
if (error || !match) {
// handle the error
}
else if (match != nil){
// match found
}}];
/*GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 1;
request.maxPlayers = 1;
GKMatchmakerViewController *mmvc = [[GKMatchmakerViewController alloc] initWithMatchRequest:request];
mmvc.matchmakerDelegate = self;
currentMatch.delegate=self;
[self presentModalViewController:mmvc animated:YES];*/
//[mmvc release];
}
- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
switch (state){
case GKPlayerStateConnected:
if (match.expectedPlayerCount == 0) {
// start the match
}
break;
case GKPlayerStateDisconnected:
// remove the player from the match, notify other players, etc
break;
}
}
- (void)matchmakerViewControllerWasCancelled:(GKMatchmakerViewController *)viewController{}
// Matchmaking has failed with an error
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFailWithError:(NSError *)error{
}
// A peer-to-peer match has been found, the game should start
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match{
}
// Players have been found for a server-hosted game, the game should start
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindPlayers:(NSArray *)playerIDs{
}
// An invited player has accepted a hosted invite. Apps should connect through the hosting server and then update the player's connected state (using setConnected:forHostedPlayer:)
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didReceiveAcceptFromHostedPlayer:(NSString *)playerID {
}
- (void) sendPosition
{
NSError *error;
NSString* str = #"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
// NSData *packet = [NSData dataWithBytes:&msg length:sizeof(PositionPacket)];
[currentMatch sendDataToAllPlayers: data withDataMode: GKMatchSendDataUnreliable error:&error];
if (error != nil)
{
// Handle the erro.r
}
}
But i dont know why but delegate method of GKMatchmakerViewController is not called i had set the delegate but still and even i ama not able to get GKMATCH (here currentMatch).
So due to this
[currentMatch sendDataToAllPlayers: data withDataMode: GKMatchSendDataUnreliable error:&error];
this method is not working.
as CurrentMatch refrence is 0X0.
Please help me out.How do i send and recive data.
M i doing anything wrong?OR is there any thing else to be done.
Please help me.
Thanks

UIApplicationDelegate methods not being called

I am trying to create a plugin for region monitoring. Region Monitoring is starting fine but the function didfinishlaunching and didrecievelocalnotification are not being evoked. I am not sure why this is happening.
regionMonitoring.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface RegionMonitoringPlugin : NSObject <UIApplicationDelegate,CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
-(void)enterRegionNotify;
-(void)leaveRegionNotify;
-(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)raduis;
#end
regionMonitoring.mm
#import "RegionMonitoringPlugin.h"
#implementation RegionMonitoringPlugin
- (id) init
{
//if ( init == [super init]){
if (locationManager==nil){
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
return self;
}
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
[self enterRegionNotify];
}
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
[self leaveRegionNotify];
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)regionwithError:(NSError *)error
{
NSLog(#"Location error %#, %#", error, #"Fill in the reason here");
}
-(void)leaveRegionNotify
{
NSLog(#"Starting region monitoring - check point 3");
UILocalNotification *note = [[UILocalNotification alloc] init];
note.alertBody= #"Region Left"; // ToAsk: What should be displayed
note.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:note];
[note release];
}
-(void)enterRegionNotify
{
UILocalNotification *note = [[UILocalNotification alloc] init];
note.alertBody= #"Region Left"; //ToAsk: what should be displayed ?
note.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] presentLocalNotificationNow:note];
[note release];
}
-(void)startMonitor:(float)latitude longitude:(float)longitude radius:(float)radius
{
NSLog(#"Starting region monitoring - check point 2");
[self leaveRegionNotify];
CLLocationCoordinate2D home;
home.latitude = latitude;
home.longitude = longitude;
CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:home radius:radius identifier:#"region"];
[locationManager startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest];
[region release];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSLog(#"Starting region monitoring - checkpoint 4");
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Region Monitor Notification" message:notification.alertBody delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
- (BOOL)application:(UIApplication *) application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(#"Test");
return TRUE;
}
#end
extern "C" {
static RegionMonitoringPlugin *regionMonitor;
// Unity callable function to start region monitoring
BOOL _startRegionMonitoring(float m_latitude,float m_longitude, float m_radius)
{
NSLog(#"Starting region monitoring");
if (![CLLocationManager regionMonitoringAvailable] || ![CLLocationManager regionMonitoringEnabled] )
return NO;
if (regionMonitor == nil){
regionMonitor = [[RegionMonitoringPlugin alloc] init] ;
}
[regionMonitor startMonitor:m_latitude longitude:m_longitude radius:m_radius];
return YES;
}
}
Unity Code for plugin : RegionMonitorMediater.h
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class RegionMonitoringMediator {
/*Interface to native implementation */
[DllImport ("__Internal")]
private static extern bool _startRegionMonitoring (float m_latitude,float m_longitude, float m_radius);
public static bool startRegionMonitoring (float latitude,float longitude, float radius)
{
/*Call plugin only when running on real device*/
if (Application.platform != RuntimePlatform.OSXEditor)
return _startRegionMonitoring ( latitude , longitude , radius);
else return false;
}
}
Calling region monitor
OnPress event I do
bool startedRM = RegionMonitoringMediator.startRegionMonitoring(77.0f,28.0f,10.0f);
There is only one UIApplicationDelegate allowed per app. When Unity3D builds your application for iPhone player a class AppController is generated which acts as interface.
This class is the place for inserting your code to call RegionMonitoringPlugin.
init should include a call to super at its start:
- (id) init
{
if (self = [super init])
{
// initialize everything else
}
return self;
}
note that we used assignment (=) operator, and not comparison (==) operator.

Why can't my devices find each other using this Game Kit connection code?

I'm trying to connect two devices over Bluetooth using Game Kit. The first device is running an application with the following code inside it:
-(void)connect
{
GKPeerPickerController* picker;
picker = [[GKPeerPickerController alloc] init];
picker.delegate = self;
//picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
[picker show];
}
- (void)viewDidLoad {
[super viewDidLoad];
peerStatus = kServer;
gamePacketNumber = 0;
currentSession = nil;
gamePeerId = nil;
NSString *uid = [[UIDevice currentDevice] uniqueIdentifier];
gameUniqueID = [uid hash];
[self connect];
}
- (void)peerPickerController:(GKPeerPickerController *)picker didSelectConnectionType:(GKPeerPickerConnectionType)type {
// GKSessionModeClient
// GKSessionModeServer
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
currentSession.available = YES;
currentSession.delegate = self;
}
- (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
{
self.gamePeerId= peerID;
//self.currentSession = session;
self.currentSession.delegate = self;
[self.currentSession setDataReceiveHandler: self withContext:nil];
// Remove the picker.
picker.delegate = nil;
[picker dismiss];
[picker autorelease];
// Start your game
}
- (void)peerPickerControllerDidCancel: (GKPeerPickerController *)picker
{
NSLog(#"peerPickerControllerDidCancel");
picker.delegate = nil;
[picker autorelease];
}
- (void)session: (GKSession*)session peer:(NSString*)peerID didChangeState:(GKPeerConnectionState)state
{
NSLog(#"finding and connecting to others sessions");
if(state == GKPeerStateAvailable){
NSLog(#"aviable and ready to conect");
[session connectToPeer:peerID withTimeout:60];
session.available =NO; //put YES si volem multiconexions sino es tancarĂ  la sesio en conectarse 2
}
}
- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID{
NSLog(#"lisetn for others sessions");
NSError *error=nil;
if(amAcceptingConnetions){
if(![session acceptConnectionFromPeer:peerID error:&error]){
//Handler error
}
}else{
[session denyConnectionFromPeer:peerID];
}
}
The second device is running another application that uses the same code as above, only with the following piece changed:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeServer];
The normal window appears on both to indicate that they are searching for other devices, but the two devices don't recognize each other. What could be wrong here?
You need to allocate currentSession if it's not already being allocated. Perhaps try changing:
[self.currentSession initWithSessionID:kTankSessionID displayName:nil sessionMode:GKSessionModeClient];
To this:
self.currentSession = [[GKSession alloc] initWithSessionID:kTankSessionID displayName:nil sesssionMode:GKSessionModeClient];
You may want to also add a check to see if the session is already allocated, and release it if it is before you create a new one. I noticed some improvements in performance and reliability if you reset the session every time your devices try to connect, instead of reusing the same session.
You have to import PeerPickerController along with GameKit/Gamekit.h also. If you want to know more,Please refer this link.
or
http://www.devx.com/wireless/Article/43502/0/page/1