gpt4 book ai didi

ios - 快速的 Alamofire POST 请求

转载 作者:行者123 更新时间:2023-11-28 09:45:37 24 4
gpt4 key购买 nike

我在我的 swift 2.0 项目中使用了以下代码。虽然我添加了“导入 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。

最佳答案

请查看我的 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")

}
}
}

关于ios - 快速的 Alamofire POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32941187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com