swift2 Alomofire POST请求(以swift格式)

xzlaal3s  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(158)

我在我的swift 2.0项目中使用了下面的代码。虽然我添加了“import Alamofire”,但我不能添加Alamofire。请求。我必须创建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。

50few1ms

50few1ms1#

请参阅我的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")

                    }
            }
    }
guykilcj

guykilcj2#

请求并非总是JSON格式,请检查您的请求:
以下是将Alamofire与Swift 2配合使用的示例:

获取- 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)
}

相关问题