[Swift]GET,POSTリクエスト

クラス

import Foundation

class RequestManager:NSObject,NSURLConnectionDelegate,NSURLConnectionDataDelegate{
    var storedData:NSMutableData?
    
    //------------------ init --------------------
    override init(){
        
    }
    
    //------------------ common --------------------
    private func getQueryStringByDic(dic:Dictionary<String,String>) -> String{
        var tmp:[String] = []
        for key:String in dic.keys {
            tmp.append("\(key)=\(dic[key])")
        }
        return join("&",tmp)
    }
    private func getUrlEncodedQueryStringByDic(dic:Dictionary<String,String>) -> String{
        var tmp:[String] = []
        for key:String in dic.keys {
            let value:String = dic[key]!
            tmp.append("\(key)=\(value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!)")
        }
        return join("&",tmp)
    }
    private func getDeviceDatetimeString() -> String{
        let date:NSDate = NSDate(timeIntervalSinceNow:NSTimeInterval(NSTimeZone.systemTimeZone().secondsFromGMT))
        var form:NSDateFormatter = NSDateFormatter()
        form.calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
        form.dateFormat = "yyyy-MM-dd HH:mm:ss"
        form.timeZone = NSTimeZone(forSecondsFromGMT: 0)
        form.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        return form.stringFromDate(date)
    }
    /**
    返り値は[AnyObject]またはDictionary
    **/
    private func getDataByJsonString(json:String) -> AnyObject?{
        let jsonData:NSData? = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        if jsonData == nil {
            return nil
        }
        var error: NSError? = nil
        let data:AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments, error: &error)
        if error != nil {
            return nil
        }
        return data
    }
    
    //------------------ send --------------------
    func sendHttpGetRequestWithURL(url:String,queryDic:Dictionary<String,String>?) -> NSURLConnection?{
        self.storedData = NSMutableData()
        
        var queryString:String = ""
        if queryDic != nil {
            queryString = "?" + self.getUrlEncodedQueryStringByDic(queryDic!)
        }
        let request:NSURLRequest = NSURLRequest(URL: NSURL(string: url + queryString)!)
        return NSURLConnection(request: request, delegate: self)
    }
    func sendHttpPostRequestWithURL(url:String,queryDic:Dictionary<String,String>?) -> NSURLConnection?{
        self.storedData = NSMutableData()
        
        let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string:url)!)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 20
        request.HTTPShouldHandleCookies = false
        request.HTTPBody = self.getQueryStringByDic(queryDic!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
        return NSURLConnection(request: request, delegate: self)
    }
    
    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        println(response)
    }
    func connection(connection: NSURLConnection, didReceiveData data: NSData) {
        self.storedData?.appendData(data)
    }
    func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
        //basic認証のid,passを求められたら
        if challenge.previousFailureCount == 0 {
            let newCredential:NSURLCredential = NSURLCredential(user: "userID", password: "password", persistence: NSURLCredentialPersistence.ForSession)
            challenge.sender.useCredential(newCredential, forAuthenticationChallenge: challenge)
        }else{
            //認証失敗
            println("authentication failed")
        }
    }
    func connectionDidFinishLoading(connection: NSURLConnection) {
        let jsonString:String? = NSString(data: self.storedData!, encoding: NSUTF8StringEncoding)
        if jsonString == nil {
            println("connectionDidFinishLoading Failed 1")
            return
        }
        let json:AnyObject? = self.getDataByJsonString(jsonString!)
        if json == nil {
            println("connectionDidFinishLoading Failed 2")
            return
        }
        
        if json is Dictionary<String,AnyObject> {
            println("json is Dictionary")
            self.logDic(json as Dictionary<String,AnyObject>)
        }else if json is [AnyObject] {
            println("json is Array")
            self.logArray(json as [AnyObject])
        }
    }
    private func logDic(dic:Dictionary<String,AnyObject>){
        for key:String in dic.keys {
            println("\(key) : \(dic[key])")
        }
    }
    private func logArray(list:[AnyObject]){
        for (i:Int,obj:AnyObject) in enumerate(list) {
            println("\(i) : \(obj)")
        }
    }
}

実行

var reqdic:Dictionary<String,String> = Dictionary()
reqdic["sendDatetime"] = self.getDeviceDatetimeString()
reqdic["message"] = "どうしてもつかまるです。むぎちゃ。"
let reqm:RequestManager = RequestManager()
//GET
reqm.sendHttpGetRequestWithURL("/php/50/index.php", queryDic: reqdic)

//POST
reqm.sendHttpPostRequestWithURL("/php/50/index.php", queryDic: reqdic)

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

出力結果

<NSHTTPURLResponse: 0x7fcd5ad0ec20> { URL: /php/50/index.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Tue, 09 Jun 2015 10:24:37 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.4.32";
} }
json is Dictionary
yourData : Optional({
    message = "Optional(\"\U3069\U3046\U3057\U3066\U3082\U3064\U304b\U307e\U308b\U3067\U3059\U3002\U3080\U304e\U3061\U3083\U3002\")";
    sendDatetime = "Optional(\"2015-06-09 19:24:38\")";
})
device : Optional(iPhone5s)
place : Optional(newyork)
method : Optional(POST)
datetime : Optional(2015-06-09 19:24:37)
randomStr : Optional(LM3HqZ3X2GG6nQ9APqZ67gSud3mbLjHMzjTommuH0gwaxsMN)
name : Optional(john)