iOS http POST使用Alamofire

问题描述 投票:2回答:3

我需要一些帮助,使用Alamofire通过Twilio的API使用用户名/密码对网页进行POST。

我之前使用过GitHub的SwiftRequest,但是它不支持Swift 2.0。

我使用的代码(使用SwiftRequest)是:

        var data = [
            "To" : mobileInput.text as String!,
            "From" : twilioSMSFrom,
            "Body" : String(code) as String
        ]

        var swiftRequest = SwiftRequest()

        swiftRequest.post("https://api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages",
            auth: ["username" : twilioUsername, "password" : twilioPassword],
            data: data,
            callback: {err, response, body in
                if err == nil {
                    println("Success: \(response)")
                } else {
                    println("Error: \(err)")
                }
            })

我怎样才能将其转换为使用Alamofire?

我试过寻找解决方案,但可以找到任何解决方案。

有谁能够帮我?

swift alamofire
3个回答
1
投票

尝试这样的事情:

Alamofire.request(.POST, "https://api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages", parameters: ["username": twilioUsername, "password" : twilioPassword])
     .responseJSON { response in
         print(response.request)
         print(response.response)
         print(response.result)

         if let JSON = response.result.value {
             print("Did receive JSON data: \(JSON)")
         }
         else {
             print("JSON data is nil.")
         }

      }

你一定要查看他们的github页面 - https://github.com/Alamofire/Alamofire


1
投票

我想到了。

使用Alamofire的解决方案:

        let data = [
            "To" : mobileInput.text as String!,
            "From" : twilioSMSFrom,
            "Body" : String(code) as String
        ]

        Alamofire.request(.POST, "https://\(twilioUsername):\(twilioPassword)@api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages", parameters: data)
            .responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
        }

0
投票

这是SWIFT 2.2 VERSION的最新答案试试这个它可以帮助你....

参数: -

    let params : Dictionary = ["YourKEY" : "YourVALUE"]

Post Request_Form: -

Alamofire.request(.POST,"Post Your Url HERE", parameters: params, encoding:.JSON).responseJSON
        {
          response in switch response.result 
            {
                  case .Success(let JSON):
         //   print("Success with JSON: \(JSON)")
            //converting json into NSDictionary

            let response = JSON as! NSDictionary
            print(response)

            var array = NSMutableArray!()
            //converting respose form into NSMutableArray formate
            array = response.valueForKey("countryList")as? NSMutableArray

            //example if there is an id
          //  let userId = response.objectForKey("id")!

        case .Failure(let error):
            print("Request failed with error: \(error)")
            }
    }
© www.soinside.com 2019 - 2024. All rights reserved.