IOS Swift从表单发布请求和身份验证和数据

时间:2016-09-04 11:01:17

标签: ios swift

我有以下代码,我正在尝试向api发送帖子请求。

当我通过bash运行以下内容时,我得到了一个创建的响应。但是,当我尝试将其转换为swift并运行代码时,api会拒绝我的代码。

有什么想法吗?

http -a mike:密码POST http://mybudget-env.hnfarjj5iy.ap-southeast-2.elasticbeanstalk.com/api/transactions/金额= 1000用户=迈克说明= test1

HTTP/1.1 201 Created
Allow: GET, POST, HEAD, OPTIONS
Connection: keep-alive
Content-Type: application/json
Date: Sun, 04 Sep 2016 10:45:39 GMT
Server: Apache/2.4.23 (Amazon) mod_wsgi/3.5 Python/2.7.10
Vary: Accept,Cookie
X-Frame-Options: SAMEORIGIN
transfer-encoding: chunked

{
    "amount": "1000", 
    "created": "2016-09-04T10:45:39.432369Z", 
    "description": "test1", 
    "id": 18, 
    "owner": 2
}

我的viewcontroller.swift

import UIKit

class PostController: UIViewController {

    @IBOutlet weak var firstname: UITextField!
    @IBOutlet weak var lastname: UITextField!
    @IBOutlet weak var instrument: UITextField!
    @IBOutlet weak var test: UITextField!

    @IBAction func buttonPost(sender: UIButton) {
        print(postForm("amount=" + self.firstname.text! + " user=" + self.lastname.text! + " description=" + self.instrument.text!))


    }

    override func viewDidLoad() {
        super.viewDidLoad()


        firstname.autocorrectionType = .No
        lastname.autocorrectionType = .No
        instrument.autocorrectionType = .No
        test.autocorrectionType = .No


        //Looks for single or multiple taps.
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PostController.dismissKeyboard))
        view.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func postForm(postString: String) -> String {

        let url:NSURL = NSURL(string: "http://mybudget-env.hnfarjj5iy.ap-southeast-2.elasticbeanstalk.com/api/transactions/")!
        let session = NSURLSession.sharedSession()

        let username = "mike"
        let password = "password"
        let loginString = NSString(format: "%@:%@", username, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions([])

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

        let paramString = postString
        request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }

            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(dataString)

        }

        task.resume()




        let greeting = postString
        return greeting
    }


    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }



    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

1 个答案:

答案 0 :(得分:2)

您没有在请求中设置内容类型,并且您没有在每个参数之间添加&

您应该使用代理工具(如Charles)来检查每种情况下您的设备实际离开网络的位置,以便纠正所有不匹配。