2016年3月17日 星期四

swift send value via HTTPHeader

i.e authentication

http://stackoverflow.com/questions/35071753/send-data-through-params-to-rails-app-from-ios-in-swift


request.setValue("XXXXXXXXXX", forHTTPHeaderField: "Authorization")

func postRequest2(x: String) {
    let string = "http://localhost:3000/api/users/2/products"
    let url = NSURL(string: string)
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url!)
    let params = ["title": "Fifth Title"]
    request.setValue("XXXXXXXXXX", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
    }
    catch {

    }
    let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
        if let antwort = response as? NSHTTPURLResponse {
            let code = antwort.statusCode
            print(code)
        }
    }
    tache.resume()

}

沒有留言:

張貼留言