[objective-c]Get,Postリクエスト

Get,Postリクエスト

objective-c
ヘッダーファイル

__strong NSMutableData*mData;

メインファイル

-(NSString*)getQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getEncodedQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        NSString*value = dic[key];
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,[value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]] ]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getDatetimeFromDate:(NSDate*)date
{
    NSDateFormatter* form = [[NSDateFormatter alloc] init];
    NSCalendar* cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [form setCalendar: cal];
    [form setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* str = [form stringFromDate:date];
    return str;
}

/**
 返り値はNSArrayまたはNSDictionary
 **/
-(id)getDataByJsonString:(NSString*)jsonString{
    NSData *json_data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError*tmp=nil;
    id data = [NSJSONSerialization JSONObjectWithData:json_data options:NSJSONReadingAllowFragments error:&tmp];
    if (tmp) {
        return nil;
    }
    return data;
}

-(NSURLConnection*)exeHttpGetWithURL:(NSString*)_url queryString:(NSString*)_getQueryString delegate:(id)delegate
{
    
    NSString *url=[NSString stringWithFormat:@"%@?%@",_url,_getQueryString];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    //送信
    return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}

-(NSURLConnection*)exeHttpPostWithURL:(NSString*)_url queryString:(NSString*)_postQueryString delegate:(id)delegate
{
    //リクエスト設定
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
    [request setHTTPMethod:@"POST"];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
    [request setTimeoutInterval:20];
    [request setHTTPShouldHandleCookies:FALSE];
    NSData*httpBody=[_postQueryString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:httpBody];
    
    //送信
    return [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}

/**
 認証
 **/
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //basic認証のid,passを求められたら
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"userID"
                                                                    password:@"password"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        
    }else {
        //認証失敗
        NSLog(@"failure");
    }
}

/**
 データ受信
 受信データが大きいときは一回で全データを取得できないので、mDataにappendDataしておく
 **/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    if (data) {
        [mData appendData:data];
    }
}

/**
 データ受信完了
**/
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString*jsonString=[[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
    mData=nil;
    id json=[self getDataByJsonString:jsonString];
    
    //NSDictionaryのとき
    if ([json isKindOfClass:[NSDictionary class]]) {
        NSLog(@"NSDictionary\n%@", [json description]);
        
    //NSArrayのとき
    }else if([json isKindOfClass:[NSArray class]]){
        NSLog(@"NSDictionary\n%@", [json description]);
        
    }
}

-(IBAction)onTapButton:(UIButton*)sender
{
    mData=[[NSMutableData alloc]init];
    NSString*url=@"/php/50/index.php";
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"datetimeOfSend"]=[self getDatetimeFromDate:[NSDate date]];
    dic[@"message"]=@"あいうえお";
    
    switch ((int)sender.tag) {
        case 0://GET
            [self exeHttpGetWithURL:url queryString:[self getEncodedQueryStringByDic:dic] delegate:self];
            break;
        case 1://POST
            [self exeHttpPostWithURL:url queryString:[self getQueryStringByDic:dic] delegate:self];
            break;
        default:
            break;
    }
}

php

$tmp=array("yourData" => "none" );
if(!empty($_GET)){
	$tmp["yourData"]=$_GET;
	$tmp["method"]="GET";
}else if(!empty($_POST)){
	$tmp["yourData"]=$_POST;
	$tmp["method"]="POST";
}
$tmp["datetime"]=date("Y-m-d H:i:s");
$tmp["randomStr"]=getRandomStr(48);
$tmp["name"]="john";
$tmp["place"]="newyork";
$tmp["device"]="iPhone5s";

header("Content-Type: application/json; charset=utf-8");
echo json_encode($tmp);
exit;

function getRandomStr($length=8){
	$str='';
	for ($i = 0, $str = null; $i < $length; ) {
		$num = mt_rand(0x30, 0x7A);
		if ((0x30 <= $num && $num <= 0x39) || (0x41 <= $num && $num <= 0x5A) || (0x61 <= $num && $num <= 0x7A)) {
			$str .= chr($num);
			$i++;
		}
	}
	return $str;
}

NSLogの結果 GET

NSDictionary
{
    datetime = "2014-04-11 14:37:28";
    device = iPhone5s;
    method = GET;
    name = john;
    place = newyork;
    randomStr = aepa0FUQzn2hOJbB7mwzDztUzpE0FuV5kyihl8t90LQSfNoa;
    yourData =     {
        datetimeOfSend = "2014-04-11 14:37:28";
        message = "\U3042\U3044\U3046\U3048\U304a";
    };
}

NSLogの結果 Post

NSDictionary
{
    datetime = "2014-04-11 14:40:43";
    device = iPhone5s;
    method = POST;
    name = john;
    place = newyork;
    randomStr = if7wIKtiAIxgJ32GzIlXOPOvzmokZYR6emlJhIpDvmlO8F2S;
    yourData =     {
        datetimeOfSend = "2014-04-11 14:40:43";
        message = "\U3042\U3044\U3046\U3048\U304a";
    };
}

