dimanche 28 juin 2015

Xcode "switch/case" statement - warning about break;

What constantly happens to me is this, when I'm using Xcode with Objective-C:

I'll be writing a switch/case statement. Typically, to make sure statements are separated, the programmer must make sure there are break;s between cases.

I often forget to put the break; statement in, so instead of the device executing only the the desired case, the device executes the case and then the case after it. This happens on both a physical device (iPhone 6) and on every simulated device on iOS Simulator.

Here's what the syntax of the failed statement looks like, with someInt being a number that is either 0 or 1:

switch (someInt)
{
    case 0:
    {
         // some statements to execute if "someInt" is 0
    }
    case 1:
    {
         // some statements to execute if "someInt" is 1
         break;
    }
}

Note how, in case 0:, there is no break; statement. This causes case 0: to execute and then case 1 to execute, instead of just case 0 to execute.

Is there a way I can put a flag in Xcode so it warns me if I forget a break; statement?

I know many programmers have probably been confused for days, weeks on end, because of this problem.

Call and use uitableview from uitableviewcell?

I have a UITableViewController with many UITableViewCell. Each Cell have a UISwitch Button.

Here is my UITableViewController Class:

@implementation DanhsachTableViewController{
    NSMutableArray *data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
}

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"dscell"];
        NSDictionary *dataCell =  data[indexPath.row];
        cell.service =  dataCell[@"service"];
        cell.package =  dataCell[@"package"];
        cell.loai_goi = dataCell[@"loai_goi"];

        return cell;
    }
-(void) changeCellState:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi{
    for (int i =0;i<data.count;i++){
        DichVu2TableViewCell *cellLocal = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
            [cellLocal.sudung setOn:NO animated:YES];
        }
     }
}

"Data" array was loaded in method loadData (not important here so I don't include it).

In UITableViewCell (class name: DichVu2TableViewCell), I set event Value Change of Switch so that each time a Switch change value (ON for example), all other cell's switch which have the same value "service" and "loai_goi" will be set OFF.

DanhsachTableViewController *tableview = [[DanhsachTableViewController alloc] init];
    tableview.tableView.delegate = (DanhsachTableViewController *)self.superview.superview;
[tableview changeCellState:_service package:_package loaigoi:_loai_goi];

But when I call, the array "data" of above tableview have 0 object so nothing happened.

Is there any way to do that?

Hi Oyeoj, Thanks for your help.

I have a little problem when followed your guide. There are some error in xcode when I use extract your code so I have to customize. But the program still has error when running. Would you please help me review my code. Thanks in advance.

DichVu2TableViewCell.h

@class DichVu2TableViewCell;
//Change : NSObject to <NSObject> because XCode 6.3 has error.
@protocol DichVu2TableViewCellDelegate <NSObject>

-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi;

@end

@interface DichVu2TableViewCell : UITableViewCell

@property (weak) id <DichVu2TableViewCellDelegate> delegate;

@end

DichVu2TableViewCell.m

@implementation DichVu2TableViewCell
….
- (void)someSwitchingEvent
{
    [self.delegate changeCell:self state:_service package:_package loaigoi:_loai_goi];
}
@end

DanhsachTableViewController.h

@interface DanhsachTableViewController : UITableViewController

@property (strong,nonatomic) NSString *loaitb;
@property (strong,nonatomic) NSString *type;
@property (strong,nonatomic) NSString *name;
@property NSMutableArray *pre_inuse_;
@property NSMutableArray *data_inuse_;
@property NSMutableArray *vas_inuse_;
@end

DanhsachTableViewController.m

#import "DichVu2TableViewCell.h"
//Change <DichVu2TableViewCellDelegate> to (DichVu2TableViewCellDelegate) because XCode 6.3 has error.
@interface DanhsachTableViewController (DichVu2TableViewCellDelegate)
@property (nonatomic) NSIndexPath *forUpdateIndexPath;
@end

@implementation DanhsachTableViewController{
    NSMutableArray *data;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DichVu2TableViewCell *cell = (DichVu2TableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"dscell"];
    NSDictionary *dataCell =  data[indexPath.row];
    cell.service =  dataCell[@"service"];
    cell.package =  dataCell[@"package"];
    cell.loai_goi = dataCell[@"loai_goi"];
    cell.kieu_goi = dataCell[@"kieu_goi"];

    [cell.sudung setOn:NO animated:YES];
    cell.delegate = self;
//Change cellLocal —> cell because there are no cellLocal avaiable. And Program error when run to this row.
    [cell.sudung setOn:(self.forUpdateIndexPath == indexPath) animated:YES];

    return cell;
}

-(void)changeCell:(DichVu2TableViewCell *)sender state:(NSString *)service package:(NSString *)package loaigoi:(NSString *)loai_goi
{
//Add cellLocal —> cell because there are no cellLocal avaiable
    DichVu2TableViewCell *cellLocal = (DichVu2TableViewCell *)[self.tableView cellForRowAtIndexPath:self.forUpdateIndexPath];
    if ([service isEqualToString:cellLocal.service] && ![package isEqualToString:cellLocal.package] && [loai_goi isEqualToString:cellLocal.loai_goi]){
        // get the indexPath of the cell
        self.forUpdateIndexPath =  [self.tableView indexPathForCell:sender];
        // update the date source
        NSMutableDictionary *dataCell =  [data[self.forUpdateIndexPath.row] mutableCopy];
        [dataCell setObject:service forKey:@"service"];
        [dataCell setObject:package forKey:@"package"];
        [dataCell setObject:loai_goi forKey:@"loai_goi"];
        // you dont need the for-statement just reload the table
        [self.tableView reloadData];
        // then update the switch inside `- cellForRowAtIndexPath`
    }

}

iOS touch(es) blocking issue

I am encoutering a strange issue with an iOS application that I'm currently working on, issue related to touches.

For exemplification, the layout of the app looks something like this (its quite basic, nothing fancy, just some buttons and a touch area):

Application layout

A is the touch area (its a CONTAINER which has a View inside, view that displays an image , image that is affected by the way im touching the area).

B is a simple iOS button (the one you create by default with XCODE , with just a changed background color and size (width/height).

Now , the issue: it only happens some times, I could not yet figure out why and when, but I can reproduce it sometimes. Basically, when clicking B , touches on A (with a finger from the left hand) behave strange: i am receiving the touchesMoved event, but the touch position is the position of the touch on B, hence the movement of the image in A does not happen, and when it happens (after removing the right hand finger from B), the movement behaves as if the touch was at the B position.

Here is part of the code , the part that handles touches, in the ViewController attached to the A view. I have removed some of the code that I dont think its related to my issue, to keep things cleaner.

-(void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{

    NSLog(@"A View touched : %d", [touches count]);
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView: _theAView];
    NSLog(@"Touch at %f %f", touchLocation.x, touchLocation.y);
    initialTouchX = touchLocation.x;
    initialTouchY = touchLocation.y;    


}

-(void)touchesMoved:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{

    /*
    some code was here handling time, to only handle moving every X milliseconds
    */
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:theAView];


    /*
    code handling the display of the image , removed
    */
    initialTouchX = touchLocation.x;
    initialTouchY = touchLocation.y;

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {

}

As for the code of the B button, its just a basic IBAction, which calls a function with a parameter:

- (IBAction)btnDown:(id)sender {
    //call some function here 
}

Two things to note:

1) in the code above, "theAView" reffers to the view in the A area. 2) the 1st part of code (the one with the touches) resides in a different ViewController; the 2nd part of the code, for the button, resides in the default ViewController file that XCODE creates when creating a project.

I also tried enabling multitouch on both the A view and the B button, but the problem is still there.

Any help is appreciated.

Thanks in advance.

Gamecenter new match creation with specific opponent

I'm creating a turn-based game using gamecenter. It is a one to one game so every game has two participants.

When a game is finished, a gameover screen appears and either of the participants can press "rematch" to start a new game with the same opponent.

The code I use when the button is pressed is (simplified) this:

let request = GKMatchRequest()
        request.maxPlayers = 2
        request.minPlayers = 2
        request.recipients = [opponent]

GKTurnBasedMatch.findMatchForRequest(request, withCompletionHandler: {
            match, error in
            if error != nil {
                println("FIND MATCH REQUEST ERROR:\(error.localizedDescription)")
            } else {
                println("Match Found")}})

Now, my question is this. When I rematch a game where the opponent is a friend of mine in gamecenter everything seems to work fine. However, if I rematch a game where the opponent is not a friend of mine in gamecenter I get the following error:

The requested operation could not be completed because the player is invalid.

However, when I print the opponent player (GKPlayer) I get the following (which seems to be fine and not invalid as the error suggests):

(playerID:g:58D9E388A2CD0DEFC795DC9035E7D22A alias:TestBoomar_1 name:‎“‪TestBoomar_1‬” status:(null))

So, my question is this: Do GKMatchRequest recipients have to be the players friends in order for those recipients to be valid? Shouldn't recipients be able to be any players in Gamecenter, not dependent on whether they are friends of the game creator?

Any input is appreciated, Thanks!

How to recognise a song by listening using Echonest for iOS?

I want to implement a functionality similar to the one integrated in Shazam app. I want my app by pressing to a button to "listen" for a song and after some time to "guess" the song or give some predictions using Echonest api for iOS. I was searching the web and so far I've learned the I need to send the fingerprint to the Echonest server and give me response with the song info. But somewhere I've read that that functionality will be no more available. Also tried to upload the whole mp3 file to their server and the response is always an empty one. Does anyone has experience with this issue and tell me where I'm wrong? I've used echoprint but no success.

MySQL server and iOS app

I am running a site right now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Fix Fatal iOS crash

I am AdHoc testing an iOS app on iPad mini and iPhone 4. The app worked fine 48 hours ago on both platforms but is now fatally crashing/freezing when I test on iPhone 4. The app lets you login to an apache server using php/json, take pics using the iOS camera, then upload the pics to a vertical UIScrollView where the pics are viewed as jpeg thumbs. From there you can tap a thumb and view it full screen.The app works perfectly on iPad but not on iPhone 4. The app crashes (either freezes or goes back to the home screen) when I tap a photo jpeg thumb in the UIScrollView to view it full screen. (this works fine on iPad testing).

All i want to do right now is view a photo fullscreen on iPhone 4 but the app keeps fatally freezing. The second I tap a photo on iPhone, the app freezes and the compiler highlights the following line of code in the application.

[api commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"stream", @"command", IdPhoto,@"IdPhoto", nil] onCompletion:^(NSDictionary *json) { 

//after this line of code is a 
Thread 1. EXC_BAD_ACCESS(code=1,address=ox28)

This is also a line of code the compiler points to after the freeze/crash. (It high lights the above live half the time and this line other times with the same 'Thread 1' alert.

if([value isKindOfClass:[NSDictionary class]]) {