用Alamofire進行網絡請求的一段代碼解析(二)

/*api

        Router路由器,這個枚舉類型採用了URLRequestConvertible協議。採用這個協議的類型,是用來構造URL請求的。這個協議只有一個只讀屬性URLRequest,它是NSURLRequest類型的。函數

    

    

    */spa

    enum Router: URLRequestConvertible {3d

        

        static let baseURLString = "https://api.500px.com/v2"code

        static let consumerKey = "4qf9GGuzHwjVfjmbvoQVpjjbBSjOGv7VbOrSnrgt"orm

        

        /*路由

            Swift的枚舉中,下例的PopularPhotos等被稱爲枚舉值,而枚舉值所指向的值被稱爲關聯值。括號內的類型是關聯值的類型。string

        */it

        case PopularPhotos(Int)coding

        case PhotoInfo(Int, ImageSize)

        case Comments(Int, Int)

        

        var URLRequest: NSURLRequest {

            

            /*

                這是定義了一個元組。

            

                let (,) = {}()這個語句的意思是,元組(,) 用一個函數的返回值進行初始化;小括號的意思是,當即執行這個函數,將返回值賦值給元組。

            */

            let (path: String, parameters: [String: AnyObject]) = {

                switch self {

                case .PopularPhotos(let page):

                    let params = ["consumer_key": Router.consumerKey, "page": "\(page)", "feature": "popular", "rpp": "50", "include_store": "store_download", "include_states": "votes"]

                    return ("/photos", params)

                

                case .PhotoInfo(let photoID, let imageSize):

                    var params = ["consumer_key": Router.consumerKey, "iamge_size": "\(imageSize.rawValue)"]

                    return ("/photos/\(photoID)", params)

                

                case .Comments(let photoID, let commentsPage):

                    var params = ["consumer_key": Router.consumerKey, "comments": "1", "comments_page": "\(commentsPage)"]

                    return ("/photos/\(photoID)/comments", params)

                    

                }

            }()

            

            

            let URL = NSURL(string: Router.baseURLString)

            let URLRequest = NSURLRequest(URL: URL!.URLByAppendingPathComponent(path))

            let encoding = Alamofire.ParameterEncoding.URL

            

            /*

                ParameterEncoding枚舉類型的encode函數沒有函數體,那麼返回值是如何實現的呢??

            */

            return encoding.encode(URLRequest, parameters: parameters).0

        }

        

    }

相關文章
相關標籤/搜索