Alamofire POST dictionary with row data - ios

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

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

Cannot figure out why Error is always turning out to be 'nil'

I am creating an Event Manager App, It requires to input valid Event Code to check the Event Details. I am working on the Sign in page where in the user will input the event code. When the page is error free, I tried to clean, build and run the app, insert breakpoints to check the executions of my codes. But seems that I am encountering an issue, where in, whether I input valid code or not, It just loaded and after it loads, It goes back to a clear textfield, no error alerts or not event dispatch the Dashboard Page. I really can't figure out what's wrong with my codes. I am new in swift. I really need hep to fix it. Below are my codes for your reference and image of eventDetails from breakpoint. Thankyou
APIService.swift
typealias JSONDictionary = Dictionary<String, AnyObject>
class APIService: NSObject, URLSessionDataDelegate {
enum Path {
case SubmitEventCode
}
typealias APICallback = ((AnyObject?, NSError?) -> ())
let responseData = NSMutableData()
var statusCode: Int = -1
var callback: APICallback! = nil
var path: Path! = nil
func validatePasscode(eventcode: String!, callback: #escaping APICallback)
{
let url = PASSCODE_CHECKER_URL //https://hopprLab.com/API/events/PasscodeChecker
makeHTTPPostRequest(path: Path.SubmitEventCode, callback: callback, url: url)
}
func connection(_ connection: URLSession, didReceive response: URLResponse){
let httpResponse = response as! HTTPURLResponse
statusCode = httpResponse.statusCode
switch (httpResponse.statusCode) {
case 201, 200, 401:
self.responseData.length = 0
default:
print("ignore")
}
}
func connection(_ connection: URLSession, didReceive data: Data) {
self.responseData.append(data)
}
func connectionDidFinishLoading(_ connection: URLSession) {
let error: NSError? = nil
let json = try? JSONSerialization.jsonObject( with: responseData as Data, options:[]) as AnyObject
if ((data) != nil) {
callback(nil, error)
return
}
switch(statusCode, self.path!) {
case(200, Path.SubmitEventCode):
callback(self.handleValidatePasscode(json: json!) as AnyObject,nil)
default:
//UnknownError
callback(nil, nil)
}
}
func handleAuthError(json: AnyObject) -> NSError {
if let eventObj = json as? JSONDictionary {
//
if let messageObj: AnyObject = eventObj["error"] {
if let message = messageObj as? String {
return NSError(domain: "validatePasscode", code: 200, userInfo: ["error": message])
}
}
}
return NSError(domain: "validatePasscode", code: 200, userInfo: ["error": "unknown auth error"])
}
func handleValidatePasscode(json: AnyObject) -> Event? {
if let eventObj = json as? JSONDictionary{
if let eventid: AnyObject = eventObj["event_id"]{
if let eventJson = eventid as? JSONDictionary {
if let eventpass = Event.init(JSON: eventJson){
return eventpass
}
}
}
}
return nil
}
//private
func makeHTTPPostRequest(path: Path, callback: #escaping APICallback, url: String) {
self.path = path
self.callback = callback
var request = URLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let dataTask = session.dataTask(with: request, completionHandler: {
(data: Data?, response: URLResponse?, error: Error?) -> Void in
if data != nil {
DispatchQueue.main.async {
callback(nil,nil)
}
}
})
dataTask.resume()
}
}
Event.swift
struct Event {
let id: String
let name: String
let location: String
let startDateTime: Date
let endDateTime: String
let deleteFlag: Bool?
let deleteDateTime: String?
let dateCreated: String?
let hasRaffle: Bool?
let registrationReq: Bool?
let participantCount: Int
let closedFlag: Bool?
let closedDateTime: String?
let reopenFlag: Bool?
let reopenDateTime: String?
init?(JSON: [String: AnyObject]) {
guard let eventID = JSON["event_id"] as? String,
let eventName = JSON["event_name"] as? String,
let eventLocation = JSON["event_location"] as? String,
let startDateTime = JSON["start_datetime"] as? String,
let endDateTime = JSON["end_datetime"] as? String,
let participantCount = JSON["participant_count"] as? Int else {
return nil
}
self.id = eventID
self.name = eventName
self.location = eventLocation
self.endDateTime = endDateTime
self.participantCount = participantCount
validatePasscode Function
func validateEventPasscode() {
//Show Loading
self.view.squareLoading.start(0.0)
let api = APIService()
api.validatePasscode(eventcode: eventCode) { (data, error) in
guard let eventDetails = self.event, error == nil else {
if let networkError = error {
if networkError != error {
_ = SCLAlertView(appearance: appearance).showError("Ooops", subtitle: "Please enter valid event code")
else {
_ = SCLAlertView(appearance: appearance).showError("Network Error", subtitle: "Network Error")
}
}
guard eventDetails.deleteFlag else {
_ = SCLAlertView(appearance: appearance).showError("Ooops!", subTitle: "Please enter a valid event passcode")
self.view.squareLoading.stop(0.0)
return
}
if eventDetails.closedFlag == true && eventDetails.reopenFlag == false {
_ = SCLAlertView(appearance: appearance).showError("Closed Event", subTitle: "Please check the status of your event and try again")
self.view.squareLoading.stop(0.0)
return
}
}
}

can not get access token from api

enter image description hereI'm new to Swift and I just faced a problem . any help and suggestion is welcome, also i've seen Alomofire, but I was not able to setup Alamofire because of some errors, and Also I need help in Alamofire :|
request.addValue("application/json", forHTTPHeaderField:
"Accept")
request.addValue("application/x-www-form-urlencoded",
forHTTPHeaderField: "Content-Type")
let postString = ["grant_type" : "password" ,
"username" : EntPhoneNumber.text! ,
"password" : EntPassword.text! ,] as [String :
Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject:
postString)
}catch let error {
print(error.localizedDescription)
DisplayMessage(UserMessage: "Something went wrong , please try
again!")
return
}
let task = URLSession.shared.dataTask(with: request)
{
(data : Data? , response : URLResponse? , error : Error?) in
self.removeActivtyIndicator(activityIndicator:
MyActivityIndicator)
if error != nil
{
self.DisplayMessage(UserMessage: "1Could not successfully
perform this request , please try again later.")
print("error = \(String(describing : error))")
return
}
// let's convert response sent from a server side code to a
NSDictionary object:
do { let json = try JSONSerialization.jsonObject(with: data!,
options: .mutableContainers) as? NSDictionary
print(json!)
if let parseJSON = json
{
let userID = parseJSON["grant_type"] as? String
print("access_token : \(String(describing: userID))");
if userID == nil
{
//display an alert dialog with a friendly error
message
self.DisplayMessage(UserMessage: "2Could not
successfully perform this request , please try later.")
return
}
else
{
self.DisplayMessage(UserMessage: "3successfully
loged in.")
}
}
...
as you can see this is my code which i'm posting a request to api to get an access_token but i receive an error :
{error = "invalid_request";
"error_description" = "The mandatory 'grant_type' parameter is missing.";
}
These are the parameters that I should post to API and in postman it works properly but my code does not work at all in compiler.
you are making it too complex
let postString = ["grant_type" : "password" ,
"username" : EntPhoneNumber.text! ,
"password" : EntPassword.text! ,] as [String :
Any]
Alamofire.request(URL, method: .post, parameters: postString, encoding: URLEncoding.methodDependent, headers: nil).responseJSON { response in
if let json = response.result.value {
print("Response: ",json)
}
}
try this.
This is all you need. If you have any doubt ask here.
Follow this link to install Alamofire using CocoaPods
https://www.raywenderlich.com/156971/cocoapods-tutorial-swift-getting-startedenter link description here
I have created this custom method for API request.
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
You need to encode the login and password parameters in query while sending the request. Lets create a separate Network class which has loginRequest(username:password) function which makes the API request to the server with username and password params. The login method has a closure which either returns a userId string or Error.
class Networking {
enum NetworkError: Error {
case parsingData
case jsonParsing
case emptyData
case apiError(error: Error)
}
func parseJSON(from data: Data) throws -> Any {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
return json
} catch {
return error
}
}
func loginRequest(username: String, password: String, completion: #escaping (String?, NetworkError?) -> ()) {
var request = URLRequest(url: URL(string: "api.nahadeh.com/connect/token")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let queryParams = "grant_type=password&username=\(username)&password=\(password)"
request.httpBody = queryParams.data(using: .utf8, allowLossyConversion: false)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error != nil else {
completion(nil, NetworkError.apiError(error: error!))
return
}
guard let data = data else {
return completion(nil, NetworkError.emptyData)
}
do {
let json = try self.parseJSON(from: data) as! [String: Any]
guard let accessToken = json["access_token"] as? String else {
completion(nil, NetworkError.jsonParsing)
return
}
completion(accessToken, nil)
} catch {
completion(nil, NetworkError.jsonParsing)
}
}.resume()
}
}
Now from your UIViewController subclass you can create the instance of Networking class and call the login method with username and password params
class LoginViewController: UIViewController {
let networking = Networking()
func login(username: String, password: String) {
networking.loginRequest(username: username, password: password) { (token, error) in
if let token = token {
print(token)
self.displayMessage("Successfully loged in. Go to home screen")
return
}
if let nError = error {
switch nError {
case .jsonParsing:
self.displayMessage("jsonParsingError")
case .emptyData:
self.displayMessage("emptyData")
case .apiError(let error):
print(error.localizedDescription)
self.displayMessage("Could not successfully perform this request , please try later.")
case .parsingData:
self.displayMessage("parsingData")
}
}
}
}
func displayMessage(_ message: String, completion: (() -> Void)? = nil) {
let alert = UIAlertController(title: "Message", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: completion)
}
}
Using Alamofire it's very easy to make API request, just pass the params and it will do the work for you
func loginRequest(username: String, password: String, completion: #escaping (String?, Error?) -> ()) {
let params: [String: String] = [
"grant_id": "password",
"username": username,
"password" : password
]
Alamofire.request("api.nahadeh.com/connect/token", method: .post, parameters: params, encoding: .httpBody, headers: nil).validate().response { (response) in
switch response.result {
case .success(let value):
let accessToken = value["access_token"]
completion(accessToken, nil)
case .failure(let error):
completion(nil, error)
}
}
}

how to go on next viewController

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.

Calling a function and wait for its completion

i have this class and its func
class DataUsuarios {
func update(completionHandler : ((isResponse : Array<JSON>) -> Void)) {
//CODE
completionHandler(isResponse: jsn)
}
}
and i call it with this
let data = DataUsuarios()
data.update{(isResponse) -> Void in
self.datos = isResponse
}
and it works as it should..
Now i have this class and function that i made
import Foundation
class Post{
func makeRequest(param : String, url : String, completionHandler : ((succeeded: Bool, msg: String? , crypted : String?) -> Void)) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let params : Dictionary<String, String> = ["VAL": param]
let session = NSURLSession.sharedSession()
session.configuration.timeoutIntervalForRequest = 3 //3 segundos timeoutRequest
session.configuration.timeoutIntervalForResource = 5 //5 segundos timeoutResource
request.HTTPMethod = "POST"
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
}catch let err as NSError {
print(err.localizedDescription)
print("Error could not make request'")
completionHandler(succeeded: false, msg: "Error al interpretar JSON" , crypted: nil)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
var json : NSDictionary?
do{
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
}catch let err as NSError {
print(err.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
completionHandler(succeeded: false, msg: "Error en POST", crypted: nil)
}
if let parseJSON = json {
if let encrypted = parseJSON["encriptado"] as? String {
let decrypted = encrypted.aesDecrypt()
let datosDecrypted: NSData = decrypted.dataUsingEncoding(NSUTF8StringEncoding)!
var jsonLogin:NSDictionary!
do{
jsonLogin = try NSJSONSerialization.JSONObjectWithData(datosDecrypted , options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
}catch let err as NSError {
print(err.localizedDescription)
print("Error could not make request'")
completionHandler(succeeded: false, msg: "Error" , crypted: nil)
}
if ( jsonLogin.valueForKey("success") != nil ) {
if let successNumber = jsonLogin.valueForKey("success") as! Int! {
print("Success: " , successNumber);
completionHandler(succeeded: true, msg: nil, crypted: decrypted)
}
}
completionHandler(succeeded: false, msg: "Error Success", crypted: nil)
}
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
completionHandler(succeeded: false, msg: "Error", crypted: nil)
}
})
task.resume()
}
}
but i don't know how to call it and get the completionHandler values
let post = Post()
post.makeRequest(cad, url: Constants.Static.server+"url.php" { succeeded, msg, crypted) -> Void in
}
Hope you can help! :)
Perhaps you want dispatch_async()?:
func makeRequest(param : String, url : String, completionHandler : ((succeeded: Bool, msg: String? , crypted : String?) -> ())) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
println("This is run on the background queue")
//CODE
dispatch_async(dispatch_get_main_queue(), 0), {
println("This is run on the main queue, after the previous block")
completionHandler(succeeded: true, msg: nil, crypted: decrypted)
}
}
}
Ok, i found it..
post.makeRequest(cad, url: Constants.Static.server+"url.php" ){(succedded : Bool, msg : String?, crypted:String? ) in
if(succedded){
// CODE USING CRYPTED
}else {
// CODE USING MSG
}
}

Resources