How to post SwiftyJSON with Alamofire? - ios

I would like to post a JSON via Alamofire.
but i'm not too sure how can i deal with it.
my swiftyJSON is in an array as my
how can i encode an array of JSON into a dictionaryObject? to suits
Alamofire's Parameters?
urlRequest = try JSONEncoding.default.encode(urlRequest, with: location)
my sample JSON looks like this:
"[{\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}, {\n acc = accuracy;\n lat = lat;\n long = long;\n type = type;\n}]"

The trick is you'll need to convert it to Dictionary.
Sample snippet as follow:
```
// let assume swiftyJSON is a SwiftyJSON object (JSON)
if let data = swiftyJSON.rawString()!.data(using: .utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
Alamofire.request(url, method: .post, parameters: json, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
}
} catch {
print("JSONSerialization error")
}
}
```

First add SwiftJSON to your project then
class func requestPOSTURL(serviceName:String,parameters: [String:Any]?, completionHandler: #escaping (JSON?, NSError?) -> ()) {
let headersSet: HTTPHeaders = [
"Authorization":GlobalAccesstoken,
"Accept": "application/json"
]
Alamofire.request(serviceName, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headersSet).responseJSON {
(response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
let json = JSON(data)
completionHandler(json,nil)
}
break
case .failure(_):
completionHandler(nil,response.result.error as NSError?)
break
}
}
}
AFWrapper.requestPOSTURL(serviceName: LapiUrl+"get_profile", parameters: params) { (response:JSON?, error:NSError?) in
if error != nil {
print(error!)
return
}
if response == nil {
return
}
print(response!)
var distRespoce = response!.dictionary?["response"]?.array?[0]
if (distRespoce?["status"].string == "true"){
let distuserData = distRespoce!.dictionary?["user_data"]
}
else{
print("no")
}
}
Try above code ..

You can do like this : -
Alamofire.request(urlString, method: .post, parameters: paramData, encoding:JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result)
{
case .success(_):
if response.result.value != nil
{
do
{
var dict : NSDictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(dict)
dict = UtilityClass.removeNullFromResponse(response: response.result.value! as! NSDictionary)
self.dataBlock(dict,nil)
}
catch
{
UtilityClass.hideHudLoading()
}
}
break
case .failure(_):
if response.result.error != nil
{
print(response.result.error!)
UtilityClass.hideHudLoading()
}
break
}
}
}

Simple Get post code, Easy to use, maintain and understand
Below is pod, you must need to use my code of json parsing.
#Network manager related
pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :tag => ‘4.0.1’
pod 'AlamofireNetworkActivityIndicator', '~> 2.0'
pod 'AlamofireObjectMapper', '~> 4.0.0'
pod 'SVProgressHUD', :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git'
pod 'Reachability', '~> 3.2'
pod 'SwiftyJSON', '~> 3.0.0'
pod 'ObjectMapper', '~> 2.0'
pod 'SDWebImage', '~> 3.8'
Here, You can Call API in your view controller.
RegistrationService().login(email: (txtEmail.text)!.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), password: self.txtPassword.text!, success: { (response) in
//Save data to user default
}) { (error) in
print(error as Any)
}
RegistrationService.swift //Service class, in which you can add api's
//
// RegistrationService.swift
// hotelBids
//
// Created by Mehul Parmar on 27/05/16.
// Copyright © 2017 Sooryen Innovation labs. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper
open class RegistrationService {
enum listOfApi : String {
case
login,
country
}
func country(_ success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
// create post request
NetworkManager().Get(listOfApi.country.rawValue,
paramaters: [:],
showLoader: true,
success: { responseObject in
success(responseObject)
}) { error in
failure(error)
}
}
func login(email: String, password: String, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
// create request parameter
let requestParameters = ["email" : email,
"password" : password,
"user_role" : "customer"
]
// create post request
NetworkManager().POST(listOfApi.login.rawValue,
paramaters: requestParameters as [String : AnyObject]?,
showLoader: true,
success: { responseObject in
success(responseObject)
}) { error in
failure(error)
}
}
NetworkManager.swift
//
// NetworkManager.swift
// Constants.kAppName.localized()
//
// Created by Mehul Parmar on 08/06/16.
// Copyright © 2016 . All rights reserved.
//
import Foundation
import Alamofire
import SVProgressHUD
import SwiftyJSON
//import AMSmoothAlert
import ObjectMapper
import AlamofireObjectMapper
//used for facebook logour while invalid session
import FacebookLogin
//MARK : - Errors
enum NetworkConnection {
case available
case notAvailable
}
class NetworkManager {
let baseUrlDev_OLD : String = "https://hotelbids.com/" + "dev/" + "hb-app/" + "v3/" + "user/"
let baseUrlDev : String = "http://184.73.131.211/api/v1/"
//MARK : - Shared Manager
let sharedManager = SessionManager()
func getHeaders(_ urlString: String) -> [String: String] {
var headerDictionary = [String: String]()
if UserDetail.rememberToken != nil {
if (UserDetail.rememberToken?.length)! > 0 {
headerDictionary[Constants.KEY_remember_token] = "\(UserDetail.rememberToken!)"
}
}
/*
if let xapi = UserDefault.getXapi() {
headerDictionary[Constants.KEY_Xapi] = xapi
}
if let accessLanguage = UserDefault.getLanguage() {
headerDictionary[Constants.KEY_Language] = accessLanguage
}
if let userId = UserDefault.getUserId() {
headerDictionary[Constants.KEY_USER_ID] = userId
}
if let accessToken = UserDefault.getAccessToken() {
headerDictionary[Constants.KEY_AccessToken] = accessToken
}*/
print("urlString: \(urlString)\nheaderDictionary : \(headerDictionary)")
return headerDictionary
}
func printResponse(urlString: String, paramaters: [String: AnyObject]?, response: AnyObject) {
let dictResponce = self.getValidatedData(response as AnyObject)
// if dictResponce.boolValue {
if let paramatersTemp = paramaters {
if paramatersTemp.values.count > 0 {
let jsonParameters = JSON(paramatersTemp)
print("\n\n\nurlString : \(urlString) ,\n\n paramaters: \(jsonParameters) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
else {
print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
}
else {
print("\n\n\nurlString : \(urlString) ,\n\n Response: \(String(describing: dictResponce))\n\n\n")
}
// } else {
// print("urlString : \(urlString) ,\n Response: \(String(describing: dictResponce))")
// }
}
func getValidatedData(_ response: AnyObject?) -> JSON {
//Removing null and <null>, and replacing number or integer to string
guard var dictResponse = response as? NSDictionary else{
return nil
}
dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
let jsonResponce = JSON(dictResponse)
return jsonResponce
}
// MARK: - Get Method
func Get(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
switch checkInternetConnection() {
case .available:
if let showLoader = showLoader {
if showLoader {
DispatchQueue.main.async {
// update some UI
UIApplication.shared.keyWindow?.showLoader()
}
}
}
Alamofire.request(baseUrlDev.add(urlString: urlString), method: .get, parameters: paramaters, encoding: URLEncoding.default, headers: self.getHeaders(urlString)).responseJSON (completionHandler: { response in
DispatchQueue.main.async {
if UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.endIgnoringInteractionEvents()
}
if let showLoader = showLoader {
if showLoader {
if SVProgressHUD.isVisible() {
SVProgressHUD.dismiss()
}
}
}
}
//Success
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
//Print response using below method
self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
else {
//Check response error using status code
if let strErrorReasonCode : Int = response.response?.statusCode {
if let data = response.data {
let jsonResponce = JSON(data: data)
if strErrorReasonCode == 500 {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
return
}
if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let Alamofire_Error = -1005
if authentication_Errors == strErrorReasonCode {
print("\n\n\n\nauthentication_Errors :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
self.isUnAuthotized()
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(strErrorReasonCode) {
print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
CustomAlert().ShowAlert(responce.message)
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(Alamofire_Error) {
self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
}, failure: {_ in
failure(jsonResponce)
})
}
}
else {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
}
}
}
else {
failure(nil)
}
}
})
case .notAvailable:
if let _ = showLoader {
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
}
failure(JSON(AppAlertMsg.kNoInternet))
print("No internet")
}
}
// MARK: - POST Method
func POST(_ urlString: String, paramaters: [String: AnyObject]? = nil, showLoader: Bool? = nil, success:#escaping (_ responseObject:JSON) -> Void , failure:#escaping (_ errorResponse:JSON?) -> Void) {
switch checkInternetConnection() {
case .available:
if let showLoader = showLoader {
if showLoader {
DispatchQueue.main.async(execute: {
if !UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.beginIgnoringInteractionEvents()
}
SVProgressHUD.show(withStatus: AppAlertMsg.kPleaseWait)
})
}
}
sharedManager.request(baseUrlDev.add(urlString: urlString), method: .post, parameters: paramaters, encoding: JSONEncoding.default, headers: self.getHeaders(urlString)).validate().responseJSON(completionHandler: { response in
DispatchQueue.main.async {
if UIApplication.shared.isIgnoringInteractionEvents {
UIApplication.shared.endIgnoringInteractionEvents()
}
if let showLoader = showLoader {
if showLoader {
if SVProgressHUD.isVisible() {
SVProgressHUD.dismiss()
}
}
}
}
//Success
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
//Print response using below method
self.printResponse(urlString: urlString, paramaters: paramaters, response: (value as AnyObject))
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
} else {
//Check response error using status code
if let strErrorReasonCode : Int = response.response?.statusCode {
if let data = response.data {
let jsonResponce = JSON(data: data)
if strErrorReasonCode == 500 {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
return
}
if let dictionary : NSDictionary = jsonResponce.dictionaryObject as NSDictionary? {
let responce : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictionary)
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let Alamofire_Error = -1005
if authentication_Errors == strErrorReasonCode {
print("\n\n\n\nauthentication_Errors (jsonResponce)\n\n\n\n")
self.isUnAuthotized()
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(strErrorReasonCode) {
print("\n\n\n\nauthentication_Errors_Range :\(strErrorReasonCode) \n\nmessage: \(responce.message) \n\nparamaters: \(String(describing: paramaters)) \n\nresponse: \(jsonResponce)\n\n\n\n")
CustomAlert().ShowAlert(responce.message)
failure(jsonResponce)
}
else if authentication_Errors_Range.contains(Alamofire_Error) {
self.POST(urlString, paramaters: paramaters, showLoader: showLoader, success: { (responseObject) in
if response.result.isSuccess {
if let value = response.result.value {
let dictResponce = self.isValidated(value as AnyObject)
if dictResponce.0 == true {
success(dictResponce.1)
}
else {
failure(dictResponce.1)
}
}
}
}, failure: {_ in
failure(jsonResponce)
})
}
}
else {
print("\n\n\n\n server error :\(AppAlertMsg.kErrorMsg) \n\n URL:\(urlString) \n\n paramaters:\(JSON(paramaters as Any))\n\n\n\n")
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kErrorMsg, duration: 3.0, position: "bottom" as AnyObject)
failure(jsonResponce)
}
}
}
else {
failure(nil)
}
}
})
case .notAvailable:
if let _ = showLoader {
UIApplication.shared.keyWindow?.makeToast(message: AppAlertMsg.kNoInternet, duration: 3.0, position: "bottom" as AnyObject)
}
failure(JSON(AppAlertMsg.kNoInternet))
print("No internet")
}
}
// MARK: - No Internet Connection
func checkInternetConnection() -> NetworkConnection {
if isNetworkAvailable() {
return .available
}
return .notAvailable
}
// MARK: - Check Status
func isValidated(_ response: AnyObject?) -> (Bool, JSON) {
//Removing null and <null>, and replacing number or integer to string
guard var dictResponse = response as? NSDictionary else{
return (false,nil)
}
dictResponse = (dictResponse.replacingNullsWithStrings() as NSDictionary).convertingNumbersToStrings()! as NSDictionary
let jsonResponce = JSON(dictResponse)
let responseModel : ResponseDataModel = ModelManager.sharedInstance.getResponseDataModel(dictResponse)
/* //
HTTP Status Code
200 – Success/OK
4xx – Authentication Errors
5xx – Service Errors
*/ //
guard let statusCodeInt = responseModel.code.toInt() else {
print("code is not proper")
return (false,jsonResponce)
}
let success_Range = 200..<300
let authentication_Errors = 401
let authentication_Errors_Range = 400..<500
let service_Errors_Range = 500..<600
if success_Range.contains(statusCodeInt) {
// all okey
return (true, jsonResponce)
}
else if authentication_Errors == statusCodeInt {
print("service_Errors_Range :\(statusCodeInt)")
self.isUnAuthotized()
return (false,jsonResponce)
}
else if authentication_Errors_Range.contains(statusCodeInt) {
print("authentication_Errors_Range :\(statusCodeInt)")
CustomAlert().ShowAlert(responseModel.message)
return (false,jsonResponce)
}
else if service_Errors_Range.contains(statusCodeInt) {
print("service_Errors_Range :\(statusCodeInt)")
CustomAlert().ShowAlert(responseModel.message)
return (false,jsonResponce)
}
else {
return (false,nil)
}
}
func isUnAuthotized() {
// we have to logout, bcos session expired , or user unauthorized
CustomAlert().ShowAlert(isCancelButton: false, strMessage: AppAlertMsg.kUnAuthotized) { (isYESClicked) in
if isYESClicked {
//Delete all data from user default
//Set sign in as Home screen
print("set to Login view controller ")
GmailClass.sharedInstance().signOut()
LoginManager().logOut()
UserStatus = UserType.Fresh.rawValue
let deviceTokenTemp = DeviceToken
if let bundle = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundle)
}
DeviceToken = deviceTokenTemp
Constants.appDelegate.logoutSuccess()
}
}
}
// MARK: - Loader method
class func ShowActivityIndicatorInStatusBar() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
class func HideActivityIndicatorInStatusBar() {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
extension String {
func add(urlString: String) -> URL {
return URL(string: self + urlString)!
}
func EncodingText() -> Data {
return self.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}
}

Related

iOS - Alamofire RequestRetrier not provoked

I am trying to implement a retry mechanism and i saw that alamofire has one.
I am trying to implement a simple mechanism of retry with number of times for a request , yet something is wrong.
class OAuth2Handler: RequestAdapter, RequestRetrier {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
return urlRequest
}
var defaultRetryCount = 4
private var requestsAndRetryCounts: [(Request, Int)] = []
private var lock = NSLock()
private func index(request: Request) -> Int? {
return requestsAndRetryCounts.index(where: { $0.0 === request })
}
func addRetryInfo(request: Request, retryCount: Int? = nil) {
lock.lock() ; defer { lock.unlock() }
guard index(request: request) == nil else { print("ERROR addRetryInfo called for already tracked request"); return }
requestsAndRetryCounts.append((request, retryCount ?? defaultRetryCount))
}
func deleteRetryInfo(request: Request) {
lock.lock() ; defer { lock.unlock() }
guard let index = index(request: request) else { print("ERROR deleteRetryInfo called for not tracked request"); return }
requestsAndRetryCounts.remove(at: index)
}
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: #escaping RequestRetryCompletion){
lock.lock() ; defer { lock.unlock() }
guard let index = index(request: request) else { completion(false, 0); return }
let (request, retryCount) = requestsAndRetryCounts[index]
if retryCount == 0 {
completion(false, 0)
} else {
requestsAndRetryCounts[index] = (request, retryCount - 1)
completion(true, 0.5)
}
}
}
this is the class that i am trying to use this:
let sessionManager = SessionManager()
override init() {
sessionManager.adapter = RequestAdapter.self as? RequestAdapter
sessionManager.retrier = OAuth2Handler()
}
func sendRequest(url: String,meth: HTTPMethod,parameters: [String: AnyObject]?, success: #escaping (String, Data) -> Void, failure: #escaping (Error) -> Void) {
self.asyncSerialWorker.enqueueWork { (done) in
self.sessionManager.request(url, method:meth).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
print("Generic succsess")
let value = responseObject.result.value
let json = JSON(value!)
guard let result = responseObject.data else {return}
success(self.parser.parseMaiden(json: json), result)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
print("login failed")
failure(error)
}
done()
}
}
}
if there are any other suggestions i would love to hear them
thanks
sessionManager.adapter = RequestAdapter.self as? RequestAdapter seems very wrong. You should be setting it to an instance of your OAuth2Handler.
So the issue her was to add the request to the retry, so first i did this:
let sessionManager = SessionManager()
var retrier = OAuth2Handler()
override init() {
sessionManager.retrier = retrier
}
and in the call itself i did as follow:
func sendRequest(url: String,meth: HTTPMethod,parameters: [String: AnyObject]?, success: #escaping (String, Data) -> Void, failure: #escaping (Error) -> Void) {
let request = sessionManager.request(url, method: meth, parameters: parameters, encoding: JSONEncoding.default)
retrier.addRetryInfo(request: request)
self.asyncSerialWorker.enqueueWork { (done) in
self.sessionManager.request(url, method:meth).responseJSON { (responseObject) -> Void in
if responseObject.result.isSuccess {
print("Generic succsess")
let value = responseObject.result.value
let json = JSON(value!)
guard let result = responseObject.data else {return}
success(self.parser.parseMaiden(json: json), result)
}
if responseObject.result.isFailure {
let error : Error = responseObject.result.error!
print("login failed")
failure(error)
}
done()
}
}
}
as you can see i have add to the retry a request :
retrier.addRetryInfo(request: request)
maybe i should do a remove in success(will check and update)

