Skip to content

Instantly share code, notes, and snippets.

@t-oginogin
Last active December 14, 2015 23:39
Show Gist options
  • Save t-oginogin/5166838 to your computer and use it in GitHub Desktop.
Save t-oginogin/5166838 to your computer and use it in GitHub Desktop.

init

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code
    }
    return self;
}

TextField編集後Keyboardを閉じる

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField canResignFirstResponder]) {
        [textField resignFirstResponder];
    }
    return YES;
}

GCD

- (void)sample
{
    dispatch_queue_t mainDispatchQueue = dispatch_get_main_queue();
    dispatch_queue_t globalDispatchQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _indicator.hidden = NO;
    [_indicator startAnimating];
 
    dispatch_async(globalDispatchQueueDefault, ^{
        
        // ここで非同期で動かす処理
 
        dispatch_async(mainDispatchQueue, ^{
            _indicator.hidden = YES;
            [_indicator stopAnimating];
        });
    });
}

JSON取得(POSTして非同期で受け取る)

- (void)post
{
    NSString *urlString = [NSString stringWithFormat:@"http://xxx.xxx.xxx.xxx/"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
 
    [request setHTTPMethod:@"POST"];
    [request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
    NSString *postString = @"parameter=1";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
 
    void (^handler)(NSURLResponse* response, NSData* data, NSError* error);
    handler = ^(NSURLResponse* response, NSData* data, NSError* error){
 
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        if (httpResponse.statusCode != 200) {
            NSLog(@"HTTP Response error: %@,%@",
                  [error localizedDescription],
                  [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
            return;
        }
 
        if (data == nil) {
            NSLog(@"No data received");
            return;
        }
 
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingAllowFragments error:&error];
 
        if (jsonObject == nil) {
            NSLog(@"JSON data parsing failed");
            return;
        }
 
        // jsonObjectを使う処理
    };
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue currentQueue]
                           completionHandler:handler];
   
}

JSON送信

- (void)postData:(NSDictionary *)jsonObject
{
    NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *error;
    NSURLResponse *response;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:kNilOptions error:&error];
    [request setHTTPBody:jsonData];
 
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}

JavaScriptからnative code実行

JavaScript側

<script type="text/javascript">
    function updateValue(value) {
        window.location = "nativecode://updateValue/"+value;
    }
</script>

iOS側

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;
    if ([[url scheme] isEqualToString:@"nativecode"]) {
        NSString *methodString = [url host];
        
        if ([methodString isEqualToString:@"updateValue"]) {
            NSArray *parameters = [url pathComponents];
            int value = [[parameters objectAtIndex:1] intValue];
            [self updateValue:value];   // execute native method
        }
        return YES;
    }
    return YES;
}

UserDefaults

- (void)setup;
{
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
      						SERVER_URL, @"serverURL",
								nil];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults registerDefaults:dictionary];
    self.serverURL = [defaults stringForKey:@"serverURL"];
}

名前付きブロック定義

void (^editName)(NSString *name);
editName = ^(NSString *name){
};

editName(@"test");

Xcodeで信頼されない証明書を設定したリポジトリにsvn接続できない場合

ターミナルで

$ svn ls <リポジトリのURL>

を実行

(R)eject, accept (t)emporarily or accept (p)ermanently?

と聞かれるので、

(p)ermanently を選択する。

Unit Test時(Target xxxTests)のリソースパス

NSString *filePath = [[NSBundle bundleForClass:[self class]] pathForResource:@"xxxx" ofType:@"xml"];

EXC_BAD_ACCESSの原因探し(ゾンビオブジェクトの検出)

[Product]->[Edit Schema]-[Run XXXXX]-[Arguments]-[Environment Variables]に次を追加。

  • NSDebugEnabled : YES

  • MallocStackLogging : YES

  • NSZombieEnabled : YES

キーチェーンアクセスの公開鍵を別のマシンにインポート

$ security import pub_key.pem -k ~/Library/Keychains/login.keychain

ARC on と ARC offを混在させる

[TARGETS]-[Build Phases]でファイル単位でCompiler Flagsを設定

ARC on

-fobjc-arc

ARC off

-fno-objc-arc

XcodeプロジェクトファイルをRubyで操作

http://rubygems.org/gems/xcodeproj

APNsサンプル

アプリ側

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDictionary *notificationDictionary =
    [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (notificationDictionary) {
        for (NSString *key in notificationDictionary) {
            NSLog(@"key:%@", key);
        }
        NSString *itemName = [notificationDictionary objectForKey:@"todo"];
        NSLog(@"ToDo1: %@", itemName);
        UILocalNotification *localNotification = [notificationDictionary objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        application.applicationIconBadgeNumber = localNotification.applicationIconBadgeNumber - 1;
    }
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
    
    [[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert)];
    
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    const void *devTokenBytes = [deviceToken bytes];
    NSLog(@"deviceToken: %@", deviceToken);
    NSLog(@"Success registration.");
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Error in registration. Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
// プロバイダから送信したJSONデータ
//    {
//        "aps":{
//            "alert":"New Message!",
//            "badge":1,
//        },
//        "todo":"test"
//    }
    for (NSString *key in userInfo) {
        NSLog(@"key:%@", key);
    }
    NSString *itemName = [userInfo objectForKey:@"todo"];
    NSLog(@"ToDo2: %@", itemName);
    application.applicationIconBadgeNumber = 0;
}

プロバイダ側(Ruby)

require 'openssl'
require 'socket'

# device token(32Byte)
device = ['0000000000000000000000000000000000000000000000000000000000000000']

socket = TCPSocket.new('gateway.sandbox.push.apple.com',2195)

context = OpenSSL::SSL::SSLContext.new('SSLv3')
context.cert = OpenSSL::X509::Certificate.new(File.read('apns.pem'))
context.key  = OpenSSL::PKey::RSA.new(File.read('apns.pem'))

ssl = OpenSSL::SSL::SSLSocket.new(socket, context)
ssl.connect

payload = <<EOS
{
  "aps":{
    "alert":"New Message!",
    "badge":1,
  },
  "todo":"test"
}
EOS

puts payload

(message = []) << ['0'].pack('H') << [32].pack('n') << device.pack('H*') << [payload.size].pack('n') << payload

ssl.write(message.join(''))
ssl.close
socket.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment