2016-11-07 77 views
0
typealias ServiceResponse = (JSON, NSError?) -> Void 
class RestApiManager: NSObject { 
    static let sharedInstance = RestApiManager() 
    let baseURL = "http://api.randomuser.me/" 
    func postUser(){} 
    func getRandomUser(onCompletion: (JSON) -> Void) { 
     let route = baseURL 
     makeHTTPGetRequest(route, onCompletion: { json, err in 
      onCompletion(json as JSON) 
     }) 
    } 
    func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) { 
     let request = NSMutableURLRequest(URL: NSURL(string: path)!) 
     let session = NSURLSession.sharedSession() 
     let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
      let json:JSON = JSON(data: data) 
      onCompletion(json, error) 
     }) 
     task.resume() 
    } 
    func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) { 
     var err: NSError? 
     let request = NSMutableURLRequest(URL: NSURL(string: path)!) 
     // Set the method to POST 
     request.HTTPMethod = "POST" 
     // Set the POST body for the request 
     request.HTTPBody = NSJSONSerialization.dataWithJSONObject(body, options: nil, error: &err) 
     let session = NSURLSession.sharedSession() 
     let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
      let json:JSON = JSON(data: data) 
      onCompletion(json, err) 
     }) 
     task.resume() 
    } 
} 

如何在我的ViewController中調用httppost方法postuser並將頭文件+編碼參數傳遞給它?如何使用swift進行HTTP POST請求

Like http://www.api.com/post/data?username=kr%209&password=12 我需要在ehader中發送會話/ cookie/useragent。

+0

request.allHTTPHeaderFields = [ 「內容類型」: 「應用/ JSON」, 「接受」: 「應用/ JSON」 ] request.addValue(mySessionToken,forHTTPHeaderField: 「SessionToken」) – jpulikkottil

+0

當然,你可以做到這一點。如果你設法寫出你上面寫的代碼,那事情會非常簡單。只需爲需要的方法添加額外的參數,然後構建請求。 – EridB

回答

0
request.setValue("Your Header value", forHTTPHeaderField: "Header-Key") //User-Agent for ex. 
0

請注意,該類有一個sharedInstance靜態屬性?這是一個快速實施的singleton pattern。這使您可以撥打RestApiManager類的方法如下:

let postBody: [String: AnyObject] = [ 
    "username": "joe.bloggs", 
    "password": "test1234" 
] 

RestApiManager.sharedInstance.makeHTTPPostRequest(path: "relative/url", body: postBody) { json, err in 
    // Handle response here... 
} 

單例模式允許你從項目的任何地方調用類的sharedInstance實例。您不需要在viewController中創建API管理器的實例來使用它。