Record audio and send it to server in Swift 3

I have recorded audio with iOS successfully, but the problem is that I cannot send audio to server. Code that I tried is as shown below.
let audioData : NSData = try Data(contentsOf: (audioRecorder?.url)!) as NSData
var finalurl = url+Access_Token!
let params = [
"name":"iosTest.mp3",
"file": audioData] as [String : Any]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30000
manager.request(finalurl, method: .post, parameters: params).responseJSON {
response in
stopActivityIndicator()
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
let ResponseSuccess = JSON.object(forKey: "response")!
displayAlertMessage(userMessage: ResponseSuccess as! String, myView: self)
}
}
} catch let error as NSError {
print("audioPlayer error: \(error.localizedDescription)")
displayAlertMessage(userMessage: "Something error Occured! Please try again" as! String, myView: self)
}
Have you tried this from their official documentation on GitHub? Uploading Multipart Form Data
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(audioRecorder?.url, withName: "iosTest.mp3")
},
to: "https://yourLinkGoesHere",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)
or this Uploading a File
Alamofire.upload(audioRecorder?.url, to: "https://yourLinkGoesHere").responseJSON { response in
debugPrint(response)
}
SWIFT 5, Alamofire 5.
File with the request and completion #escaping :
import Alamofire
import SwiftyJSON
func request(variable1: String?, variable2: String?, audioFilePath: URL, completion: #escaping (String) -> ()) {
let url = URL(string: "https://...")!
let headers: HTTPHeaders = [
"content-type": "multipart/form-data; boundary=---011000010111000001101001",
"accept": "application/json",
"authorization": "Bearer \(your_token_if_needed)"
]
var parameters: [String: Any] = [:]
if variable1 != nil { parameters["var1"] = variable1 }
if variable2 != nil { parameters["var2"] = variable2 }
// Let's check the data
print(parameters)
AF.upload(multipartFormData: { multipartFormData in
for (key,value) in parameters {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
multipartFormData.append(audioFilePath, withName: "audio.m4a")
}, to: url, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
do{
let json = try JSON(data: response.data!)
print(json)
// Parse an Array
let statusJson = json["status"].string
if statusJson == "success" {
completion("success")
}
else
{ completion(jsonErrorMsg!) }
} catch {
print(error.localizedDescription)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
}
}
Your ViewController class (Where you want to record the audio file)
// 1 - Delegation
class ViewController: UIViewController, AVAudioRecorderDelegate {
// 2 - Variables
var audioRecorder: AVAudioRecorder!
var audioFilename: URL!
var meterTimer:Timer!
var isAudioRecordingGranted: Bool!
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - permission
switch AVAudioSession.sharedInstance().recordPermission {
case AVAudioSessionRecordPermission.granted:
isAudioRecordingGranted = true
audioRecorderAction()
break
case AVAudioSessionRecordPermission.denied:
isAudioRecordingGranted = false
break
case AVAudioSessionRecordPermission.undetermined:
AVAudioSession.sharedInstance().requestRecordPermission() { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
self.isAudioRecordingGranted = true
self.audioRecorderAction()
} else {
self.isAudioRecordingGranted = false
}
}
}
break
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
audioRecorder = nil
}
func audioRecorderAction(){
if isAudioRecordingGranted {
//Create the session.
let session = AVAudioSession.sharedInstance()
do {
//Configure the session for recording and playback.
try session.setCategory(.playAndRecord, mode: .default, options: [])
try session.setActive(true)
//Set up a session
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue
]
//file name URL
audioFilename = getDocumentsDirectory().appendingPathComponent("audio.m4a")
//Create the audio recording, and assign ourselves as the delegate
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.record()
meterTimer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector:#selector(self.updateAudioTimer(timer:)), userInfo: nil, repeats: true)
}
catch let error {
print("Error for audio record: \(error.localizedDescription)")
}
}
}
func finishAudioRecording(success: Bool) {
audioRecorder.stop()
audioRecorder = nil
meterTimer.invalidate()
if success {
print("Finished.")
} else {
print("Failed :(")
}
}
#objc func updateAudioTimer(timer: Timer) {
if audioRecorder.isRecording {
let min = Int(audioRecorder.currentTime / 60)
let sec = Int(audioRecorder.currentTime.truncatingRemainder(dividingBy: 60))
let totalTimeString = String(format: "%02d:%02d", min, sec)
recordingTimeLabel.text = totalTimeString
audioRecorder.updateMeters()
if (sec == 10) {
finishAudioRecording(success: true)
}
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
//MARK:- Audio recoder delegate methods
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
finishAudioRecording(success: false)
request(variable1: var_to_send1, variable2: var_to_send2, audioFilePath: audioFilename, completion: { (response) -> Void in
if response == "success" {
print("success")
} else {
print("error")
}
})
}
}

