Saturday, August 23, 2014

[English] Useful Macros

1. [NSString stringWithFormat:]

#define STRFORMAT(f, ...) [NSString stringWithFormat:f, __VA_ARGS__]

NSString* message = [NSString stringWithFormat:@"HELLO %3.1d", 333.333];

-> NSString* message = STRFORMAT(@"HELLO %3.1d", 333.333);

2. NSLocalizedString

#define LSTR(s) NSLocalizedString((s), nil)

NSString* message = NSLocalizedString(@"KEY", nil);

-> NSString* message = LSTR(@"KEY");

3. Class Method

#define ME [self class]

[ExampleClass classMethod];

-> [ME classMethod];

4. Block's __weak self

#define PREPARE_SELF __weak typeof(self) SELF = self

__weak MyClass* SELF = self;
[self doSomethingWithBlock:^{
    [SELF showAlert];
}];

->
PREPARE_SELF;
[self doSomethingWithBlock:^{
    [SELF showAlert];
}];

5. Hex Color

#define HEXCOLOR(c) [UIColor colorWithRed:((c>>16)&0xFF)/255.0 green:((c>>8)&0xFF)/255.0 blue:(c&0xFF)/255.0 alpha:1.0]

HEXCOLOR(0x34ff78);

6. 4 inch Size Check


#define IS_IPHONE4INCH (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)

if (IS_IPHONE4INCH) {
.....
}

7. iOS Version Major

#define IOS_VERSION_MAJOR [[[[[UIDevice currentDevice]systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue]

if (IOS_VERSION_MAJOR < 7) {
....
}

8. Document Path

#define DOCUMENT_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

9. NSLog
In release version you want to remove all NSLog, but when debug code's log is very usefully. This macro disable NSLog in release version and enable in debug.

#ifdef DEBUG
#  define LOG(...) NSLog(__VA_ARGS__)
#  define LOG_CURRENT_METHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd))
#else
#  define LOG(...) ;
#  define LOG_CURRENT_METHOD ;
#endif

NSLog(@"Test");

-> LOG(@"Test");

10. Async

#define TTAsync(...) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ##__VA_ARGS__)

11.  Async Main Queue

#define TTAsyncMain(...) dispatch_async(dispatch_get_main_queue(), ##__VA_ARGS__)

12. Dispatch Once

#define TTOnce(...) { \
    static dispatch_once_t __wb_oncePred; \
    dispatch_once(&__wb_oncePred, ##__VA_ARGS__); \
}

Monday, August 18, 2014

[English] The Push-Notification on iOS8

In iOS8 maybe "registerForRemoteNotificationTypes:" is deprecated. So if you wanna get notification list in iOS 8. You should follow this way. 


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //-- Set Notification
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
            [[UIApplication sharedApplication] registerForRemoteNotifications];
        }
        else
        {
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
             (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
        }

     //--- your custom code
     return YES;
}

Wednesday, August 13, 2014

[English] [Cocos2d-x v3] Layer and Scene Template for xcode.


When you want to create new Layer or Scene file, in xcode you can easy create new file.



Implement template

Very easy to implement to your xcode:
- Download template file here
- Go to Application/xcode.app , right click to xcode file -> Show Package Contents.
- Go to Contents/Developer/Library/Xcode/Templates/File Templates.
- Coppy the template file which  is downloaded (KidCocos2d-x) to the File Templates folder
Done !

Monday, August 4, 2014

[English] Ansyc load the texture

In loading scene you should use ansyc load the atlas and other resource.

void LoadingScene::onEnter(){
    // add background to current scene
    Sprite *background = Sprite::create("splash.png");
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();
    background->setPosition(origin.x + visibleSize.width/2, origin.y + visibleSize.height/2);
    this->addChild(background);

    // start ansyc method load the atlas.png
    Director::getInstance()->getTextureCache()->addImageAsync("GameAtlas.png", CC_CALLBACK_1(LoadingScene::loadingCallBack, this));
}


void LoadingScene::loadingCallBack(Texture2D *texture){
    
    auto plPath = FileUtils::getInstance()->fullPathForFilename("GameAtlas.plist");
    //auto plPath = "atlas/GameAtlas.plist";
    auto frameCache = SpriteFrameCache::getInstance();
    frameCache->addSpriteFramesWithFile(plPath, texture);

    // After loading the texture , preload all the sound
    SimpleAudioEngine::getInstance()->preloadEffect("audio1.ogg");

    // After load all the things, change the scene to new one
    auto scene = MainScene::create();
    TransitionScene *transition = TransitionFade::create(1, scene);
    Director::getInstance()->replaceScene(transition);
}


Sunday, August 3, 2014

[My Note] What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?


  1. Long Polling
  2. Server-Sent Event
  3. Websockets
  4. Comet

    In the examples below the client is the browser and the server is the webserver hosting the website.
    Before you can understand these technologies, you have to understand classic http web traffic first.

    Regular http:

    1. A client requests a webpage from a server.
    2. The server calculates the response
    3. The server sends the response to the client.
    HTTP

    AJAX Polling:

    1. A client requests a webpage from a server using regular http (see http above).
    2. The requested webpage executes javascript which requests a file from the server at regular intervals (e.g. 0.5 seconds).
    3. The server calculates each response and sends it back, just like normal http traffic.
    AJAX Polling

    AJAX Long-Polling:

    1. A client requests a webpage from a server using regular http (see http above).
    2. The requested webpage executes javascript which requests a file from the server.
    3. The server does not immediately respond with the requested information but waits until there's newinformation available.
    4. When there's new information available, the server responds with the new information.
    5. The client receives the new information and immediately sends another request to the server, re-starting the process.
    AJAX Long-Polling

    HTML5 Server Sent Events (SSE) / EventSource:

    1. A client requests a webpage from a server using regular http (see http above).
    2. The requested webpage executes javascript which opens a connection to the server.
    3. The server sends an event to the client when there's new information available.
      • Real-time traffic from server to client, mostly that's what you'll need
      • You'll want to use a server that has an event loop
      • Not possible to connect with a server from another domain
      • If you want to read more, I found these very useful: (article)(article)(article)(tutorial).
    HTML5 SSE

    HTML5 Websockets:

    1. A client requests a webpage from a server using regular http (see http above).
    2. The requested webpage executes javascript which opens a connection with the server.
    3. The server and the client can now send each other messages when new data (on either side) is available.
      • Real-time traffic from the server to the client and from the client to the server
      • You'll want to use a server that has an event loop
      • With WebSockets it is possible to connect with a server from another domain.
      • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
      • If you want to read more, I found these very useful: (article), (article) (tutorial).
    HTML5 WebSockets

    Comet:

    Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.

    Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?
    You can use PHP with WebSockets, check out Ratchet.

    (http://stackoverflow.com/)