Calling a function and wait for its completion - ios

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

Related

How to get JSON response data from shared class to ViewController?

I'm not using Alamofire, so i want to use JSON post approach in SharedClass and i want to send my api name and all parameters to that function. Finally i want to get the response back. I tried but it's not working. If it's not correct please correct me or if any other options are available please suggest me.
My code in SharedClass
func postRequestFunction(apiName:String , parameters:String ) -> [String:Any] {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print(error!)
// print("error=\(String(describing: error))")
print("localizedDescription : \(String(describing: error?.localizedDescription))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
print(returnRes)
} catch let error as NSError {
print(error)
}
}
task.resume()
return returnRes
}
In my view controller class my code is. Here i'm calling function
func getProjectDetails() {
let response = SharedClass.sharedInstance.postRequestFunction(apiName: "API Name", parameters: parameters)
print(response)
let res = response["Response"] as! [String:Any]
let status = res["status"] as! String
if status == "SUCCESS" {
//I will handle response here
} else {
let message = res["message"] as! String
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: message)
}
}
Here is my solution:
class APIManager {
private init () {}
static let shared = APIManager()
func postRequestFunction(apiName: String , parameters: String, onCompletion: #escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
onCompletion(false, error, nil)
} else {
guard let data = data else {
onCompletion(false, error, nil)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
onCompletion(true, nil, returnRes)
} catch let error as NSError {
onCompletion(false, error, nil)
}
} else {
onCompletion(false, error, nil)
}
}
}
task.resume()
}
}
func getProjectDetails() {
/* Notes:
** onCompletion Block Parameters:
success - This indicates whether the API called successfully or not.
error - This indicates errors from either API calling failed, JSON parsing, or httpStatus is not 200.
result - This indicates the JSON parsed result.
** APIManager:
I have renamed your SharedClass to APIManager for better readibility.
** sharedInstance:
I have renamed sharedInstance to shared for better readibility.
*/
APIManager.shared.postRequestFunction(apiName: "API Name", parameters: "parameters") { (success, error, result) in
if success {
if let res = result?["Response"] as? [String: Any] {
if let status = res["status"] as? String {
if status == "SUCCESS" {
//You can handle response here.
} else {
let message = res["message"] as! String
//Call alert function.
}
}
}
} else {
print(error?.localizedDescription)
}
}
}
You forgot the asynchronous paradigm of Service, You can return your API response in Closure, as like below
func postRequestFunction(apiName:String , parameters:String, returnRes: #escaping ([String: Any]) -> () ) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
// check for fundamental networking error
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
if let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
returnRes(response)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
And use like below
postRequestFunction(apiName: "yourUrl", parameters: "Param") { (response) in
print(response)
}

How to fetch JSON data from a url using URLSession?

I am working on an iOS application in which I have to fetch data from this url .
As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.
Here is my code.
import UIKit
import SwiftyJSON
typealias ServiceResponse = (ApiResponseData, NSError?) -> Void
class ApiManager: NSObject {
var session:URLSession? = nil
var urlRequest:URLRequest? = nil
override init(){
super.init()
urlRequest = URLRequest(url: URL(string:"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")!)
urlRequest?.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
session = URLSession(configuration: .default)
}
func callRestApiToFetchDetails(onCompletion: #escaping ServiceResponse) {
let task = session?.dataTask(with: urlRequest!, completionHandler: {data, response, error -> Void in
print("Response = \(data)")
do {
let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
// Do Stuff
print("\(jsonData)")
} catch {
// handle error
print("Error in parsing - \(error)")
}
})
task?.resume()
}
}
But I am getting error in parsing.
You web service response is String.Encoding.ascii that convert into
String.Encoding.utf8 after you have to convert through
NSDictionary JSONSerialization.
Try this method to work.
let url = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in
if let d = data {
if let value = String(data: d, encoding: String.Encoding.ascii) {
if let jsonData = value.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]
if let arr = json["rows"] as? [[String: Any]] {
debugPrint(arr)
}
} catch {
NSLog("ERROR \(error.localizedDescription)")
}
}
}
}
}.resume()

Application crash when adhoc distribute but doesn't crash when install with XCode

I have an Application and when ever i install the app via itunes/Diawi adhoc distribution it crashes but doesn't crash when i install the app via XCODE.
MY CRASH REPORT..
Thread 0 Crashed:
0 Vabo 0x00000001000bb07c specialized AppDelegate.registerDeviceForPushNotification(UIApplication) -> () (AppDelegate.swift:214)
1 Vabo 0x00000001000ab260 ViewController.(connectToWebWith(String, password : String) -> ()).(closure #2).(closure #3) (ViewController.swift:265)
Swift method of Crash number 1:
func registerDeviceForPushNotification(application:UIApplication) -> Void {
let settings: UIUserNotificationSettings = UIUserNotificationSettings.init(forTypes: [.Alert,.Badge,.Sound], categories: nil)
self.pushNotificationToken = FIRInstanceID.instanceID().token()!
let userID = self.userData["id"] as! NSNumber
print("InstanceID token: \(self.pushNotificationToken)")
self.registerDeviceOnServerWith(self.pushNotificationToken, userID: userID)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
func registerDeviceOnServerWith(token:String, userID:NSNumber) -> Void {
let params = ["api_token":token, "user_id":userID , "type":"iOS"]
// params.setValue(username, forKey: "email")
// params.setValue(password, forKey: "password")
let urlString = Constants.kMainURL + Constants.kRegisterDeviceToken;
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue(self.tokenID as String, forHTTPHeaderField: "token")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else {
return
}
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success:NSString = (parseJSON["status"] as? NSString)!
if success.isEqualToString("Success"){
print("APNS is Registeration is : \(success)")
}else{
self.registerDeviceOnServerWith(token, userID: userID)
// Status Failed
}
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
}
})
task.resume()
}
Method of Crash Number 2:
func connectToWebWith(username:String, password:String) -> Void {
self.startLoadingAnimator()
let params = ["email":username, "password":password]
// params.setValue(username, forKey: "email")
// params.setValue(password, forKey: "password")
let urlString = Constants.kMainURL + Constants.kSignInURL;
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
dispatch_async(dispatch_get_main_queue(), {
self.stopLoadingAnimator()
let alertView = UIAlertView.init(title: "Error", message: "Failed to authenticate", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
})
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else {
dispatch_async(dispatch_get_main_queue(), {
self.stopLoadingAnimator()
let alertView = UIAlertView.init(title: "Error", message: "Couldn't establish connection", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
})
return
}
print("Response: \(response)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
dispatch_async(dispatch_get_main_queue(), {
self.stopLoadingAnimator()
let alertView = UIAlertView.init(title: "Error", message: "Failed to authenticate", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
})
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
self.stopLoadingAnimator()
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
print("JSON = \(parseJSON)")
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success:NSString = (parseJSON["status"] as? NSString)!
if success.isEqualToString("Success"){
print("Succes: \(success)")
dispatch_async(dispatch_get_main_queue(), {
let userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setValue(username, forKey: Constants.kVaboEmail)
userDefault.synchronize()
userDefault.setValue(password, forKey: Constants.kVaboPassword)
userDefault.synchronize()
userDefault.setBool(true, forKey: Constants.kIsLoggedIn)
userDefault.synchronize()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.tokenID = (parseJSON["token"] as? NSString)!
let array = parseJSON["userData"] as! NSArray
appDelegate.userData = array.objectAtIndex(0) as! NSDictionary
appDelegate.userDidLoggedIn()
})
}else{
let errorString = parseJSON["messageData"] as! String
dispatch_async(dispatch_get_main_queue(), {
let alertView = UIAlertView.init(title: "Vabo", message: errorString, delegate: nil, cancelButtonTitle: "Dismiss")
alertView.show()
})
}
}
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)")
dispatch_async(dispatch_get_main_queue(), {
self.stopLoadingAnimator()
let alertView = UIAlertView.init(title: "Error", message: "Server Response Failed", delegate: nil, cancelButtonTitle: "OK")
alertView.show()
})
}
})
task.resume()
}
P.S
The iPhone on the app give crash has iOS 10.1,
While it runs perfectly on iOS 9.3.5
From the log you provided it's not clear which line is the 214th. (AppDelegate.swift:214) and the reason for the crash is also missing from the log.
But I see you are using force cast a couple of places, I would make sure that those values actually exist when you try to access them. I suggest to use guard statements instead of force casting:
func registerDeviceForPushNotification(application:UIApplication) -> Void {
let settings: UIUserNotificationSettings = UIUserNotificationSettings.init(forTypes: [.Alert,.Badge,.Sound], categories: nil)
guard let token = FIRInstanceID.instanceID().token(), let userID = self.userData["id"] as? NSNumber {
// You might want to log something here
return
}
print("InstanceID token: \(self.pushNotificationToken)")
self.registerDeviceOnServerWith(self.pushNotificationToken, userID: userID)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
Update:
If you take a look on the documentation of the UIUserNotificationSettings you can see it has been deprecated in iOS 10. You should use the UNUserNotificationCenter on iOS 10:
let center = UNUserNotificationCenter.currentNotificationCenter()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
You can find more information here and here

Parsing the JSON Data in Swift 2

I am parsing the data and I am getting the responseString also.But my problem is I want to convert it into dictionary and then I want to get the values from that jsonObject.
But I am unable to get that.
My Code is as follows
func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: String) -> ()){
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
var bodyData = ""
for (key,value) in params{
if (value == nil){ continue }
let scapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(
.URLHostAllowedCharacterSet())!
let scapedValue = value!.stringByAddingPercentEncodingWithAllowedCharacters(
.URLHostAllowedCharacterSet())!
bodyData += "\(scapedKey)=\(scapedValue)&"
}
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = session.dataTaskWithRequest(request,
completionHandler: {data, response, error -> Void in
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
postCompleted(succeeded: true, msg: dataString! as String)
print(dataString!)
if let datas = dataString!.dataUsingEncoding(NSUTF8StringEncoding) {
do{
let json = try NSJSONSerialization.JSONObjectWithData(datas, options: []) as? [String:AnyObject]
//return json
print(json)
}
catch
{
print("Something went wrong")
}
}
})
task.resume()
}
I am calling that method like this
self.loginRequest("http://stream.gsr-india.com:8080/pgn_service/REST/WebService/GetUserDetails",
withParams: ["first_name":firstNameTextField.text,"last_name":lastNameTextField.text , "application_id":uniqueIdTextField.text])
{
(succeeded: Bool, msg: String) -> () in
if(succeeded) {
if msg == "0"
{
//Incorrect data...
}
else
{
//The login it's ok...
}
}
}
Can anyone Please help me to resolve that.
Thanks In Advance.
Change method declaration to
func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: NSDictionary?) -> ()){
then change the task handler to
let task = session.dataTaskWithRequest(request,
completionHandler: {data, response, error -> Void in
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString!)
do{
let json = try NSJSONSerialization.JSONObjectWithData(datas, options: []) as? [String:AnyObject]
postCompleted(succeeded: true, msg: json)
print(json)
}
catch {
print("Something went wrong")
}
}
})
change the callback to
(succeeded: Bool, msgDict: NSDictionary?) -> () in
if let dict = msgDict {
// call any value like dict["error"] etc
}

