[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";
    };
}