【问题标题】:Alomofire POST request in swift快速的 Alamofire POST 请求
【发布时间】:2026-01-09 04:15:01
【问题描述】:

我在我的 swift 2.0 项目中使用以下代码。尽管我添加了“import Alamofire”,但我无法添加 Alamofire.request。我必须创建 Alamofire 的对象,然后通过它访问。

这就是我创建对象的方式:

let manager = Alamofire.Manager.sharedInstance
manager.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!))

let parameters = ["foo": "bar"]

manager.request(.POST, "url", parameters: parameters)
.responseJSON { request, response, json, error in
print("request: \(request)")
}

我对 Alamofire 和 swift 都是新手。谁能告诉我如何在完成处理程序中从上述代码中获得响应,以及为什么我不能使用 Alamofire.request 而不是 manager.request。

【问题讨论】:

    标签: ios swift xcode swift2 alamofire


    【解决方案1】:

    请查看我的 Post 方法,希望对您有所帮助

    发布方式:

    /**
        ** POST Method for calling API
        *  Services gateway
        *  Method  get response from server
        *  @parameter              -> requestObject: request josn object ,apiName: api endpoint
        *  @returm                 -> void
        *  @compilationHandler     -> success: status of api, response: respose from server, error: error handling
        **/
        static func getDataWithObject( requestObject: NSDictionary, apiName : NSString,
            completionHandler:
            (success : Bool, response : NSDictionary, error : ErrorType?) -> Void) {
    
                // Make Url
                let url = NSURL(string: apiName as String)
                let request = NSMutableURLRequest(URL: url!)
                request.HTTPMethod = "POST"
                //request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
                // Call the method to request and wait for the response
                // @param  ->
                // @return ->
                Alamofire.request(.POST, url!, parameters:requestObject as? [String : AnyObject], encoding: .JSON)
                    .responseJSON {responseRequest, responseResponse, responseResult in
    
                        // Switch for Success or Error
                        switch responseResult {
    
                            // If the API return succesfull response
                        case .Success(let data):
    
                            let data_ar = data as! NSDictionary
                            print(data_ar)
                            // Get the Status if 0 then error if 1 then succes
                            // From our server side
                            if let str = data_ar.valueForKey("OK") as? Bool {
    
                                // Check if the status is OK and no error from
                                // our server side
                                if ( str ) {
    
                                    print("Response from Server %@", data_ar)
    
                                    // Cast the response and pss to handler
                                    // To notify
                                    completionHandler(success: true, response:data_ar
                                        , error:responseResult.error )
                                } else {
                                    print("Error from Our Server %@", data_ar)
                                    let str = data_ar.valueForKey("message") as! NSString
                                    self.showAlertView(str, title: "Error From Server")
                                }
    
                            }
    
                        case .Failure(let data, let error):
                            print("Request failed with error: \(error)")
                            print(data)
                            print((error as! NSError).localizedDescription)
                            self.showAlertView((error as! NSError).localizedDescription, title: "Error From Server")
    
                        }
                }
        }
    

    【讨论】:

      【解决方案2】:

      请求并非总是在 JSON 中,请检查您的请求:

      以下是在 Swift 2 中使用 Alamofire 的示例:

      GET - JSON

      Alamofire.request(.GET, "http://api.androidhive.info/contacts/", parameters: nil, encoding: .JSON, headers: nil).responseJSON { (req, res, json) -> Void in
          print("\(res?.allHeaderFields)")
          print("\(json.value!)")
      }
      

      POST - 没有 JSON

      Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"], encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
          print(res)
          print(data)
      
          let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
          print(dataString)
      }
      

      【讨论】:

      • 谢谢兄弟。你的代码对我来说是完美的。你能告诉我为什么我不能在我的 xcode 中自动完成 Alomofire.request,尽管如果我复制你的代码我没有收到任何错误。对于自动补全,我必须添加一个 Alomofire 对象,然后继续。
      • 您已经创建了 Alamofire 的实例,并且您已经创建了一个 URL 请求,无需这样做。 Alamofire 会处理它。继续@user3730935
      • 但是没有它我不能自动完成我的编码!! :(