iTunes isRunning with NSTask - boolean

So I am trying to make an if based on if iTunes is running or not. I need this because my application gets the track name. This track name has already been accomplished and works but I do not want iTunes always running...
So I decided to try a NSTask with setLaunchPath instance to check if iTunes.app isRunning. The code below is self explanatory but for some reason it keeps hitting my else if when iTunes is open. I call this method in my awakeFromnib by an nstimer every 5 seconds.
-(IBAction)ifRunning:(id)pID; {
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/Applications/iTunes.app/Contents/MacOS/iTunes"];
if ([task isRunning]==TRUE) {
NSLog(#"iTunes is Running, hit if");
NSString *track = ([self getCurrentTrack]);
//getCurrentTrack another one of my methods
}
else if ([task isRunning] == FALSE) {
NSLog(#"iTunes is not running, hit else if");\
[trackName setTitle:(#"iTunes is Not Playing")];
}
else {
NSLog(#"Hit else");
}
}

I figured it out using the code below. Hope this post is useful!
-(IBAction)ifRunning:(id)pID; {
NSLog(#"Process check ");
NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSArray *runningAppDictionaries = [ws launchedApplications];
NSDictionary *aDictionary;
for (aDictionary in runningAppDictionaries)
{
// NSLog(#"Open App: %#", [aDictionary valueForKey:#"NSApplicationName"]);
if ([[aDictionary valueForKey:#"NSApplicationName"] isEqualToString:#"iTunes"])
{
NSLog(#"iTunes is Is Running");
[self getCurrentTrack:nil];
break;
}
else {
NSLog(#"iTunes is not running.");
}
}
}

Related

Facebook Dialog showing only in Portrait mode

I have a issue with the Login and sharing dialogs on my app. About a week ago they started appearing only on Portrait mode (either normal or upside down), but the landscape modes does not work.
NSArray *permissions = #[#"user_photos",
#"user_likes",
#"user_friends",
#"email"];
_loginManager = [[FBSDKLoginManager alloc] init];
_loginManager.loginBehavior = FBSDKLoginBehaviorWeb;
[_loginManager logInWithReadPermissions:permissions fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if(result.isCancelled || error)
{
[self pressedCancel];
return;
}
NSSet* declinedPermissions = result.declinedPermissions;
for (NSString *declinedPermission in declinedPermissions) {
if(!nullOrEmpty(declinedPermission))
{
[self pressedCancel];
return;
}
}
if ([FBSDKAccessToken currentAccessToken]) {
// self.settings.facebookToken = [FBSDKAccessToken currentAccessToken].tokenString;
// Send data capture
if([EventData sharedInstance].dataCaptureSettings.enabled)
{
[FacebookHelper getUserInfoWithCompletion:
^(NSDictionary* userInfo, NSError* error)
{
if(!nullOrEmpty(userInfo))
{
[self captureData:userInfo];
} else {
[self captureData:nil];
}
[self didSignIn];
}];
return;
} else {
[self captureData:nil];
[self didSignIn];
}
}
}];
Here's a MPOC to replicate the issue:
https://www.dropbox.com/s/p62vajqfk916bz1/FBTest.zip?dl=0
Any ideas what may be causing this? Or how could I make it work on Landscape mode as well?
Thanks!
just in case anyone else has this issue, it was fixed on the newest Facebook SDK for iOS (4.38.1)

iOS GameCenter Matchmaker not working

I’m trying to make a custom matchmakingview using a matchmaker. The code below is used to find a match.
When i run this on two different devices with different Game Center accounts, both will get a match but none will connect to the match. They will just get stuck in the while loop in infinity and never get out. Have i missed something, do you need to call something to actually connect to the match?
- (void) findMatch{
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = 2;
request.maxPlayers = 2;
request.playersToInvite = nil;
NSLog(#"Start searching!");
[matchmaker findMatchForRequest:request
withCompletionHandler:^(GKMatch *match, NSError *error)
{
if (error) {
// Print the error
NSLog(#"%#", error.localizedDescription);
}
else if (match != nil)
{
curMatch = match;
curMatch.delegate = self;
NSLog(#"Expected: %i", match.expectedPlayerCount);
while (match.expectedPlayerCount != 0){
NSLog(#"PLayers: %i", curMatch.playerIDs.count);
}
NSLog(#"Start match!");
}
}];
You should not be using a while loop to wait for expectedPlayerCount to reach 0, instead implement the GKMatchDelegate method:
- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
if (!self.matchStarted && match.expectedPlayerCount == 0) {
self.matchStarted = YES;
//Now you should start your match.
}
}

iOS Gamecenter Programmatic Matchmaking

I'm trying to implement a real-time multiplayer game with a custom UI (no GKMatchMakerViewController). I'm using startBrowsingForNearbyPlayersWithReachableHandler:
^(NSString *playerID, BOOL reachable) to find a local player, and then initiating a match request with the GKMatchmaker singleton (which I have already initiated).
Here's where I'm having trouble. When I send a request, the completion handler fires almost immediately, without an error, and the match it returns has an expected player count of zero. Meanwhile, the other player definitely has not responded to the request.
Relevant code:
- (void) findMatch
{
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = NUM_PLAYERS_PER_MATCH; //2
request.maxPlayers = NUM_PLAYERS_PER_MATCH; //2
if (nil != self.playersToInvite)
{
// we always successfully get in this if-statement
request.playersToInvite = self.playersToInvite;
request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse
response)
{
[self.delegate updateUIForPlayer: playerID accepted: (response ==
GKInviteeResponseAccepted)];
};
}
request.inviteMessage = #"Let's Play!";
[self.matchmaker findMatchForRequest:request
withCompletionHandler:^(GKMatch *match, NSError *error) {
if (error) {
// Print the error
NSLog(#"%#", error.localizedDescription);
}
else if (match != nil)
{
self.currentMatch = match;
self.currentMatch.delegate = self;
// All players are connected
if (match.expectedPlayerCount == 0)
{
// start match
[self startMatch];
}
[self stopLookingForPlayers];
}
}];
}
Figured it out! I needed to call - (void)matchForInvite:(GKInvite *)invite completionHandler:(void (^)(GKMatch *match, NSError *error))completionHandler in my invitation handler so that both players have the same match data.

A memory leak happen when doing ftp request in the background thread

I am developing an app which can download image from the server through ftp request and then display them. The ftp request is running in the background. When the download finished, a update message will be sent to the view.
I encountered a memory leak when doing the ftp request which has the following features:
1. The memory leak do not happen every time. May be 1 / 7.
2. If I do the ftp request on the main thread, everything is OK.
3. If I do the ftp request on simulator, everything is OK.
I used SIMPLEFTP to do the ftp job and I have done some modification to fix my request.
In the FtpListService.m, This file is used to request a document list information (name, size, modification date). Memory leak is happened here (I highlight the line with "####").
//This is the method to start a ftp request
- (void)_startReceive
// Starts a connection to download the current URL.
{
BOOL success;
NSURL * url;
CFReadStreamRef ftpStream;
//don't tap receive twice in a row!
assert(self.networkStream == nil);
// First get and check the URL.
self.InputUrl = [self.InputUrl stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
url = [FtpUtil smartURLForString:self.InputUrl];
success = (url != nil);
// If the URL is bogus, let the user know. Otherwise kick off the connection.
if (!success) {
DLog(#"Bad ftp url.");
} else {
// Create the mutable data into which we will receive the listing.
assert(self.listData != nil);
// Open a CFFTPStream for the URL.
ftpStream = CFReadStreamCreateWithFTPURL(NULL, (CFURLRef) url);
assert(ftpStream != NULL);
self.networkStream = (NSInputStream *) ftpStream;
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:RUNLOOPMODEL];
//This timer will be called to terminate the request which is blocked for a customed time.
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUTFTPLIST target:self
selector:#selector(listdealTimeOut:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:RUNLOOPMODEL];
[self.networkStream open];
CFRelease(ftpStream);
}
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
connected = #"connected";
switch (eventCode) { //####################### EXC_BAD_ACCESS
case NSStreamEventOpenCompleted: {
//NSLog(#"NSStreamEventOpenCompleted");
} break;
case NSStreamEventHasBytesAvailable: {
NSInteger bytesRead;
uint8_t buffer[LISTDOCBUFFER];
// Pull some data off the network.
bytesRead = [self.networkStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == -1) {
[self _stopReceiveWithStatus:#"Network read error"];
} else if (bytesRead == 0) {
[self _stopReceiveWithStatus:#"no more data"];
} else {
assert(self.listData != nil);
// Append the data to our listing buffer.
[self.listData appendBytes:buffer length:bytesRead];
[self _parseListData];
}
} break;
case NSStreamEventHasSpaceAvailable: {
//NSLog(#"NSStreamEventHasSpaceAvailable");
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventErrorOccurred: {
DLog(#"NSStreamEventErrorOccurred");
[self _stopReceiveWithStatus:#"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
DLog(#"NSStreamEventEndEncountered");
// ignore
} break;
default: {
DLog(#"default");
assert(NO);
} break;
}
}
In the FtpService.m. Here I counld specify the address and trytime to do ftp request:
- (NSArray *)requstServerListInfo:(NSString *)filename tryTime:(int)tryTime
{
NSArray *result = nil;
//Create the request ftp path
NSString* tm = [NSString stringWithFormat:FTPURL];
if(filename != nil)
tm = [NSString stringWithFormat:#"%#%#/",FTPURL,filename];
while (tryTime-- > 0) {
FtpListService *listService = [[FtpListService alloc] initWithUrl:tm];
[listService _startReceive];
//isReceiving will be NO only when : connect error, time out, correctly done job
//I do not really understand the loop, I just know this will cause the request job to begin
while (listService.isReceiving) {
[[NSRunLoop currentRunLoop] runMode:RUNLOOPMODEL beforeDate:[NSDate distantFuture]];
}
//if correctly request, dirArray != nil
if(listService.dirArray == nil) {
[listService release];
continue;
} else {
result = listService.dirArray;
[listService release];
break;
}
}
return result;
}
The ftp job start from PGNetConductor.m which is a singleton:
pm = [[PGDataManagement alloc] init];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
result = [pm startNetWork];
}
PGDataManagement is owned by PGNetConductor : #property (nonatomic, unsafe_unretained) PGDataManagement *pm;
I try a lot but failed to solve the problem. Hope someone could give me some advice. If you need the code or more infomation , tell me. Thanks!

High Score submission to Game Center not working

I'm doing an ios app based on maths..
I've done the code for uploading the high score to the Game Center..
but this doesn't work..
it's always showing 0 as the high score..
This is my code...
[[GKLocalPlayer localPlayer]authenticateWithCompletionHandler:^(NSError *error)
{
if (error ==nil)
{
CCLOG(#"Success");
} else
{
CCLOG(#"Fail");
}
}];
.
.
.
.
.
-(void)showLeaderboard
{
if( ! gameCenterViewController_ )
gameCenterViewController_ = [[GameCenterViewController alloc] init];
[gameCenterViewController_ showLeaderboard];
}
-(void)submitMyScore1:(int)score1
{
CCLOG(#"submitMyScore1--%d",score1);
//This is the same category id you set in your itunes connect GameCenter LeaderBoard
GKScore *myScoreValue = [[[GKScore alloc] initWithCategory:#"bigwizlist"] autorelease];
myScoreValue.value = score1;
[myScoreValue reportScoreWithCompletionHandler:^(NSError *error){
if(error != nil)
{
CCLOG(#"Score Submission Failed");
} else
{
CCLOG(#"Score Submitted");
}
}];
}
I think you need to use an int64_t for your method! I use this method and it works perfectly fine :-)
-(void)submitScore:(int64_t)score category:(NSString*)category{
GKScore *gkScore = [[[GKScore alloc]initWithCategory:category]autorelease];
gkScore.value = score;
[gkScore reportScoreWithCompletionHandler:^(NSError* error)
{
[self setLastError:error];
bool sucess = (error == nil);
[delegate onScoresSubmitted:sucess];
}];
}
Greetings
Anselm