how to go on next viewController - ios

In my app i have tried to make different class for api calling. like click on login button and its call the method of different class. but when i want to go to another viewcontroller from that different class its getting crash.
here is my code in loginViewController
let mydata = DataControllerLogin()
mydata.login(txtemail.text!,password: txtPassword.text!)
class DataControllerLogin: UIViewController {
func login(username:String,password:String)
{
if Reachability.isConnectedToNetwork() == true
{
let url = "\(basicURL)login"
let param : [String : AnyObject] = [
"email" : username,
"password" : password
]
Alamofire.request(.POST, url, parameters: param, encoding: .JSON).responseObject(completionHandler: { (response:Response<LoginCode, NSError>) in
if (response.result.value != nil)
{
let LoginCode = response.result.value
let message = LoginCode?.Message
let detail = LoginCode?.result
if (LoginCode?.Status == 1)
{
let controller : LoginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.navigationController?.pushViewController(controller, animated: true)
SVProgressHUD.dismiss()
}
else
{
alertViewShow(self, title: "Sorry", message: message!)
SVProgressHUD.dismiss()
}
if let threedayForecast = LoginCode?.result {
print(threedayForecast.FirstName)
}
}
else
{
}
})
}
else {
alertViewShow(self, title: "No Internet Connection", message: "Make sure your device is connected to the internet.")
}
}
}
but its getting crash on line wherever i have define viewController.
let controller : LoginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
self.navigationController?.pushViewController(controller, animated: true)
its showing error like
exc_bad_instruction (code=exc_i386_invop subcode=0x0)
so if you know please let me know what is the issue?

Write this at the top of the file.
import UIKit
import Alamofire
import SwiftyJSON
typealias SOAPICompletionHandler = (code:Int, error:NSError?, response:NSDictionary?) -> Void
Add below method in your file:-
func callApi(strApiName:String, param : [String : AnyObject]?, type:String, header:[String : String]?, completionHandler:SOAPICompletionHandler) {
//let strURL : String = BASEURL+"/"+strApiName
let strURL = strApiName;
if type == POSTREQ {
Alamofire.request(.POST, strURL, parameters: param, encoding: .JSON, headers: header).responseJSON(completionHandler: { (responseData) -> Void in
let isSuccess = JSON(responseData.result.isSuccess)
if isSuccess {
// let swiftyJson = JSON(responseData.result.value! as! NSDictionary) as! AnyObject
completionHandler(code: 1, error: nil, response: responseData.result.value! as? NSDictionary)
} else {
let error = responseData.result.error! as NSError
completionHandler(code: 0, error: error, response: nil)
}
})
} else if type == GETREQ {
Alamofire.request(.GET, strURL, parameters: param, encoding: .JSON, headers: header).responseJSON(completionHandler: { (responseData) -> Void in
let isSuccess = JSON(responseData.result.isSuccess)
if isSuccess {
// let swiftyJson = JSON(responseData.result.value! as! NSDictionary)
completionHandler(code: 1, error: nil, response: responseData.result.value! as? NSDictionary)
} else {
let error = responseData.result.error! as NSError
completionHandler(code: 0, error: error, response: nil)
}
})
} else if type == PUTREQ{
Alamofire.request(.PUT, strURL, parameters: param, encoding: .JSON, headers: header).responseJSON(completionHandler: { (responseData) -> Void in
let isSuccess = JSON(responseData.result.isSuccess)
if isSuccess {
// let swiftyJson = JSON(responseData.result.value! as! NSDictionary)
completionHandler(code: 1, error: nil, response: responseData.result.value! as? NSDictionary)
} else {
let error = responseData.result.error! as NSError
completionHandler(code: 0, error: error, response: nil)
}
})
} else if type == DELETEREQ{
Alamofire.request(.DELETE, strURL, parameters: param, encoding: .JSON, headers: header).responseJSON(completionHandler: { (responseData) -> Void in
let isSuccess = JSON(responseData.result.isSuccess)
if isSuccess {
// let swiftyJson = JSON(responseData.result.value! as! NSDictionary)
completionHandler(code: 1, error: nil, response: responseData.result.value! as? NSDictionary)
} else {
let error = responseData.result.error! as NSError
completionHandler(code: 0, error: error, response: nil)
}
})
}
else if type == PATCHREQ{
Alamofire.request(.PATCH, strURL, parameters: param, encoding: .JSON, headers: header).responseJSON(completionHandler: { (responseData) -> Void in
let isSuccess = JSON(responseData.result.isSuccess)
if isSuccess {
// let swiftyJson = JSON(responseData.result.value! as! NSDictionary)
completionHandler(code: 1, error: nil, response: responseData.result.value! as? NSDictionary)
} else {
let error = responseData.result.error! as NSError
completionHandler(code: 0, error: error, response: nil)
}
})
}
}
you need to add Alamofire and SwiftyJSON.
Hope for best.

