close

需要被HttpPost 的 Model

public class BaseParameter {

    /**

     * 取得 Http body QueryString

     */

    public func getHttpData() -> NSData?

    {

        let mirror = Mirror(reflecting: self)

        var str: String = ""

        for child in mirror.children

        {

            let key = child.label!

            let value = Utilities.unwrap(child.value)!

            str += "\(key)=\(value)&"

        }

        // 移除最後一個'&'

        str = String(str.characters.dropLast())

        return str.dataUsingEncoding(NSUTF8StringEncoding)

    }

}


========================================

將Mirror 的value取得內容值

public class Utilities
{
    public static func unwrap(subject: Any) ->
 Any? {
        var value: Any?
        let mirrored = Mirror(reflecting:subject)
        if mirrored.displayStyle != .Optional {
            value = subject
        } else if let firstChild = mirrored.children.first {
            value = firstChild.value
        }
        return value
    }
}

如果是複雜的Model,getHttpData 需要再改寫


參考資料: 

http://stackoverflow.com/questions/31773928/how-to...

https://stackoverflow.com/questions/24122288/remov...

http://stackoverflow.com/questions/9460817/form-da...

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(0) 人氣()