I'm new in Swift and I can't find the solution to this code :
func presentationlum() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://raspberrypi.local/etatlum.php")!)
let Session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
var JsonDict=NSArray()
let dem = Session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do{
JsonDict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0) )as! NSArray
}
print(JsonDict)
})
dem.resume()
if JsonDict[0] as! String == "0"
{
print("it works !")
}
else
{
print("it works to !")
}
}
When I built it I have a "Thread 1 : signal SIGABRT" error.
The Server send a Json_encode array with only 0 or 1 ( example : ["1","0","0","1","0"]).
I just want to get this response and do conditions with it but I can't.
Please help, thanks.
You are accessing your answer before the blocks complete :
func presentationlum() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://raspberrypi.local/etatlum.php")!)
let Session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
var JsonDict : NSArray
let dem = Session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do{
if let _JsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions() )as? NSArray
{
JsonDict = _JsonDict
if JsonDict[0] as! String == "0"{
print("it works !")
}else{
print("it works to !")
}
}else{
print("Cannot parse JSON answer")
}
}catch {
print("An Error as occurred : \(error)")
}
print(JsonDict)
})
dem.resume()
}
Related
This is my script in php to have a Json response
<?php
include "dbconnect.php";
$id = $_POST['id'];
$uname = $_POST['uname'];
try {
$queryExistingBike = "SELECT StatoBici, Username FROM BICI INNER JOIN UTENTE ON utenteKEY = KEYutente WHERE (IdBike = '$id')";
$search = $connection->query($queryExistingBike);
//print_r ($search);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$dati = $search->fetch_assoc();
if ($dati["Username"] == "$uname") {
$dati['Username'] = "true";
} else {
$dati['Username'] = "false";
}
//print_r($dati);
print json_encode($dati);
?>
This is the Json response from php script
{"StatoBici":"ok","Username":"false"}
This is the code in swift to make a http post request to web service
func jsonResponse(){
var request = URLRequest(url: URL(string: "http://bike1010.com/webservice/getBikeData.php")!)
request.httpMethod = "POST"
let postString = "id=2017&uname=admin" // Your parameter
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: 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))")
}
let responseString = try? JSONSerialization.jsonObject(with: data, options:[])
print(responseString)
}
task.resume()
}
The output into Xcode
Optional({
StatoBici : Ok
Username : Tue
})
if that's what you wanted to achieve:
let responseString = try? JSONSerialization.jsonObject(with: data, options:[]) as? [String:Any]
print(responseString)
//simple example for receiving each field from response
let statoBici:String = responseString["StatoBici"] as! String
let username:Bool = responseString["Username"] as! Bool
print("StatoBici received: \(statoBici), username received: \(username)")
As Wojcik mentioned in comment you already have parse JSON. Your responseString is actually parsed object. You can access values as:
if let obj = responseString as? NSDictionary {
let StatoBici = obj.value(for : "StatoBici") as! String
let okValue = obj.value(for : "OK") as! String // If OK is bool use bool
}
I am making an ios application. I am new to swift and not able to understand my code. can anyone please help me to understand what is going on with my code.
This is login application on adding email id if the email exist it should go to next view controller and if not then it should give error. I am getting difficulty in understanding my code .
Here is my code:
class checkLoginViewController: UIViewController {
#IBOutlet weak var checkUsernametextfield: UITextField!
#IBAction func checkUsernameButton(_ sender: UIButton) {
print("Clicked On SUbmit !!!!")
//Read Value from Text
let email = checkUsernametextfield.text
let myUrl = URL(string: "http://192.168.0.117/rest/signup.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "email=\(String(describing: email))";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("response = \(String(describing: response))")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of First Name by its key
let emailValue = parseJSON["email"] as? String
print("email: \(String(describing: emailValue))")
}
} catch {
print(error)
}
}
task.resume()
Output:
Clicked On SUbmit !!!! response = Optional( { URL: http://192.168.0.117/rest/signup.php } { Status
Code: 200, Headers {
Connection = (
"Keep-Alive"
);
"Content-Length" = (
61
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 12 Mar 2018 06:35:58 GMT"
);
"Keep-Alive" = (
"timeout=5, max=100"
);
Server = (
"Apache/2.4.27 (Ubuntu)"
); } }) email: nil
Maybe try this. Hope it works.
let url = URL(string:"http://192.168.0.117/rest/signup.php")
let parameters = ["email": checkUsernametextfield.text]
var request = URLRequest(url : url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
session.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
do {
let json = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
if let json = json {
print("HERE SHOULD BE YOUR JSON \(json)")
}
}
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
}).resume()
Here is way to send request.
enter code here
static func downloadConfig(url:URL, completion:#escaping (_ sucess:Bool , _ jsonObject: [String: String]?)->() ) {
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded",
forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
request.httpBody = postString.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data,response,error) in
if let data = data ,let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200 {
do {
if let todoJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String]{
completion(true,todoJSON)
}
else
{
completion(false,nil)
}
}
catch {
//erro parsing
completion(false,nil)
}
}
else
{
completion(false,nil)
}
}.resume()
}
use this download json function in this way.
//Download Json File
let base_url = "base_url"
let urlstr = String.init(format: "%#", base_url)
let url = URL(string: urlstr)
GameUtil.downloadConfig(url: url!) {
(sucess: Bool , jsonObject: [String:String]?) in
if sucess , jsonObject != nil
{
self.configJson = jsonObject!
}
}
I am getting response data nil.
func fetchSinglePageData() {
var response: NSData?
var errors: NSError?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
response = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)
print("LatestURL Single page:(response)")
if response == nil {
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
}
else{
let jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(response!, options: nil, error: &errors) as NSDictionary
print("JSON Response Single page:(jsonDict)")
var statuses = [NSObject : AnyObject]()
self.lblstartTime?.text = jsonDict["start_time"] as? String
self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
self.lblManager?.text = jsonDict["manager"] as? String
}
})
}
project_id is string which is recevied from presvious page which is correctly working.
In swift 3
//make a url request
let urlString = "your_url"
let urlRequest = URLRequest.init(url: URL.init(string: urlString)!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 50)
//create a session
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, urlResponse, error) in
if error != nil{
//handle error
return
}else{
if let responseData = data{
let jsonDict = try JSONSerialization.jsonObject(with: responseData, options: [])as? [String:Any]
//handle your response here
}
}
}
task.resume()
In swift 2.2
let urlString = "your_url"
let request = NSURLRequest(URL: NSURL(string: urlString)!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
//handel error
print(error!.localizedDescription)
return
}
if let responseData = data{
do{
if let jsonDict = try NSJSONSerialization.JSONObjectWithData(responseData, options: [])as? [String:Any]{
//you have data in json dict
}
}catch{
print("error in parsing response")
return
}
}
}
task.resume()
func singlePageData(){
var errors: NSError?
let urlString = "xyz.com"
print("URL RESPONSE \(urlString)")
let request = NSURLRequest(URL: NSURL(string: urlString), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
//handel error
print(error!.localizedDescription)
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
return
}
if let responseData = data{
var jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &errors) as NSDictionary!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
println("Json dict value \(jsonDict)")
self.lblprojectName?.text = jsonDict["name"] as? String
println("lblprojectName: \(self.lblprojectName?.text)")
self.lblstartTime?.text = jsonDict["start_time"] as? String
println("lblstartTime : \(self.lblstartTime?.text)")
self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
println("lblcurrentStage : \(self.lblcurrentStage?.text)")
self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
println("lblcompletionTime : \(self.lblcompletionTime?.text)")
self.lblManager?.text = jsonDict["manager"] as? String
})
}
}
task.resume()
}
This is my answer as per Jitendra Solanki answer i have made changes to code and it is now working in Swift 1.2
After a quick look, maybe \ missing:
NSData(contentsOfFile:"url...?project_id=\(self.projectID)&project_page=Request"
In this line:
response = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)
you have project_id=(self.projectID), to use interpolation you should instead have project_id=\(self.projectID)
I would suggest that you separate the code to generate your full URL, then print the URL to the console and ensure that it is what you would expect.
Then you can visit the url yourself and check to see what the server returns, then once you know you have the correct URL and response you can then work to deserialise the response
EDIT: updated with URLSession (Swift 3 version)
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
let projectID = 12
let url = URL(string: "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(projectID)&project_page=Request")
dataTask = defaultSession.dataTask(with: url!) {
data, response, error in
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
if let responseData = data {
if let json = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String:AnyObject] {
print(json)
}
}
}
}
}
dataTask?.resume()
After updating to Swift 2.0 my http request is no longer working. I switched url strings from http to https after updating server to ssl due to new swift 2.0 guidelines but now I am getting request timed out. Any help appreciated.
func getJSON(){
activityIndicator.startAnimating()
let myUrl = NSURL(string: "https://www.example.com/getList.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let userEmail = defaults.objectForKey("email") as? String
let postString = "email=\(userEmail!)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
if(resultValue == "success")
{
self.activityIndicator.stopAnimating()
dispatch_async(dispatch_get_main_queue(), {
self.tableData = parseJSON["bList"] as! NSArray
self.tableFeatData = parseJSON["fList"] as! NSArray
let now = NSDate()
let updateString = "Last Updated at " + self.dateFormatter.stringFromDate(now)
self.refreshControl.attributedTitle = NSAttributedString(string: updateString)
if self.refreshControl.refreshing
{
self.refreshControl.endRefreshing()
}
self.tblView!.reloadData()
})
}
else
{
self.activityIndicator.stopAnimating()
let messageToDisplay = parseJSON["message"] as! String!;
dispatch_async(dispatch_get_main_queue(), {
//Display alert message with confirmation
let myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default){action in
self.dismissViewControllerAnimated(true, completion:nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated:true, completion:nil);
});
}
}
}
task.resume();
}
I am trying to parse JSON but getting this error:
type of expression is ambiguous without more context
My code is:
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
let endpoint = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL:endpoint!)
let session = NSURLSession.sharedSession()
NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) throws -> Void in
if error != nil {
print("Get Error")
}else{
//var error:NSError?
do {
let json:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
print(json)
} catch let error as NSError {
// error handling
print(error?.localizedDescription)
}
}
}
//task.resume()
}
This is working fine with out try catch in Xcode 6.4 but this is not working in Xcode 7.
Don't declare an AnyObject type for your decoded object since you want it to be an NSDictionary and you're performing a conversion to do this.
Also it's better to use zero options for NSJSONSerialization instead of random ones.
In my example I've also used a custom error type just for demonstration.
Note, if you're using a custom error type, you have to also include a generic catch to be exhaustive (in this example, with a simple downcasting to NSError).
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
The same with Swift 3.0.2:
enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
guard let endpoint = URL(string: urlPath) else {
print("Error creating endpoint")
return
}
URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
Apple declare here.
func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
Fix it:
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
// Your handle response here!
}
UPDATE:
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
let endpoint = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL:endpoint!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
print(error)
}.resume()
}
RESULT:
Optional(Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x7f8873f148d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://headers.jsontest.com/, NSErrorFailingURLKey=http://headers.jsontest.com/, NSLocalizedDescription=The resource could not be loaded because the App >Transport Security policy requires the use of a secure connection.})
Hope this helps!
For Swift 4 Web service Call , Post Method using URLSession
func WebseviceCall(){
var request = URLRequest(url: URL(string: "YOUR_URL")!)
request.httpMethod = "POST"
let postString = "PARAMETERS"
request.httpBody = postString.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
Here is the simplest way to parse JSON using NSUrlSession.,
let PARAMS = "{\"params1\":\"%#\",\"Params2\":\"%#\",\"params3\":\"%#\"}"
let URL = "your url here"
on submit button write this code.,
let urlStr = String(format: "%#",URL)
let jsonString = String(format:PARAMS, params1value,params2value,params3value )
// Encode your data here
let jsonData = jsonString.data(using:.utf8)
var request = URLRequest(url: URL(string: urlStr)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
//set your method type here
request.httpMethod = "POST"
request.httpBody = jsonData
let configuration = URLSessionConfiguration.default
// create a session here
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) {(data , response, error) in
if(error != nil){
print("Error \(String(describing: error))")
}
else {
do {
let fetchedDataDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(fetchedDataDictionary!)
let message = fetchedDataDictionary?["response key here"] as! String
if message == "your response string" {
print(message)
}
else {
self.dataArray = (fetchedDataDictionary?["data"] as! NSArray)
}
}
catch let error as NSError {
print(error.debugDescription)
}
}
}
task.resume()
1)Make ApiConnection class in to your project..
import Foundation
class ApiConnection: NSObject {
class func postDataWithRequest(_ dicData:NSDictionary, completionHandler:#escaping (_ response:NSDictionary?,_ status:Bool)->Void)
{
let URL=Foundation.URL(string: Constant.API_URL)
let request=NSMutableURLRequest(url: URL!)
request.httpMethod="POST"
request.addValue(Constant.kApplicationJSON, forHTTPHeaderField:Constant.kContentType)
let data=try? JSONSerialization .data(withJSONObject: dicData, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody=data
//let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*5))
//dispatch_after(dispatchTime, dispatch_get_main_queue()) {
let session = URLSession.shared.dataTask(with: request as URLRequest,completionHandler: { (data, response, error) in
if error==nil
{
DispatchQueue.main.async(execute: {
let dicResponse = try? JSONSerialization .jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
completionHandler(dicResponse, error==nil)
})
}
else
{
completionHandler(nil, error==nil)
}
})
session.resume()
}
}
**********************************use this in your view controller****************
let dict : NSMutableDictionary = [:];
dict["Your key"] = "your value"
dict["Your key"] = "your value"
dict["Your key"] = "your value"
ApiConnection.postDataWithRequest(dict) { (response, status) in
if(status){
print(response);
else{
print("failed webservice call");
}
}
*************************************Swift3.0*************************************
var objDic = [String: Any]()
let dic = NSMutableDictionary()
print(dic)
objDic["action"] = ""
objDic["product_id"] = self.peroductid
// arrProduct .addObjects(from: objDic) as! Dictionary
print("\(objDic)")
Alamofire.request(Constant.Webservice_productinfo,
method: HTTPMethod.post,
parameters:objDic as? Parameters,
encoding: JSONEncoding.default,
headers: nil).responseJSON
{
(response:DataResponse<Any>) in
switch(response.result)
{
case .success(_):
if response.result.value != nil
{
let status = response2?.object(forKey: "status") as! String?
if status == "error"{}
//finding the status from response
var response2 = response.result.value as AnyObject?
self.response1 = response.result.value as! NSDictionary
let type =
(self.cartlistarray[0] as!NSDictionary)["base_image"]
cell.productname.text = (self.cartlistarray[0] as!NSDictionary)["name"] as? String
//Store the result value in swift 3.0
UserDefaults.standard.set(userDetail.value(forKey: "email") as? NSString, forKey: "email")
if(UserDefaults.standard.object(forKey:"email") == nil){}
//did select row click the data pass into another view
let ProductListViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProductListViewController") as! ProductListViewController
ProductListViewController.category_id = ((self.bannerarry[0] as? [String : String])?["cat_id"])!
//or else callin from indexpath.row
item = ((cartlistarray[indexpath.row] as? NSDictionary)?.value(forKey:"product_id") as! String?)!
extension UIAlertController{
func showErrorAlert(strMesage:NSString,VC:Any)
{
let alert = UIAlertController(title: "Demo App", message: strMesage as String, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
(VC as AnyObject).present(alert, animated: true, completion: nil)
}
}
extension UILabel{
func setLabel(strTitle:String)
{
self.backgroundColor = UIColor.clear
self.textColor = UIColor.white
self.textAlignment = NSTextAlignment.left
self.font = UIFont(name: "Avenir-Light", size: 15.0)
self.font = UIFont.italicSystemFont(ofSize: 15)
self.text=strTitle
}
}
//image in to base 64
let image = imageCamera.image
let imageData:NSData = UIImageJPEGRepresentation(image!, 1.0)!as NSData
imageconvert = imageData.base64EncodedString(options: .lineLength64Characters)
base64formate = imageconvert.trimmingCharacters(in:CharacterSet.whitespaces)
print(base64formate)
print data into profle view
let imageurl:String! = SharedManager.sharedInstance().myMutableDict.value(forKey:"profileimg") as? String ?? "123"
let url = URL(string: imageurl)
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: url!)!
// When from background thread, UI needs to be updated on main_queue
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
self.imageview.image = image
}
}
let actionSheetController: UIAlertController = UIAlertController(title: "Magento Extension App", message:response1?.object(forKey: "message") as? String, preferredStyle: .alert)
actionSheetController.addAction(UIAlertAction(title: "Ok", style: .default , handler:{ (UIAlertAction)in
print("Ok button click")
}))
self.present(actionSheetController, animated: true, completion: nil)
}
case .failure(_):
print("error: \(response.result.error)") // original
URL request
break
}
}
**************************objc**************************************************
NSDictionary *objDic1 = #{#"mode":#"loginUser",
#"email":[result
objectForKey:#"email"],
#"password":#"",
};
// With AFNetworking
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:100];
// manager set
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:WEBSERVICE_CALL_URL parameters:objDic1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable result) {
[SVProgressHUD dismiss];
NSLog(#"This s my response %#",result);
NSLog(#"success!");
if ([[result valueForKey:kStatus] isEqualToString:kOK])
{
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
}];
****************SDK LINK*******************************************
https://github.com/AFNetworking/AFNetworking
var userDetail = NSArray()
userDetail = self.response1.value(forKey: "userData") as! NSArray
print(userDetail)
self.tmpDic = userDetail[0] as! NSDictionary
print(self.tmpDic)
var optionsdic = NSDictionary()
optionsdic = self.tmpDic.value(forKey:"options") as! NSDictionary
print(optionsdic)
self.arrayOfKeys = optionsdic.allKeys as NSArray
print(self.arrayOfKeys)
if (self.arrayOfKeys.contains("color"))
{
print("color")
self.colorarray = optionsdic.value(forKey:"color") as! NSArray
print(self.colorarray.count)
for index in 0..<self.colorarray.count
{
var dic = NSDictionary ()
dic = self.colorarray .object(at: index) as! NSDictionary
self.colorarrayobject .add(dic)
print(dic)
}
print(self.colorarrayobject)
}
else {
var defaultarray = NSArray()
defaultarray = optionsdic.value(forKey:"default") as! NSArray
print(defaultarray)
self.element0array = defaultarray[0] as! NSArray
print(self.element0array)
self.dic = self.element0array[0] as! NSDictionary
print(dic)
self.arr5 = self.dic .value(forKey: "values") as! NSArray
print(self.arr5)
for iteams in 0..<self.arr5.count
{
var type = String()
type = ((self.arr5[iteams]as! NSDictionary)["label"]! as? String)!
self.configeresizeaarray.append(type)
}
print("default")
}
}
self.imagearray = self.array[0] as! NSArray
for items in 0..<self.imagearray.count
{
var type = String()
type = ((self.imagearray [items]as! NSDictionary)["image"]! as? String)!
self.cell0imagearray.append(type)
}
self.count = self.imagearray.count as Int
self.configurePageControl()
self.tableView.reloadData()
}
else
{
}
}
else
{
}