Related

Alamofire request is not executed in swift 5

I have been using Alamofire in my whole project. Now in one of my modules, the Alamofire.request() is not getting executed. I tried putting a breakpoint and it showed that all of a sudden the request is being skipped. As I am working on a live project for security purpose am not including the URL. The code which I used is given here.
func responseFunction() {
let url = ""
let parametervalue = ["enq_id" : self.enquiry_id]
print(self.enquiry_id)
Alamofire.request(url, method: .post, parameters: parametervalue).responseJSON(completionHandler: {response in
if let response_data = response.result.value as? NSDictionary{
let rdata = response_data.value(forKey: "response") as! String
if rdata == "Success"
{
let res_data = response_data.value(forKey: "result") as! [NSDictionary]
print(res_data)
for resultdata in res_data{
let enqid = resultdata.value(forKey: "enq_id") as! String
let userid = resultdata.value(forKey: "user_id") as! String
let reference_no = resultdata.value(forKey: "reference_no") as! String
let enq_date = resultdata.value(forKey: "enq_date") as! String
let enq_time1 = resultdata.value(forKey: "enq_time") as! String
let enq_time2 = enq_time1.replacingOccurrences(of: "+", with: " ")
let enq_time = enq_time2.replacingOccurrences(of: "%3A", with: " : ")
}
self.queryResponseTable.reloadData()
}
else{
let alertController = UIAlertController(title: "Response Details", message: "Server Error ! Could not get any response. Please try again later!", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default))
self.present(alertController, animated: true, completion: nil)
}
}
})
}
Can anyone help me out?
I think the below code helps you.
func Api_withParameters(aView : UIView, aWebServiceName : String, aDictParam : Dictionary<String, Any>, completeBlock: #escaping ( _ response: AnyObject) -> Void, errorBlock: #escaping ( _ error: AnyObject) -> Void) {
let passingURL = "\(BASEURL)/\(aWebServiceName)"
let jsonData = try? JSONSerialization.data(withJSONObject: aDictParam, options: [])
var jsonString = String(data: jsonData!, encoding: .utf8)
jsonString = jsonString!.filter { !"\\)(\n\t\r".contains($0) }
let passingParameter = [K_APIKEY:APIKEY, K_Data:jsonString!]
print("***** Web-Service URL : \(passingURL) \n Passing Parameter : \(passingParameter)")
Alamofire.request(passingURL, method: HTTPMethod.post, parameters: passingParameter, encoding: URLEncoding.default, headers: HEADER_CONTENT_TYPE).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
completeBlock(response.result.value as AnyObject)
break
case .failure(let error):
var errorDict = [String : Any]()
let errorcode : Int = error._code
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 404:
errorDict = ["errormsg" : "Invalid URL: \(passingURL)", "errorCode" : httpStatusCode]
default: break
}
} else {
if (String(errorcode) == "-1009"){
errorDict = ["errormsg" : "Please check your internet connection"]
}
else if(error.localizedDescription != ""){
errorDict = ["errormsg" : error.localizedDescription]
}
else{
errorDict = ["errormsg" : "Server unreachable please try again later."]
}
}
errorBlock(errorDict as AnyObject)
break
}
}
}