Send JSON data to server?

I have this code in my app delegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.post(["data":"tes"], url: "pandubaraja.esy.es/test.php") { (succeeded: Bool, msg: String) -> () in
var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
if(succeeded) {
alert.title = "Success!"
alert.message = msg
}
else {
alert.title = "Failed :("
alert.message = msg
}
// Move to the UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// Show the alert
alert.show()
})
}
return true
}
func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: "pandubaraja.esy.es/test.php")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
var msg = "No message"
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
postCompleted(succeeded: false, msg: "Error")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
if let success = parseJSON["success"] as? Bool {
println("Succes: \(success)")
postCompleted(succeeded: success, msg: "Logged in.")
}
return
}
else {
// Woa, okay the json object was nil, something went wrong. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
postCompleted(succeeded: false, msg: "Error")
}
}
})
task.resume()
}
andIi already have the data when I clicked a button, and it shows on console (println) but I still confuse how I can send it to the server
this is the code for sending data or you can say, printing data on console
import UIKit
class SendData: UIViewController, PiechartDelegate{
#IBOutlet weak var Kirim: UIImageView!
var total: CGFloat = 40
func tapGesture(gesture: UIGestureRecognizer) {
if let Kirim = gesture.view as? UIImageView { // if you subclass UIImageView, then change "UIImageView" to your subclass
println(personaldata.data)
for (var i = 0; i < Nutritionmenu.data.count; i++) {
println(Nutritionmenu.data[i]);
}
for (var i = 0; i < Activitymenu.dataact.count; i++) {
println(Activitymenu.dataact[i]);
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:")
Kirim.addGestureRecognizer(tapGesture)
Kirim.userInteractionEnabled = true
this is the data that I want to send to the server but when I compile, it always says error instead of success!

Resources