[objective-c]NSDictionaryをクエリ文字列にする

NSDictionaryをクエリ文字列にする

-(NSString*)getQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(NSString*)getEncodedQueryStringByDic:(NSDictionary*)dic
{
    NSArray*keys = [dic allKeys];
    NSMutableArray*tmp=[NSMutableArray array];
    for (NSString*key in keys) {
        NSString*value = dic[key];
        [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,[value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]] ]];
    }
    return [tmp componentsJoinedByString:@"&"];
}
-(IBAction)onTapButton:(id)sender
{
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"id"]=@"285";
    dic[@"name"]=@"jeff";
    dic[@"place"]=@"newyork";
    dic[@"version"]=@"iOS7.1";
    
    NSLog(@"%@", [self getQueryStringByDic:dic] );
}

結果

place=newyork&id=285&name=jeff&version=iOS7.1

[javascript]substrの挙動

実行するコード

var str="abcdefg";
alert( str.substr(-1,1) );

文字列の最後の1文字を取得するはずですが、IE8以下だと最初の1文字を取得するようです。

■結果
chrome
chrome

firefox
firefox

safari
safari

IE11
ie11

IE10
ie10

IE9
ie09

IE8
ie08

[objective-c]UIWebViewのリンクタップ制御

UIWebViewのリンクタップ制御
ヘッダーファイル

<UIWebViewDelegate>

メインファイル

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSString*url=[[request URL]absoluteString];
	NSLog(@"url : %@", url);
	//Safariで開く
        [[UIApplication sharedApplication] openURL:[request URL]];
    }
    return YES;
}

[PHP]暗号化・複合化

暗号化・複合化

define('KEY', 'bsrNaTwou3PJJbUHMVp20BW0JFxszbOdTaYTtY2jD26TxNFZ');//getRandomStr(48)で取得
define('IV', 'rfKvr+rLztklJ0/6hc8ZmrILlMLVoan6ltu/SR2Bvzg=');//getCryptIV()で取得

$str='あいうえお';

$crypted_str = getEncrypt($str);
echo $crypted_str;
echo '<br/><br/>';
$decrypted_str = getDecrypt($crypted_str);
echo $decrypted_str;
exit;

function getEncrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $encrypt = mcrypt_generic($resource, $data);
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return base64_encode($encrypt);
}
function getDecrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $decrypt = mdecrypt_generic($resource, base64_decode($data));
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return $decrypt;
}
function getCryptIV(){
	$key = getRandomStr(48);
	$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
	$iv  = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	$iv = base64_encode($iv);
	mcrypt_module_close($td);
	return $iv;
}
function getRandomStr($length=8){
	$str='';
	for ($i = 0, $str = null; $i < $length; ) {
		$num = mt_rand(0x30, 0x7A);
		if ((0x30 <= $num && $num <= 0x39) || (0x41 <= $num && $num <= 0x5A) || (0x61 <= $num && $num <= 0x7A)) {
			$str .= chr($num);
			$i++;
		}
	}
	return $str;
}

[PHP]INSERT文を作る

INSERT文を作る

echo getInsertQueryByKey('system_table', array('name','gender'), array( array('jeff','male'), array('pola','female') ) );

function getInsertQueryByKey($tableName,$columns,$datas){

	//SQLite古いバージョン
	$w=array();

	$column = implode(',', $columns);
	$query="INSERT INTO {$tableName} ({$column}) SELECT ";
	$tmp=array();
	foreach ($columns as $index => $columnName) {
		$tmp[] = "'". $datas[0][$index] . "'" . ' AS ' . $columnName;
	}
	$query .= implode(', ', $tmp);
	$w[]=$query;

	foreach ($datas as $index => $data) {
		if($index<1)continue;
		$tmp=array();
		foreach ($columns as $index2 => $columnName) {
			$tmp[]=$data[$index2];
		}
		$w[]="'".implode("', '", $tmp)."'";
	}

	return implode(' UNION ALL SELECT ', $w).';';

	/* MySQL or SQLite(バージョン 3.7.11以降)
	$queryValues=array();
	foreach ($datas as $index => $value) {
		$values=array();
		foreach ($value as $index2 => $value2) {
			$values[]="'".$value2."'";
		}
		$queryValues[]='('.implode(',', $values).')';
	}

	$column=implode(',', $columns);
	$value=implode(',', $queryValues);
	$sql="INSERT INTO {$tableName} ({$column}) VALUES {$value};";
	return $sql;
	*/
}

[MySQL,SQLite]INSERTで複数のデータを挿入

INSERTで複数のデータを挿入

INSERT INTO system_table (name,gender) SELECT 'jeff' AS name, 'male' AS gender UNION ALL SELECT 'pola', 'female';

MySQL or SQLite(バージョン 3.7.11以降)

INSERT INTO system_table (name,gender) VALUES ('jeff','male'),('pola','female');