How Can i get Charge and how to pass token id to charge in swift (IOS)

How to generate stripe token id, charge id in swift. Please, could anyone help on the generation of stripe payment in swift?
First do stripe payment configuration
let configuration = STPPaymentConfiguration.shared()
configuration.additionalPaymentMethods = .all
configuration.appleMerchantIdentifier = "Your stripe identifier"
configuration.canDeletePaymentMethods = true
configuration.createCardSources = false
let customerContext = STPCustomerContext(keyProvider: MyAPIClient.sharedClient)
paymentMethodViewController = STPPaymentMethodsViewController(configuration: configuration,
theme: STPTheme.init(),
customerContext: customerContext,
delegate: self)
self.navigationController?.pushViewController(controller, animated: true)
Code For ApiClient to generate ephermal key
class MyAPIClient: NSObject, STPEphemeralKeyProvider {
static let sharedClient = MyAPIClient()
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
let url = AppConstant.Server.EPHERMAL_KEY
let user = UserDefaultManager.shared.readUser()
let header: HTTPHeaders = ["api_token": user.apiToken ?? "",
"Content-Type": "application/json"]
Alamofire.request(url,
method: .get,
parameters: [
"api_version": apiVersion,
"id": user.id ?? -1
],
headers: header)
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
completion(json as? [String: AnyObject], nil)
case .failure(let error):
completion(nil, error)
}
}
}
}
Then in delegate method
func paymentMethodsViewController(_ paymentMethodsViewController: STPPaymentMethodsViewController, didSelect paymentMethod: STPPaymentMethod) {
var paymentStripeId: String?
if let source = paymentMethod as? STPSource {
paymentStripeId = source.stripeID
} else if let card = paymentMethod as? STPCard {
self.stpCard = card
}
}
Try out this method. From stripe document.
let cardParams = STPCardParams()
cardParams.number = "4242424242424242"
cardParams.expMonth = 10
cardParams.expYear = 2021
cardParams.cvc = "123"
STPAPIClient.shared().createToken(withCard: cardParams) { (token: STPToken?, error: Error?) in
guard let token = token, error == nil else {
// Present error to user...
return
}
submitTokenToBackend(token, completion: { (error: Error?) in
if let error = error {
// Present error to user...
}
else {
// Continue with payment...
}
})
}

How to post SwiftyJSON with Alamofire?

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)!
}
}

Can't make multiple FBSDKGraphRequests

