App Develop

[Swift]XCode6.2におけるシングルトン

XCode6.2におけるシングルトン

クラス

private let sharedInstance = MyClass()

class MyClass {
    class func getInstance() -> EKEventManager {
        return sharedInstance
    }
    private init(){
        //一回だけ実行される
    }
}

使う時

let myc:MyClass = MyClass.getInstance()

[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)

[Swift]デバイスの時刻取得

デバイスの時刻取得

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

[Swift]ファイル、フォルダ存在確認

ファイル、フォルダ存在確認

private func existFileWithPath(path:String) -> Bool{
    let _path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + path)
    return NSFileManager.defaultManager().fileExistsAtPath(_path)
}

[Swift]ファイル、フォルダ削除

ファイル、フォルダ削除

private func removeFileWithPath(path:String) -> Bool{
    let _path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + path)
    var error: NSError? = nil
    return NSFileManager.defaultManager().removeItemAtPath(_path, error: &error)
}

[Swift]フォルダ作成

フォルダ作成

private func mkDir(path:String) -> Bool{
    let _path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + path)
    var error: NSError? = nil
    return NSFileManager.defaultManager().createDirectoryAtPath(_path, withIntermediateDirectories: true, attributes: nil, error: &error)
}

[Swift]Documentsフォルダ内のファイル一覧出力

Documentsフォルダ内のファイル一覧出力

private func getFileNames(dir:String) -> [String]{
    let path = NSHomeDirectory().stringByAppendingPathComponent("Documents/" + dir)
    var error: NSError? = nil
    let fileNames:[AnyObject] = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path,error:&error)!
    var tmp:[String] = []
    for fileName:AnyObject in fileNames {
        tmp.append(fileName as String)
    }
    return tmp
}
private func logFileNames(){
    println("----------------- " + __FUNCTION__ + "---------------------")
    let files:[String] = self.getFileNames("")
    for n:String in files {
        println("\(n)")
    }
}

[Swift]NSTimer

NSTimer

NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "showInfo", userInfo: nil, repeats: false)

func showInfo(){
    println("あいうえお")
}

[Swift]ログメソッド

ログメソッド

func LOG(message:String = "", file:String = __FILE__, funcName:String = __FUNCTION__, line:Int = __LINE__) {
    #if DEBUG
        var f:String = file.componentsSeparatedByString("/").last!
        var cnt:Int = 45 - f.utf16Count
        while 0 < cnt {
            f += " "
            cnt--
        }
        var sline:String = String(line)
        cnt = 4 - sline.utf16Count
        while 0 < cnt {
            sline = " "+sline
            cnt--
        }
        if message.isEmpty {
            println("\(f) - \(sline) - \(funcName)")
        }else{
            println("\(f) - \(sline) - \(funcName)\n -> \(message)")
        }
    #endif
}

出力結果

ViewController.swift                          -   65 - onChangeTimeScale
 -> selectedIndex : 0

[Swift]objective-cで書かれたクラスを扱う

objective-cで書かれたクラスを扱う

1.「Common-Bridging-Header.h」というヘッダーファイルを作成する
*ファイル名は任意

2.Common-Bridging-Header.hに下記を記述する

#import "EGODatabase.h"

3.PROJECT -> Build Settings -> Swift Compiler – Code Generation
-> Objective-C Bridging Headerに作成したファイル名を設定する
Objective-C Bridging Header

4.普通に扱う

let ego:EGODatabase = EGODatabase(path: "\(NSHomeDirectory())/Documents/ultrawoman.db")
private init(){
    self._initSystemTable()
}
private func createTableWithTableName(tableName:String, columnInfo:String) -> Bool{
    let query:String = "CREATE TABLE IF NOT EXISTS '\(tableName)' (\(columnInfo));"
    let result:EGODatabaseResult = self.ego.executeQuery(query)
    if 0 < result.errorCode {
        return false
    }
    return true
}
private func _initSystemTable(){
    let table:String = "id INTEGER PRIMARY KEY AUTOINCREMENT,key TEXT DEFAULT '',value TEXT DEFAULT '',modified TEXT,created TEXT"
    let result:Bool = self.createTableWithTableName(self.tableNameOfSystem, columnInfo: table)
}