POST Json to API with Alamofire?

I want to post a JSON object I create in my service class and pass to the networkService.
This is my network service, but i get an error of
Value of type '[String : Any]' has no member 'data'
on the line: let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
func request(json: [String:Any]) {
let url = URL(string: urlString)!
let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
}
The idea being I pass in my JSON when i call the func via the func parameter.
This is the JSON object passed in:
func loginUser(data: Array<String>, deviceToken: String) {
// create JSON
let json = [ "login-email" : data[0],
"login-password" : data[1],
"login-secret" : "8A145C555C43FBA5",
"devicetoken" : deviceToken
]
networkManager.request(json: json)
}
Then I convert and send it to the API (urlString)
Any idea if/why this isnt working?
THanks
Updated revision:
func request(json: [String:Any]) {
let url = URL(string: urlString)!
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options:[])
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
} catch {
print("Failed to serialise and send JSON")
}
}
update: added my code to make a call with completion question:
func sendLoginRequest() {
let userLogin = UserService.init(loginEmail: userEmail, loginPassword: userPassword, loginSecret: loginSecret, deviceToken: deviceToken)
networkService.logUserIn(request: userLogin) { (<#JSON?#>, <#NSError?#>) in
<#code#>
}
}
edit: Updated Payload Shot:
edit 2: mapping issue example:
init?(_ json: JSON) {
// Map API Key from top level
guard let apiKey = json["apikey"].string else { return nil }
// Map User at user level
guard let userDataArray = json["user"].array else {
fatalError("user data array NOT FOUND")
}
print("USER DATA IS \(userDataArray)")
// assign user
for child in userDataArray {
guard let userID = child["id"].int,
let userEmail = child["email"].string,
let lastName = child["lastname"].string,
let firstName = child["firstname"].string,
let company = child["company"].string,
let userImage = child["image"].string,
let jobTitle = child["jobtitle"].string
else { return nil
}
}
// Assign to model properties
self.apiKey = apiKey
self.userEmail = userEmail
self.lastName = lastName
self.firstName = firstName
self.company = company
self.userImage = userImage
self.jobTitle = jobTitle
self.userID = userID
}
I just show how I work with this.
You don't have to convert your parameters to JSON. It's code from Alamofire.
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
Use this method instead of your:
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
Try this:
Instead of your request.httpBody = jsonData you can pass your json in parameters.
Your whole code will be:
func request(json: [String:Any]) {
Alamofire.request(urlString, method: .post, parameters: json, encoding: JSONEncoding.default).responseJSON {
(response) in
print(response)
}
}
If you are interested in my approach:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
let parameters = request.converToParameters()
Alamofire.request(Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
Request:
struct MakePickRequest: GeneralRequest {
let eventId: Int64
let sportId: String
let pickType: PickType
let betType: BetType
let amount: Int
func converToParameters() -> [String : String] {
return ["event_id": String(eventId), "sport_id": sportId,
"pick_type": pickType.rawValue, "bet_type": betType.rawValue,
"amount": String(amount)]
}
}
Structure with endpoints:
struct Endpoints {
// Development baseURL
static let baseURL = "http://myurl/"
private static let apiVersion = "api/v1/"
static var fullPath: String {
return "\(baseURL)\(apiVersion)"
}
// MARK: - User endpoints (POST)
static var login: String {
return "\(fullPath)users/login"
}
static var signUp: String {
return "\(fullPath)users/signup"
}
...
}
Outside of any class (but import SwiftyJSON is obligatory):
typealias APICompletionHandler = (_ data: JSON?, _ error: NSError?) -> Void
Handle response:
private func handleResponse(response: DataResponse<Any>, completionHandler: APICompletionHandler) {
self.printDebugInfo(response)
switch response.result {
case .success(let value):
self.handleJSON(data: value, handler: completionHandler)
case .failure(let error):
print(error)
completionHandler(nil, error as NSError?)
}
}
private func handleJSON(data: Any, handler: APICompletionHandler) {
let json = JSON(data)
let serverResponse = GeneralServerResponse(json)
if (serverResponse?.status == .ok) {
handler(serverResponse?.data, nil)
} else {
handler(nil, self.parseJsonWithErrors(json))
}
}
GeneralServerResponse (depends on your server API):
import SwiftyJSON
final class GeneralServerResponse {
let data: JSON
let status: Status
init?(_ json: JSON) {
guard let status = json["status"].int else {
return nil
}
self.status = Status(status)
self.data = json["data"]
}
enum Status {
case ok
case error
case unauthorized
init(_ input: Int) {
if input >= 200 && input < 400 {
self = .ok
} else if input == 403 {
self = .unauthorized
} else {
self = .error
}
}
}
}
My actual example of usage.
This is outside:
func +=<K, V> ( left: inout [K : V], right: [K : V]) { for (k, v) in right { left[k] = v } }
Example of request:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
var parameters = ["auth_token": Preferences.getAuthToken()]
parameters += request.converToParameters()
manager.apiRequest(url: Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
SessionManager extension to add headers for all requests:
extension SessionManager {
func apiRequest(url: URLConvertible, method: HTTPMethod, parameters: Parameters? = nil, encoding: ParameterEncoding, headers: HTTPHeaders? = nil) -> DataRequest {
var customHeaders: HTTPHeaders = ["api-key" : "1wFVerFztxzhgt"]
if let headers = headers {
customHeaders += headers
}
return request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
}
}
In APIManager class:
private let manager: SessionManager
init() {
manager = Alamofire.SessionManager.default
}
Call example:
apiClient.makePick(request: request) { data, error in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
// data is a JSON object, here you can parse it and create objects
}
}
Example of class:
import SwiftyJSON
final class MyClass {
let id: Int
let username: String
let parameter: Double
init?(_ json: JSON) {
guard let id = json["id"].int, let username = json["username"].string,
let parameter = json["parameter"].double else {
return nil
}
self.id = id
self.username = username
self.parameter = parameter
}
}

Alamofire 3->4 trouble with Reponse & ResponseSerializer Swift 3.0

I'm having trouble with the ResponseSerializer I get an unresolved identifier and for Response I get an undeclared type. I've read from alamofire migration doc that Response has been changed to multiple types. So I should change Response->DataReponse but this means I can only pass one argument like:
// What I have
Response(<ListWrapper, NSError>)
// What I should change it to?
DataResponse(<ListWrapper>)
How can I still recieve the Error this way and more importantly how do I migrate the extension to alamofire 4?
My class:
class List{
var idNumber: String?
var title: String?
var posterPath: String?
var release: String?
required init(json: JSON, id: Int?)
{
self.idNumber = json[ListFields.Id.rawValue].stringValue
self.title = json[ListFields.Title.rawValue].stringValue
self.posterPath = json[ListFields.PosterPath.rawValue].stringValue
self.release = json[ListFields.Release.rawValue].stringValue
}
class func setURL_APPEND(_ url: String)
{
URL_APPEND = url
}
// MARK: Endpoints
class func endpointForList() -> String
{
return URL_APPEND
}
fileprivate class func getListAtPath(_ path: String, completionHandler: #escaping (ListWrapper?, NSError?) -> Void) {
Alamofire.request(path)
.responseListArray { response in
if let error = response.result.error
{
completionHandler(nil, error)
return
}
completionHandler(response.result.value, nil)
}
}
class func getList(_ completionHandler: #escaping (ListWrapper?, NSError?) -> Void)
{
getListAtPath(List.endpointForList(), completionHandler: completionHandler)
}
}
// Problem is here:
// for ResponseSerializer I get an unresolved identifier
// and for Response I get an undeclared type
extension Alamofire.Request {
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper, NSError>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper, NSError> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
let failureReason = "Array could not be serialized because input data was nil."
let error = Alamofire.Error.errorWithCode(.dataSerializationFailed, failureReason: failureReason)
return .failure(error)
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
}
Bro try below code see:
func responseListArray(_ completionHandler: #escaping (Response<ListWrapper>) -> Void) -> Self {
let responseSerializer = ResponseSerializer<ListWrapper> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .success(let value):
let json = SwiftyJSON3.JSON(value)
let wrapper = ListWrapper()
var allList:Array = Array<List>()
wrapper.totalCount = json["favorite_count"].intValue
// print(json)
let results = json["items"]
// print(results)
for jsonList in results
{
//print(jsonList.1)
let list = List(json: jsonList.1, id: Int(jsonList.0) )
if (list.posterPath == "")
{
continue
}
else
{
//print(movies.posterPath)
allList.append(list)
}
}
wrapper.results = allList
return .success(wrapper)
case .failure(let error):
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}

Swift: Handling JSON with Alamofire & SwiftyJSON

This is sure to be asked several times, but I have not yet found the right answer, although I have been looking very hard.
I use Alamofire and SwiftyJSON and my JSON data looks like that:
{
"528" : {
"name" : "Name 1",
"id" : "528",
"product_id" : null,
"visible" : "0",
"level" : "2"
},
"29" : {
"name" : "Name 2",
"id" : "29",
"product_id" : null,
"visible" : "1",
"level" : "1"
},
"173" : {
"name" : "Name 3",
"id" : "173",
"product_id" : null,
"visible" : "0",
"level" : "2"
},
"143" : {
"name" : "Name 4",
"id" : "143",
"product_id" : null,
"visible" : "1",
"level" : "2"
},
...with this code:
Alamofire.request(.GET, dataURL, parameters: nil, encoding: .JSON)
.responseJSON { (request, response, jsonData, error) in
let json = JSON(jsonData!)
println(json)
}
...so everything should be fine with JSON
How can i access to that data? I mean how can i get names, ids, product_ids etc
How can i put that data (name) to my TableViewController?
I am using both SwiftyJSON and Alamofire in one of my projects. Here is how I am using it.
Create a protocol called APIProtocol.
Setup an API class with a GET method that accepts a delegate of type APIProtocol.
Setup TableViewController to implement the APIProtocol.
Call API.get() from TableViewController
Code
// Step 1
protocol APIProtocol {
func didReceiveResult(results: JSON)
}
// Step 2
func get(path: String, parameters: [String: AnyObject]? = nil, delegate: APIProtocol? = nil){
let url = "\(self.hostname)\(path)"
NSLog("Preparing for GET request to: \(url)")
Alamofire.request(.GET, url, parameters: parameters)
.responseJSON { (req, res, json, error) in
if(error != nil) {
NSLog("GET Error: \(error)")
println(res)
}
else {
var json = JSON(json!)
NSLog("GET Result: \(json)")
// Call delegate if it was passed into the call
if(delegate != nil) {
delegate!.didReceiveResult(json)
}
}
}
}
// Step 3
class ActivityViewController: UITableViewController, APIProtocol {
var activityModelList: NSMutableArray = [] // This is the array that my tableView is using.
...
func didReceiveResult(result: JSON) {
var activities: NSMutableArray = []
NSLog("Activity.didReceiveResult: \(result)")
for (index: String, activity: JSON) in result {
var activityModel = ActivityModel(
id: activity["id"].intValue,
message: activity["message"].stringValue
)
activities.addObject(activityModel)
}
// Set our array of new models
activityModelList = activities
// Make sure we are on the main thread, and update the UI.
dispatch_sync(dispatch_get_main_queue(), {
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
})
}
}
// Step 4
override func viewDidLoad() {
MyAPI.get("/activities", delegate: self)
}
The accessors (for SwiftyJSON at least) work like:
if let userName = json[0]["528"]["name"].string{
println(userName) // "Name 1"
}
More information on how to use SwiftyJSOn can be found here in its official documentation: https://github.com/SwiftyJSON/SwiftyJSON
Regarding how to put that data into a UITableView, there are many methods. Set up a UITableView cell and then load in the JSON data in some sort of array for instance.
Check this repo for an example that declare how to use Alamofire in your code and how to create models with swift and parsing JSON response
Install Alamofire in your project
Import Alamofire in your class
Define these variables in you class
typealias complitionBlock = (data: AnyObject) -> Void
let KBASE_URL: String = "http://static.westwing.de/cms/dont-delete/programming_task/data.json"
Set the implementation for this function
func getMainItems(complition block: complitionBlock) {
Alamofire.request(.GET, KBASE_URL, parameters:nil).responseJSON { response in
do {
let items = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions()) as! NSArray
let mutableArray: NSMutableArray = []
items.enumerateObjectsUsingBlock({ object, index, stop in
let str = object as! NSDictionary
//Replace WESItem with your model
//let item = WESItem(dictionary: str as NSDictionary)
mutableArray.addObject(item)
})
block(data: mutableArray)
} catch {
print(error)
}
}
}
For more information:
https://github.com/AhmedAskar/WestWing
Following should work for you :-
var nameArr = [String]()
Alamofire.request(.GET,"your url", parameters: nil)
.validate().responseJSON { response in
if let responseJson = response.result.value {
let name = responseJson["name"] as! String
nameArr.append(name)
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}// Alamofire Close
Use tableview as you normally use it i.e.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "cell")
}
cell!.textLabel?.text = nameArr[indexPath.row]
return cell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArr.count
}
Note: No need to use Swifty JSON as Alamofire allows JSON response which can be directly handled within ".responseJSON".
pod 'Alamofire' pod 'SwiftyJSON' pod 'ReachabilitySwift'
import UIKit import Alamofire import SwiftyJSON import SystemConfiguration
class WebServiceHelper: NSObject {
typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void
// MARK: - Internet Connectivity
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
// MARK: - Helper Methods
class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
print(strURL)
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL).responseJSON { (resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(resJson)
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
debugPrint(error)
failure(error)
}
}
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler){
if isConnectedToNetwork() {
if isShowLoader == true {
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess {
let resJson = JSON(resObj.result.value!)
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure {
let error : Error = resObj.result.error!
if isShowLoader == true {
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}
else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure :#escaping FailureHandler)
{
if isConnectedToNetwork()
{
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
let resJson = JSON(resObj.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
})
}else {
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : #escaping SuccessHandler, failure : #escaping FailureHandler)
{
if isConnectedToNetwork() {
if isShowLoader == true
{
AppDelegate.getDelegate().showLoader()
}
Alamofire.upload(
multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.append(imageData, withName: "Image.jpg")
}
for (key, value) in params! {
let data = value as! String
multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
print(multipartFormData)
}
},
to: strURL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
//let datastring = String(data: response, encoding: String.Encoding.utf8)
// print(datastring)
}
case .failure(let encodingError):
print(encodingError)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { (response) -> Void in
if response.result.isSuccess
{
let resJson = JSON(response.result.value!)
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
success(resJson)
}
if response.result.isFailure
{
let error : Error = response.result.error! as Error
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
failure(error)
}
}
case .failure(let encodingError):
if isShowLoader == true
{
AppDelegate.getDelegate().dismissLoader()
}
let error : NSError = encodingError as NSError
failure(error)
}
}
)
}
else
{
CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
}
==================================
Call Method
let aParams : [String : String] = ["DeviceIDString", "DeviceType" : "iOS", ]
WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in
if "\(responceObj["RespCode"])" != "1"
{
let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
else
{
let aParams : [String : String] = [
"Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
]
CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)
}
}, failure:
{ (error) in
CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
})
}
// fatch json data swiftjson with alamofire
// First in using Alamofire
// second in fatch json data in tableView
// create json model classmodel1
//model2

Resources