我在Corona的背景下,我曾经为所有与服务器相关的代码(简称所有HTTP调用)保留一个公共文件(您可以将其视为一个类)。哪个是最好的,所以可以推广多个常用的东西来使用多个函数。
如果我做一个常见的任务关闭,那么我如何将这些数据传递给特定的VC(其名称作为参数传递给特定的函数)
请让我了解iOS开发者如何实现它。什么是最佳实践? 你可以看到1-2个函数不需要理解我的整个代码。
请不要建议Alamofire,我不想依赖第三方图书馆。
import Foundation
class Server
{
static let baseURL="http://www.bewrapd.com/api/call/"
class func convertDataToArray(_ data: Data) -> NSArray
{
do
{
let json = try JSONSerialization.jsonObject(with: data , options: [])
print(json)
return json as! [[String:AnyObject]] as NSArray
}
catch let error as NSError
{
print(error)
}
return []
}
class func convertStringToDictionary(_ data: Data) -> [String:AnyObject]?
{
do
{
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
return json
}
catch let error as NSError
{
print(error)
}
return nil
}
//-----------------------------------------
class func tryToLogin(target: LoginViewController, userName: String, password: String )
{
var request = URLRequest(url: URL(string: baseURL+"checkLoginForIos")!)
request.httpMethod = "POST"
let postString = "userName="+userName+"&password="+password
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertStringToDictionary(data)
target.nextAction(finalData!)
}
task.resume()
}
class func fetchCarsForUser(target: CarSelectionViewController)
{
var request = URLRequest(url: URL(string: baseURL+"getAddedCarsByUser")!)
request.httpMethod = "POST"
let postString = "userId=\(userId!)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertDataToArray(data)
target.nextAction(finalData as! [[String : AnyObject]])
}
task.resume()
}
class func updateCarsStatusForUser(target: CarSelectionViewController, carId: Int, status: Bool)
{
var request = URLRequest(url: URL(string: baseURL+"updateCarBookingStatus")!)
request.httpMethod = "POST"
let postString = "carId=\(carId)&status=\(status)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertStringToDictionary(data)
target.carStatusChangeCallback(finalData!)
}
task.resume()
}
class func unbookCar(target: MenuController, status: Bool)
{
var request = URLRequest(url: URL(string: baseURL+"updateCarBookingStatus")!)
request.httpMethod = "POST"
let postString = "carId=\(carId!)&status=\(status)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertStringToDictionary(data)
target.nextAction(finalData!)
}
task.resume()
}
//-----------------------------------------
class func fetchCurrentCampaign(target: CampaignViewController )
{
var request = URLRequest(url: URL(string: baseURL+"getCurrentCampaign")!)
request.httpMethod = "POST"
let postString = "userId=\(userId!)&carId=\(carId!)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
//--------------
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)!
print("responseString = \(responseString)")
let finalData = Server.convertStringToDictionary(data)
target.nextAction(finalData!)
}
task.resume()
}
class func fetchCarHistory(target: HistoryTableViewController )
{
var request = URLRequest(url: URL(string: baseURL+"campaignHistory")!)
request.httpMethod = "POST"
let postString = "userId=\(userId!)&carId=\(carId!)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let finalData = Server.convertDataToArray(data)
target.nextAction(finalData as! [[String : AnyObject]] as NSArray)
}
task.resume()
}
class func fetchTripsForCampaign(target: TripsViewController, jobId: Int )
{
var request = URLRequest(url: URL(string: baseURL+"gpsHistory")!)
request.httpMethod = "POST"
let postString = "jobAppId=\(jobId)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let finalData = Server.convertDataToArray(data)
target.nextAction(finalData as! [[String : AnyObject]] as NSArray)
}
task.resume()
}
class func fetchTripsGeoCoordinates(target: RoutesMapViewController, tripId: Int )
{
//------
var request = URLRequest(url: URL(string: baseURL+"mapHistory")!)
request.httpMethod = "POST"
let postString = "tripId=\(tripId)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let finalData = Server.convertDataToArray(data)
target.nextAction(finalData as! [[String : AnyObject]] as NSArray)
}
task.resume()
}
class func fetchCampaignList(target: CampaignListViewController )
{
var request = URLRequest(url: URL(string: baseURL+"getCampaignList")!)
request.httpMethod = "POST"
let postString = "userId=\(userId!)&carId=\(carId!)"//+String(describing: userId)
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let finalData = Server.convertDataToArray(data)
target.nextAction(finalData as! [[String : AnyObject]] as NSArray)
}
task.resume()
}
class func applyForCampaign(target: JoApplyViewController, campaignId: Int )
{
var request = URLRequest(url: URL(string: baseURL+"applyCampaign")!)
request.httpMethod = "POST"
let postString = "campaignId=\(campaignId)&userId=\(userId!)&carId=\(carId!)"
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let finalData = Server.convertStringToDictionary(data)
target.nextAction(finalData!)
}
task.resume()
}
class func sendTripData(target: MapViewController, tripDataJSONStr: String)
{
var request = URLRequest(url: URL(string: baseURL+"sendTripCordinatesForIos")!)
request.httpMethod = "POST"
let postString = "request=" + tripDataJSONStr
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertStringToDictionary(data)
target.nextAction(finalData!)
}
task.resume()
}
}
答案 0 :(得分:1)
您可以使用闭包,不确定是否需要任何其他要求,实际上与您当前的代码没有区别,只是更容易使用:
class func tryToLogin(userName: String, password: String, completion: (_ result: [String:Any])->() )
{
var request = URLRequest(url: URL(string: baseURL+"checkLoginForIos")!)
request.httpMethod = "POST"
let postString = "userName="+userName+"&password="+password
print("### \(postString)")
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let finalData = Server.convertStringToDictionary(data)
completion(finalData)
}
task.resume()
}
在LoginViewController
上,只需正常调用,命名数据字典并在关闭时调用nextAction(finalData!)
答案 1 :(得分:0)
您可以创建一个如下所示的方法:
class func makeWebServiceCall(url:URL,postString:String,completionClosure:@escaping(_ success:Bool, _ data:Data?, _ response:HTTPURLResponse?, _ error:Error?)->Void){
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let respData = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
completionClosure(false,data,response as? HTTPURLResponse,error)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
completionClosure(false,data,response as? HTTPURLResponse,error)
return
}
let responseString = String(data: respData, encoding: .utf8)
print("responseString = \(responseString)")
completionClosure(true,data,response as? HTTPURLResponse,error)
}
task.resume()
}
现在从任何视图控制器调用此方法并分别在指定的视图控制器中处理响应。
Server.makeWebServiceCall(url: URL(string:"")!, postString: "", completionClosure: { (isSuccess, data, response, error) in
if isSuccess{
print("call is success")
}else{
print("ohh no, call failed")
}
})