I'm trying to read the posts from a Facebook page using the following code:
class FacebookGraphAPI {
class func getPosts(fromPageWithID pageId: String, parameters: [String: AnyObject]?, completion: #escaping ([FacebookPost]?, Error?) -> Void) {
self.getAccessToken { (accessToken, error) in
if error != nil {
completion(nil, error)
return
}
let params = ["access_token": accessToken, "fields": "created_time,message,story"]
if let request = FBSDKGraphRequest(graphPath: "\(pageId)/posts", parameters: params) {
request.start { (connection, result, error) in
if error != nil {
completion(nil, error)
return
}
guard let resultDict = result as? [String: AnyObject],
let data = resultDict["data"] as? NSArray
else {
completion(nil, nil)
return
}
var posts = [FacebookPost]()
for item in data {
posts.append(FacebookPost(dict: item as! NSDictionary))
}
completion(posts, nil)
}
}
completion(nil, nil)
}
}
class func getAccessToken(completion: #escaping (String?, Error?) -> Void) {
let clientId = Bundle.main.object(forInfoDictionaryKey: "FacebookAppID") as! String
let clientSecret = Bundle.main.object(forInfoDictionaryKey: "FacebookAppSecret") as! String
let params = ["client_id": clientId, "client_secret": clientSecret, "grant_type": "client_credentials", "fields": "access_token"]
if let request = FBSDKGraphRequest(graphPath: "oauth/access_token", parameters: params) {
request.start(completionHandler: { (connection, result, error) in
if error != nil {
completion(nil, error)
return
}
guard let resultDict = result as? [String: AnyObject] else {
completion(nil, nil)
return
}
let accessToken = resultDict["access_token"] as! String
completion(accessToken, nil)
})
}
}
}
Which I then call using e.g. the following:
FacebookGraphAPI.getPosts(fromPageWithID: "{page-id}", parameters: ["limit": 5 as AnyObject]) { (posts, error) in
guard error == nil else { return }
...
}
The error I'm getting is: -[_SwiftValue length]: unrecognized selector sent to instance on the second FBSDKGraphRequest start.
I tried removing the first FBSDKGraphRequest and then I at least get a response in the completionHandler. It almost seams as if I can't make more than one FBSDKGraphRequest.
Any help is greatly appreciated.
Thanks in advance!
I finally managed to find the issue, when thinking about the error and remembering that the FBSDKCoreKit framework was written in Objective-C.
All I needed to do was cast accessToken inside the parameters array to an NSString.
I changed the following:
let params = ["access_token": accessToken, "fields": "created_time,message,story"]
To:
let params = ["access_token": accessToken! as NSString, "fields": "created_time,message,story"]

Alamofire POST dictionary with row data

Hi everyone I am currently using Swift 2.2 and Alamofire and I am doing a post/form request using a json. Here is the my current code:
func authenticateUserWithValues(passCode : String, userID : String, completion: (result: Bool, user : User?, message : String) -> Void) {
let urlString = NSString(format:"%#%#", kBaseURL, kCheckAuthenticationCodeURL) as String
let parameters: [String: String] = [ "code" : passCode,
"user_id": userID,
"application_type" : "2"]
Alamofire.request(.POST, urlString, parameters: parameters, encoding: .JSON)
.responseJSON { (response) in
switch response.result {
case .Failure(let error):
print(error)
if (error.code == -1009) {
completion(result: false, user: nil, message : kString_No_Internet_Connection)
}else{
completion(result: false, user: nil, message: kString_Unexpected_Error_Occured)
}
case .Success(let responseObject):
let response = responseObject as? [String:String]
var status : String = ""
var message : String = ""
if(response!["status"] != nil){
status = response!["status"]!
}
if(response!["message"] != nil){
message = response!["message"]!
}
if (status == "OK"){
let user : User = RealmManager().addUser(response!)
completion(result: true, user: user, message: message)
}else{
completion(result: false, user: nil, message: message)
}
print(responseObject)
}
}
}
Bu I need to change it to accept a raw body request of the same Dictionary.
Here is the post request in raw format using Swift 2.2:
func authenticateUserWithValues(passCode : String, userID : String, completion: (result: Bool, user : User?, message : String) -> Void) {
let urlString = NSString(format:"%#%#", kBaseURL, kCheckAuthenticationCodeURL) as String
let url:NSURL = NSURL(string: urlString)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "{\"code\" : \"\(passCode)\", \"user_id\" : \"\(userID)\", \"application_type\" : \"2\"}"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
if (error!.code == -1009) {
completion(result: false, user: nil, message : kString_No_Internet_Connection)
}else{
completion(result: false, user: nil, message: kString_Unexpected_Error_Occured)
}
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
var status : String = ""
var message : String = ""
if(json["status"] != nil){
status = json["status"]! as! String
}
if(json["message"] != nil){
message = json["message"]! as! String
}
if (status == "OK"){
RealmManager().removerAllUsers()
RealmManager().addUser(json)
let user : User = RealmManager().getCurrentUser()!
completion(result: true, user: user, message: message)
}else{
completion(result: false, user: nil, message: message)
}
} catch let error as NSError {
completion(result: false, user: nil, message: error.localizedDescription)
}
}
task.resume()
}

Resources