Is being a few weeks and I'm still stuck with this problem here. I'm having a mind block with Api. I'm quite new on this and I really need help.
I have those lines done. The single task is: Get data from my API and post it in my label. I've 4 files/classes being used.
UserProfile
import Foundation
import SwiftyJSON
class UserProfileWork: NSObject {
var workHistoryId = String()
var jobSeekerId = String()
var jobPosition = String()
var employer = String()
var workHistoryName = String()
var responsabilities = String()
var reasonForLeaving = String()
var currentPosition = Int()
var startMonth = String()
var startYear = String()
var endMonth = String()
var endYear = String()
init?(workDict: [String: JSON]){
guard let workHistoryId = workDict["work_history_id"]?.string,
let jobSeekerId = workDict["job_seeker_id"]?.string,
let jobPosition = workDict["position"]?.string,
let employer = workDict["employer"]?.string,
let workHistoryName = workDict["work_history_name"]?.string,
let responsabilities = workDict["responsibilities"]?.string,
let reasonForLeaving = workDict["reason_for_leaving"]?.string,
let currentPosition = workDict["is_current_position"]?.toInt,
let startMonth = workDict["start_month"]?.string,
let startYear = workDict["start_year"]?.string,
let endMonth = workDict["end_month"]?.string,
let endYear = workDict["end_year"]?.string else { return nil}
self.workHistoryId = workHistoryId
self.jobSeekerId = jobSeekerId
self.jobPosition = jobPosition
self.employer = employer
self.workHistoryName = workHistoryName
self.responsabilities = responsabilities
self.reasonForLeaving = reasonForLeaving
self.currentPosition = currentPosition
self.startMonth = startMonth
self.startYear = startYear
self.endMonth = endMonth
self.endYear = endYear
}
}
Api + Userprofile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: [UserProfile]?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].array else{
completion(nil, nil)
return
}
var userProfile = [UserProfile]()
for data in dataDict {
if let data = data.dictionary, let profileData = UserProfile.init(dict: data){
userProfile.append(profileData)
}
completion(nil, userProfile)
}
}
}
}
}
And my view Controller ( I had tableview before but I decided to use only scrollView + labeles because I just need to display those single data)
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
handleRefresh()
userData()
}
private func userData(){
self.userNameLabel.text = ""
self.userNameJobPositionLabel.text = "Job Title"
self.userLocationLabel.text = "User Location"
self.userWorkExpLabel.text = "Work Experience"
self.educationLabel.text = "Education"
self.infoAboutLabel.text = "About me. More about me"
self.userJobTitleLabel.text = "Job title again"
self.companyNameLabel.text = "Company Name"
self.startFinishLabel.text = "12 sep 2010 - 11 sep 2017"
self.programNameLabel.text = "web and mobile app dev"
self.schoolNameLabel.text = "school name"
self.startFinishEducLabel.text = "finished at"
}
//reusable cells
private func handleRefresh(){
API.userProfile { (error: Error?, userProfileData: [UserProfile]?) in
if let userProfileData = userProfileData {
self.userProfileData = userProfileData
}
}
API.userEducation { (error: Error?, userEducation : [UserProfileEducation]?) in
if let userEducation = userEducation {
self.userProfileEducation = userEducation
}
}
API.userWork { (error: Error?, userWork: [UserProfileWork]?) in
if let userWork = userWork {
self.userProfileWork = userWork
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}
I really need help on this guys. Please, help me!
I made some changes and It worked.
import UIKit
import SwiftyJSON
class UserProfile: NSObject{
var userID = String()
var JobSeekerId = String()
var userFstName = String()
var userLstName = String()
var userFullName = String()
var userJobTitle = String()
var userAbout = String()
var userLocation = String()
var userRecentSalary = String()
var userSalaryHiExpect = String()
var userSalaryLoExpect = String()
var userWebsiteUrl = String()
var userEmail = String()
var userMobile = String()
init?(dict: [String: Any]){
guard let userID = dict["user_id"] as? String,
let jobSeekerId = dict["job_seeker_id"] as? String,
let userFstName = dict["first_name"] as? String,
let userLstName = dict["last_name"] as? String,
let userFullName = dict["job_seeker_name"] as? String,
let userJobTitle = dict["personal_job_title"] as? String,
let userAbout = dict["about"] as? String,
let userLocation = dict["seekingLocations"] as? String,
let userRecentSalary = dict["most_recent_salary"] as? String,
let userSalaryHiExpect = dict["salary_expectation_high"] as? String,
let userSalaryLoExpect = dict["salary_expectation_low"] as? String,
let userWebsiteUrl = dict["website_url"] as? String,
let userEmail = dict["contact_email"] as? String,
let userMobile = dict["contact_mobile"] as? String else { return nil }
self.userID = userID
self.JobSeekerId = jobSeekerId
self.userFstName = userFstName
self.userLstName = userLstName
self.userFullName = userFullName
self.userJobTitle = userJobTitle
self.userAbout = userAbout
self.userLocation = userLocation
self.userRecentSalary = userRecentSalary
self.userSalaryHiExpect = userSalaryHiExpect
self.userSalaryLoExpect = userSalaryLoExpect
self.userWebsiteUrl = userWebsiteUrl
self.userEmail = userEmail
self.userMobile = userMobile
}
}
API+userProfile
import Foundation
import Alamofire
import SwiftyJSON
extension API {
class func userProfile(completion: #escaping(_ error: Error?, _ userProfile: UserProfile?) ->Void) {
let url = URLs.jobSeekerTest90
guard let api_token = helper.getApiToken() else {
completion(nil, nil)
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer \(api_token)",
"Accept": "application/json"
]
let parameters = [
"api_token": api_token
]
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseJSON{ response in
switch response.result{
case .failure(let error):
completion(error, nil)
print(error)
case .success(let value):
let json = JSON(value)
print(json)
guard let dataDict = json["data"]["jobSeeker"].dictionaryObject else{
completion(nil, nil)
return
}
var userProfile = UserProfile(dict: dataDict)
completion(nil, userProfile)
}
}
}
}
ViewController
import UIKit
import Alamofire
class ProfileViewController: UIViewController{
#IBOutlet weak var leadingConstraint: NSLayoutConstraint!
#IBOutlet weak var menuView: UIView!
#IBOutlet weak var menuProfilePicture: UIImageView!
#IBOutlet weak var menuProfileName: UILabel!
#IBOutlet weak var myProfileJobTitle: UILabel!
#IBOutlet weak var myAccountImageMenu: UIImageView!
#IBOutlet weak var switchProfileImageMenu: UIImageView!
#IBOutlet weak var signOutImageMenu: UIImageView!
//User profile
#IBOutlet weak var userProfilePicture: UIImageView!
#IBOutlet weak var userNameLabel: UILabel!
#IBOutlet weak var userNameJobPositionLabel: UILabel!
//quick facts
#IBOutlet weak var quickFactsLabel: UILabel!
#IBOutlet weak var userLocationImage: UIImageView!
#IBOutlet weak var userLocationLabel: UILabel!
#IBOutlet weak var userWorkExpImage: UIImageView!
#IBOutlet weak var userWorkExpLabel: UILabel!
#IBOutlet weak var educationImage: UIImageView!
#IBOutlet weak var educationLabel: UILabel!
#IBOutlet weak var infoImage: UIImageView!
#IBOutlet weak var infoAboutLabel: UILabel!
// most recent jobs
#IBOutlet weak var recentJobTitleLabel: UILabel!
#IBOutlet weak var userJobTitleLabel: UILabel!
#IBOutlet weak var companyNameLabel: UILabel!
#IBOutlet weak var startFinishLabel: UILabel!
//Education
#IBOutlet weak var highestEducLabel: UILabel!
#IBOutlet weak var programNameLabel: UILabel!
#IBOutlet weak var schoolNameLabel: UILabel!
#IBOutlet weak var startFinishEducLabel: UILabel!
var iconArray: [String]!
var userProfileData : [UserProfile] = []
var userProfileEducation : [UserProfileEducation] = []
var userProfileWork : [UserProfileWork] = []
var menuShowing = false
override func viewDidLoad() {
super.viewDidLoad()
iconArray = ["currentLocationIcon", "dataIcon", "educationIcon", "infiIcon"]
leadingConstraint.constant = -520
menuView.layer.shadowOpacity = 1
menuView.layer.shadowRadius = 5
menuProfilePicture.layer.cornerRadius = 35
menuProfilePicture.clipsToBounds = true
userProfilePicture.layer.cornerRadius = 55
userProfilePicture.clipsToBounds = true
userData()
userWorkProfileData()
userEducationProfileData()
}
private func userData(){
API.userProfile { (error: Error?, userProfileData: UserProfile?) in
if let userProfileData = userProfileData {
self.myProfileJobTitle.text = userProfileData.userFullName
self.menuProfileName.text = userProfileData.userJobTitle
self.userNameLabel.text = userProfileData.userFullName
self.userNameJobPositionLabel.text = userProfileData.userJobTitle
self.userLocationLabel.text = userProfileData.userLocation
self.infoAboutLabel.text = userProfileData.userAbout
self.userJobTitleLabel.text = userProfileData.userJobTitle
}
}
}
//Scroll hidden menu
#IBAction func scrollMenu(_ sender: Any) {
if(menuShowing){
leadingConstraint.constant = -520
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}else{
leadingConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
})
}
menuShowing = !menuShowing
}
override func dismissKeyboard() {
view.endEditing(true)
}
}
Related
I followed this Doc : https://stripe.com/docs/payments/accept-a-payment?platform=ios&ui=payment-sheet
I am getting these from my backend.
"clientSecret" : "pi_3JUrPkLW44AR......7WElFl",
"stripecustomerid" : "cus_K8......pLu4",
"paymentids" : "pi_3JVA.....R9VmA"
"EphemeralKey" : "ephkey_1JV......kEtnlw"
//PaymentSheet Configuration
let clientSecret = response["clientSecret"].stringValue
let ephemeralSecret = response["EphemeralKey"].stringValue
let cusId = response["stripecustomerid"].stringValue
// MARK: Set your Stripe publishable key - this allows the SDK to make requests to Stripe for your account
STPAPIClient.shared.publishableKey = self.publishableKey
// MARK: Create a PaymentSheet instance
var configuration = PaymentSheet.Configuration()
configuration.merchantDisplayName = "Z*****"
configuration.customer = .init( id: cusId, ephemeralKeySecret: ephemeralSecret)
configuration.returnURL = "payments-example://stripe-redirect"
self.paymentSheet = PaymentSheet(
paymentIntentClientSecret: clientSecret,
configuration: configuration)
after this(payment initiation) I am getting log from stripe :
LOG ANALYTICS: ["product_usage": ["PaymentSheet"], "app_name": "Zucraz", "additional_info": [], "bindings_version": "21.8.1", "apple_pay_enabled": 0, "ocr_type": "none", "os_version": "14.4", "analytics_ua": "analytics.stripeios-1.0", "ui_usage_level": "partial", "publishable_key": "pk_test_51J9Te0LW.........tRQbRP2", "device_type": "iPhone12,1", "event": "mc_complete_init_customer", "app_version": "3.4"]
While calling this method - presenting PaymentSheet
func openPaymentSheet(){
// MARK: Start the checkout process
paymentSheet?.present(from: self) { paymentResult in
// MARK: Handle the payment result
switch paymentResult {
case .completed:
self.displayAlert("Your order is confirmed!")
case .canceled:
print("Canceled!")
case .failed(let error):
print(error)
self.displayAlert("Payment failed: \n\(error.localizedDescription)")
}
}
}
Getting this error
Error Domain=com.stripe.lib Code=50 "There was an unexpected error -- try again in a few seconds" UserInfo={NSLocalizedDescription=There was an unexpected error -- try again in a few seconds, com.stripe.lib:ErrorMessageKey=No valid API key provided. Set `STPAPIClient.shared().publishableKey` to your publishable key, which you can find here: https://stripe.com/docs/keys, com.stripe.lib:StripeErrorTypeKey=invalid_request_error, com.stripe.lib:StripeErrorCodeKey=}
There is nowhere defined in documentation to set STPAPIClient.shared().publishableKey.
still, I tried to set STPAPIClient.shared.publishableKey in my viewcontroller, still getting the error.
Thanks in advance
complete class code:
import UIKit
import SwiftyJSON
import FirebaseAnalytics
import Stripe
import PassKit
class ReviewOrderViewC: UIViewController,UITableViewDelegate,UITableViewDataSource{
#IBOutlet weak var viewForEmptyCart: UIView!
#IBOutlet weak var lblCity: UILabel!
#IBOutlet weak var lblNsmr: UILabel!
#IBOutlet weak var lblAdress: UILabel!
#IBOutlet weak var lblMobile: UILabel!
var responseData : JSON = []
#IBOutlet weak var tblReview: UITableView!
#IBOutlet weak var btnCod: UIButton!
#IBOutlet weak var btnOnlinePayment: UIButton!
#IBOutlet weak var lblApplyCoupon: UILabel!
#IBOutlet weak var viewForApplyCoupon: UIView!
#IBOutlet weak var txtCouponCode: UITextField!
#IBOutlet weak var lblCartTotalAmount: UILabel!
#IBOutlet weak var lblTotalAmount: UILabel!
#IBOutlet weak var viewBlankForCoupn: UIView!
var paymentType = "cod"
var couponCode = ""
#IBOutlet weak var lblEmptyCartText: UILabel!
#IBOutlet weak var lblAddInCartText: UILabel!
#IBOutlet weak var btnContinueSaida: CustomButton!
#IBOutlet weak var lblReviewOrder: UILabel!
#IBOutlet weak var lblMobileText: UILabel!
#IBOutlet weak var btnEditChange: UIButton!
#IBOutlet weak var lblOnlineText: UILabel!
#IBOutlet weak var lblCODText: UILabel!
#IBOutlet weak var lblPaymentMethodText: UILabel!
#IBOutlet weak var lblPriceDetailsText: UILabel!
#IBOutlet weak var lblCartTotalText: UILabel!
#IBOutlet weak var lblTotalAmountText: UILabel!
#IBOutlet weak var btnProcedd: CustomButton!
#IBOutlet weak var lblCouponText: UILabel!
#IBOutlet weak var btnApplyCoupon: UIButton!
#IBOutlet weak var lblDelivery: UILabel!
#IBOutlet weak var lblDeliveryText: UILabel!
#IBOutlet weak var lblDelTime: UILabel!
#IBOutlet weak var lblDiscountText: UILabel!
#IBOutlet weak var lblDiscount: UILabel!
#IBOutlet weak var lblFreeDel: UILabel!
#IBOutlet weak var lblCreditText: UILabel!
#IBOutlet weak var lblCreditPointText: UILabel!
#IBOutlet weak var btnRemoveCoupon: UIButton!
var addressData : JSON = []
var couponAmt = "0"
//For Stripe
var customerContext : STPCustomerContext?
var paymentContext : STPPaymentContext?
var isSetShipping = false
var paymentSheet: PaymentSheet?
var clientSecret = ""
var ephemeralKeySecret = ""
var paymentSheetFlowController: PaymentSheet.FlowController!
#IBOutlet weak var buyButton: UIButton!
#IBOutlet weak var paymentMethodButton: UIButton!
#IBOutlet weak var paymentMethodImage: UIImageView!
let publishableKey = "pk_test_51J***************bRP2"
override func viewDidLoad() {
super.viewDidLoad()
self.orderReview()
viewForApplyCoupon.isHidden = true
viewBlankForCoupn.isHidden = true
//Add Tap Gesture on Blank view to hide apply Coupon
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
viewBlankForCoupn.addGestureRecognizer(tap)
viewForApplyCoupon.layer.cornerRadius = 8
viewForApplyCoupon.clipsToBounds = true
btnCod.setImage(#imageLiteral(resourceName: "radio"), for: .normal)
// viewForEmptyCart.isHidden = true
lblReviewOrder.text = "reviewOrder".localizableSting()
lblMobileText.text = "mobile".localizableSting() + " :"
btnEditChange.setTitle("edit".localizableSting(), for: .normal)
lblPaymentMethodText.text = "paymentMethod".localizableSting()
lblCODText.text = "cod".localizableSting()
lblOnlineText.text = "online".localizableSting()
lblApplyCoupon.text = "applyCoupon".localizableSting()
lblPriceDetailsText.text = "priceDetails".localizableSting()
lblCartTotalText.text = "cartTotal".localizableSting()
lblTotalAmountText.text = "total".localizableSting()
btnProcedd.setTitle("proceedReview".localizableSting(), for: .normal)
lblEmptyCartText.text = "blankCartText".localizableSting()
lblAddInCartText.text = "addInCartText".localizableSting()
btnContinueSaida.setTitle("continueSaida".localizableSting(), for: .normal)
lblCouponText.text = "coupon".localizableSting()
txtCouponCode.placeholder = "txtCoupon".localizableSting()
btnApplyCoupon.setTitle("apply".localizableSting(), for: .normal)
btnOnlinePayment.isEnabled = true
self.lblDeliveryText.text = "deliveryCharges".localizableSting()
self.lblNsmr.text = self.addressData["fname"].stringValue + " " + self.addressData["lname"].stringValue
self.lblAdress.text = "\(self.addressData["address"].stringValue), \(self.addressData["state"].stringValue), \(self.addressData["city"].stringValue)"
self.lblMobile.text = self.addressData["mobileno"].stringValue
if NetworkManeger.getWalletStatus() == "0" {
lblCreditText.isHidden = true
lblCreditPointText.isHidden = true
}else{
lblCreditText.isHidden = false
lblCreditPointText.isHidden = false
}
self.intiateStripePayment()
}
#objc func handleTap(_ sender: UITapGestureRecognizer? = nil) {
// handling code
viewForApplyCoupon.isHidden = true
viewBlankForCoupn.isHidden = true
}
#IBAction func btnCODAction(_ sender: Any) {
paymentType = "cod"
btnCod.setImage(#imageLiteral(resourceName: "radio"), for: .normal)
btnOnlinePayment.setImage(#imageLiteral(resourceName: "contact_us_icon-1"), for: .normal)
}
#IBAction func btnOnlineAction(_ sender: Any) {
if self.responseData["totalcost"].floatValue > 0 {
paymentType = "online"
btnOnlinePayment.setImage(#imageLiteral(resourceName: "radio"), for: .normal)
btnCod.setImage(#imageLiteral(resourceName: "contact_us_icon-1"), for: .normal)
}
}
#IBAction func btnApplyCouponAction(_ sender: Any) {
//Show blank view and coupon code view
viewForApplyCoupon.isHidden = false
viewBlankForCoupn.isHidden = false
}
#IBAction func btnApplyCouponCode(_ sender: Any) {
//Call after response from API
couponCode = txtCouponCode.text ?? ""
txtCouponCode.resignFirstResponder()
//orderReview()
addCoupon()
viewForApplyCoupon.isHidden = true
viewBlankForCoupn.isHidden = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.responseData["productdetails"].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewOrderTableViewCell", for: indexPath) as! ReviewOrderTableViewCell
let imgURLString = self.responseData["productdetails"][indexPath.row]["imageurl"].stringValue
let newImageUrlStr = imgURLString.replacingOccurrences(of: " ", with: "%20")
let imageUrl = URL(string:newImageUrlStr)
cell.imgCartProduct.af_setImage(withURL:imageUrl!)
cell.lblCartProductName.text = self.responseData["productdetails"][indexPath.row]["productname"].stringValue
cell.lblPrice.text = self.responseData["productdetails"][indexPath.row]["sellingprice"].stringValue + " " + "JD".localizableSting()
cell.lblQuantity.text = self.responseData["productdetails"][indexPath.row]["qty"].stringValue
cell.lblBySaidaText.text = "bySaida".localizableSting()
cell.lblSizeText.text = "size".localizableSting() + " : "
cell.lblSize.text = self.responseData["productdetails"][indexPath.row]["size"].stringValue
cell.lblQtyText.text = "qty".localizableSting() + " : "
cell.btnRemove.addTarget(self, action: #selector(remove(sender:)), for: .touchUpInside)
cell.btnRemove.tag = indexPath.row
return cell
}
#objc func remove(sender: UIButton) {
let altMessage = UIAlertController(title: "ZUCRAZ", message: "Remove this item from cart.", preferredStyle: UIAlertController.Style.alert)
altMessage.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
_ in
if NetworkManeger.isConnectedToNetwork(){
let cartId = NetworkManeger.getCartId()
let productId = self.responseData["productdetails"][sender.tag]["pid"].stringValue
NetworkManeger.postRequest(remainingUrl: "deleteCartProduct.php", parameters: ["cartid": cartId, "pid": productId]) { (response) in
if response["status"].intValue == 200 {
self.orderReview()
}else{
NetworkManeger.showAlertWithMsg(vc: self, msg: response["msg"].stringValue)
}
}
}else{
let altMessage = UIAlertController(title: "ZUCRAZ", message: "Please check internet connection!", preferredStyle: UIAlertController.Style.alert)
altMessage.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(altMessage, animated: true, completion: nil)
}
}))
altMessage.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
self.present(altMessage, animated: true, completion: nil)
}
#IBAction func btnBack(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
#IBAction func btnProceed(_ sender: UIButton) {
self.openPaymentSheet()
}
//MARKS: API HIT
func intiateStripePayment(){
NetworkManeger.postRequest(remainingUrl: "stripepaymentinitiate.php", parameters: ["cartid": NetworkManeger.getCartId(), "user_id" : NetworkManeger.getUserId()]) { (response) in
if response["status"].intValue == 200 {
//Get ephmeral Key and clientSecret
self.clientSecret = response["clientSecret"].stringValue
// self.clientSecret = response["paymentintent"][0]["secret"].stringValue
self.ephemeralKeySecret = response["EphemeralKey"][0]["id"].stringValue
let cusId = NetworkManeger.getStripCustomerId()
// MARK: Set your Stripe publishable key - this allows the SDK to make requests to Stripe for your account
STPAPIClient.shared.publishableKey = self.publishableKey
// MARK: Create a PaymentSheet instance
var configuration = PaymentSheet.Configuration()
configuration.merchantDisplayName = "Zucraz"
configuration.customer = .init(
id: cusId, ephemeralKeySecret: self.ephemeralKeySecret)
configuration.returnURL = "payments-example://stripe-redirect"
self.paymentSheet = PaymentSheet(
paymentIntentClientSecret: self.clientSecret,
configuration: configuration)
DispatchQueue.main.async {
self.buyButton.isEnabled = true
}
}
}
}
func openPaymentSheet(){
// MARK: Start the checkout process
self.paymentSheet?.present(from: self) { paymentResult in
// MARK: Handle the payment result
switch paymentResult {
case .completed:
self.displayAlert("Your order is confirmed!")
case .canceled:
print("Canceled!")
case .failed(let error):
print(error)
self.displayAlert("Payment failed: \n\(error.localizedDescription)")
}
}
}
func displayAlert(_ message: String) {
let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in
alertController.dismiss(animated: true) {
self.navigationController?.popViewController(animated: true)
}
}
alertController.addAction(OKAction)
present(alertController, animated: true, completion: nil)
}
func orderReview(){
self.responseData = []
NetworkManeger.postRequest(remainingUrl: "orderReviewAPI.php", parameters: ["cartid": NetworkManeger.getCartId(), "user_id" : NetworkManeger.getUserId() , "coupondiscount" : couponCode, "applang" : NetworkManeger.getAppLang(), "iswalletused" : NetworkManeger.getWalletStatus(), "address_id" : self.addressData["address_id"].stringValue]) { }
}
func addCoupon(){
NetworkManeger.postRequest(remainingUrl: "cartcouponapply.php", parameters: ["cartid": NetworkManeger.getCartId(), "user_id" : NetworkManeger.getUserId() , "promocode" : couponCode, "cartvalue" : self.responseData["subtotal"].stringValue]) { }
}
Don't get confused by Error : "Set STPAPIClient.shared().publishableKey to your publishable key".
Nothing to do with this.
Check your keys if got this kind of error.
The EphemeralKey must look like: ek_test_xxx (secret).
I just want to get all the values of response variable in (Agent view controller class) when I try to get using object it returns nil I have tried in many ways but still getting nil....in agent view controller I'm assigning all those runtime values to uitextview
import UIKit
class LoginViewController: UIViewController {
weak var delegateL:AgentprofileViewController!
var user : [UserModel] = []
let mm = Usersmanager()
//MARK:-- Outlets
#IBOutlet public weak var txtPhoneNumber: UITextField!
#IBOutlet public weak var txtPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
//Functions
#IBAction func btnLogin(_ sender: Any) {
//below is the response variable which I want in other (Agent view controller class)
let response = mm.alluser(phoneNo: txtPhoneNumber.text!, Password: txtPassword.text!)
if response.count ?? 0 > 0
{
//uncom
delegateL.runtimeid? = response[0].u_id
delegateL.runtimename? = response[0].u_name!
delegateL.runtimephone? = response[0].phoneNumber!
delegateL.runtimepassword? = response[0].password!
delegateL.runtimeaddress? = response[0].address!
delegateL.runtimerid? = response[0].r_id!
delegateL.runtimername? = response[0].r_name!
print(response[0].u_id)
print(response[0].u_name)
print(response[0].password)
print(response[0].phoneNumber)
print(response[0].address)
print(response[0].r_id)
print(response[0].r_name)
if response[0].r_name=="Agent"
{
let next : tabViewController = self.storyboard?.instantiateViewController(withIdentifier: "tabViewController") as! tabViewController
self.navigationController?.pushViewController(next, animated: true)
showalertforloginsuccess()
print("Login Successfull")
//Passing view to the next view if login is succesfull
// let next : HomeViewController = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
// self.navigationController?.pushViewController(next, animated: true)
}
else{
print("Login Succesfull but login person is not agent")
}
}
else
{
showalertforloginfail()
print("Not Login")
}
}
This one is Agent Controller class where I want to access response variable values
import UIKit
class AgentprofileViewController: UIViewController {
#IBOutlet weak var txtid: UITextView!
#IBOutlet weak var txtname: UITextView!
#IBOutlet weak var txtphone: UITextView!
#IBOutlet weak var txtrid: UITextView!
#IBOutlet weak var txtpass: UITextView!
#IBOutlet weak var txtrname: UITextView!
#IBOutlet weak var txtaddress: UITextView!
var runtimeid:Int? = 0
var runtimename:String?=""
var runtimepassword:String?=""
var runtimeaddress:String?=""
var runtimephone:String?=""
var runtimerid:Int? = 0
var runtimername:String?=""
override func viewDidLoad() {
super.viewDidLoad()
//below all runtime variables contain nil
print(runtimeid)
print(runtimename)
print(runtimeaddress)
print(runtimepassword)
print(runtimephone)
print(runtimerid)
print(runtimername)
result()
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.navigationItem.title = "Profile"
}
func result() {
//uncom
//below is the error(txtid...contain nill while wrapping)
txtid.text = "\(String(describing: runtimeid))"
txtname.text = runtimename
txtpass.text = runtimepassword
txtphone.text = runtimephone
txtaddress.text = runtimeaddress
txtrid.text = "\(String(describing: runtimerid))"
txtrname.text = runtimername
}
}
I am working tirelessly on an app and I'm pretty new to Swift. I am trying to take data from an API call after user entry on the landing screen and then present the results of the API call on the modal popover that comes up to display the data that the user wanted. This is an aviation weather app; The user enters something like "KDAB" and the API returns the current aviation weather at that airport. I have a bunch of labels set up for different values and can print them to console after a search but can't seem to get them printed in the VC. I have tried some destination.segue fixes but don't see why I would use them - the data is coming directly from the decoded JSON. Help would be appreciated!
I am trying to display on the ReportViewController in each of the value labels. I.E. Wind speed in the windSpeedValueLabel by utilizing the .text property.
Right now, nothing changes from the default labels on the actual ReportViewController.
Thanks again.
My code:
//
// ReportViewController.swift
// AvWx Pro
//
// Created by Grayson Bertaina on 9/22/20.
//
import UIKit
class ReportViewController: UIViewController, WeatherManagerDelegate {
var weatherManager = WeatherManager()
#IBOutlet weak var flightRulesTitleLabel: UILabel!
#IBOutlet weak var flightRulesValueLabel: UILabel!
#IBOutlet weak var visibilityValueLabel: UILabel!
#IBOutlet weak var altimeterValueLabel: UILabel!
#IBOutlet weak var cloudsTitleLabel: UILabel!
#IBOutlet weak var cloudsType1Label: UILabel!
#IBOutlet weak var cloudsAltitude1Label: UILabel!
#IBOutlet weak var cloudsType2Label: UILabel!
#IBOutlet weak var cloudsAltitude2Label: UILabel!
#IBOutlet weak var cloudsType3Label: UILabel!
#IBOutlet weak var cloudsAltitude3Label: UILabel!
#IBOutlet weak var windGTextLabel: UILabel!
#IBOutlet weak var windSpeedValueLabel: UILabel!
#IBOutlet weak var windGustValueLabel: UILabel!
#IBOutlet weak var windFromTextLabel: UILabel!
#IBOutlet weak var windDirectionValueLabel: UILabel!
#IBOutlet weak var remarksValueLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel) {
DispatchQueue.main.async {
self.flightRulesValueLabel.text = weather.flightRules
self.cloudsType1Label.text = weather.lowestCloudsType
}
}
func didFailWithError(error: Error) {
print(error)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
}
//
// ViewController.swift
// AvWx Pro
//
// Created by Grayson Bertaina on 9/21/20.
//
import UIKit
class WxViewController: UIViewController, UITextFieldDelegate, WeatherManagerDelegate {
var weatherManager = WeatherManager()
#IBOutlet weak var stationSearch: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
weatherManager.delegate = self
stationSearch.delegate = self
}
#IBAction func searchPressed(_ sender: Any) {
print(stationSearch.text!)
stationSearch.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print(stationSearch.text!)
stationSearch.endEditing(true)
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if let station = stationSearch.text {
weatherManager.fetchWeather(stationICAO: station)
}
stationSearch.text = ""
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if stationSearch.text != "" {
return true
} else {
stationSearch.placeholder = "Type an ICAO"
return false
}
}
func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel) {
print(weather.flightConditions)
}
func didFailWithError(error: Error) {
print(error)
}
}
//
// WeatherManager.swift
// AvWx Pro
//
// Created by Grayson Bertaina on 9/21/20.
//
import Foundation
protocol WeatherManagerDelegate {
func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel)
func didFailWithError(error: Error)
}
struct WeatherManager {
let weatherURL = "https://avwx.rest/api/metar/"
var delegate : WeatherManagerDelegate?
func fetchWeather (stationICAO: String) {
let urlString = "\(weatherURL)\(stationICAO)?token=OVi45FiTDo1LmyodShfOfoizNe5m9wyuO6Mkc95AN-c"
performRequest(with: urlString)
}
func performRequest (with urlString: String) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
if let safeData = data {
if let weather = self.parseJSON(safeData) {
self.delegate?.didUpdateWeather(self, weather: weather)
}
}
}
task.resume()
print(urlString)
}
}
func parseJSON(_ weatherData: Data) -> WeatherModel? {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let clouds = decodedData.clouds
let lowCloudsType = (clouds.count > 0 ? clouds[0]?.type : nil) ?? "N/A"
let midCloudsType = (clouds.count > 1 ? clouds[1]?.type : nil) ?? "N/A"
let highCloudsType = (clouds.count > 2 ? clouds[2]?.type : nil) ?? "N/A"
let lowCloudsAlt = (clouds.count > 0 ? clouds[0]?.altitude : nil) ?? 0
let midCloudsAlt = (clouds.count > 1 ? clouds[1]?.altitude : nil) ?? 0
let highCloudsAlt = (clouds.count > 2 ? clouds[2]?.altitude : nil) ?? 0
let reportingStationVar = decodedData.station ?? "N/A"
let windGustValue = decodedData.wind_gust?.value ?? 0
let windSpeedValue = decodedData.wind_speed?.value ?? 0
let windDirectionValue = decodedData.wind_direction?.value ?? 999
let visibilityValue = decodedData.visibility?.value ?? 0
let flightRulesValue = decodedData.flight_rules ?? "N/A"
let weather = WeatherModel(lowestCloudsType: lowCloudsType , lowestCloudsAlt: lowCloudsAlt, middleCloudsType: midCloudsType , middleCloudsAlt: midCloudsAlt, highestCloudsType: highCloudsType , highestCloudsAlt: highCloudsAlt, reportingStation: reportingStationVar, windGust: windGustValue, windSpeed: windSpeedValue, windDirection: windDirectionValue, visibility: visibilityValue, flightRules: flightRulesValue)
return weather
} catch {
delegate?.didFailWithError(error: error)
return nil
}
}
}
//
// WeatherData.swift
// AvWx Pro
//
// Created by Grayson Bertaina on 9/21/20.
//
import Foundation
struct WeatherData: Codable {
let clouds: [Clouds?]
let flight_rules: String?
let remarks: String?
let wind_speed: WindSpeed?
let wind_gust: WindGust?
let wind_direction: WindDirection?
let visibility: Visibility?
let station: String?
}
struct Clouds: Codable {
let type: String
let altitude: Int
}
struct WindSpeed: Codable {
let value: Int
}
struct WindGust: Codable {
let value: Int
}
struct WindDirection: Codable {
let value: Int
}
struct Visibility: Codable {
let value: Int
}
Thanks again.
First, on WeatherManager, declare your delegate as weak to avoid reference cycle
weak var delegate : WeatherManagerDelegate?
Second, after you decode the data, you have to call the delegate and pass the data, in this case,the WeatherModel you just created using one of your delegate methods
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let clouds = decodedData.clouds
let lowCloudsType = (clouds.count > 0 ? clouds[0]?.type : nil) ?? "N/A"
let midCloudsType = (clouds.count > 1 ? clouds[1]?.type : nil) ?? "N/A"
let highCloudsType = (clouds.count > 2 ? clouds[2]?.type : nil) ?? "N/A"
let lowCloudsAlt = (clouds.count > 0 ? clouds[0]?.altitude : nil) ?? 0
let midCloudsAlt = (clouds.count > 1 ? clouds[1]?.altitude : nil) ?? 0
let highCloudsAlt = (clouds.count > 2 ? clouds[2]?.altitude : nil) ?? 0
let reportingStationVar = decodedData.station ?? "N/A"
let windGustValue = decodedData.wind_gust?.value ?? 0
let windSpeedValue = decodedData.wind_speed?.value ?? 0
let windDirectionValue = decodedData.wind_direction?.value ?? 999
let visibilityValue = decodedData.visibility?.value ?? 0
let flightRulesValue = decodedData.flight_rules ?? "N/A"
let weather = WeatherModel(lowestCloudsType: lowCloudsType , lowestCloudsAlt: lowCloudsAlt, middleCloudsType: midCloudsType , middleCloudsAlt: midCloudsAlt, highestCloudsType: highCloudsType , highestCloudsAlt: highCloudsAlt, reportingStation: reportingStationVar, windGust: windGustValue, windSpeed: windSpeedValue, windDirection: windDirectionValue, visibility: visibilityValue, flightRules: flightRulesValue)
delegate?.didUpdateWeather(self, weather: weather)
return weather
} catch {
delegate?.didFailWithError(error: error)
return nil
}
On ReportViewController, assign self as your WeatherManagerDelegate on viewDidLoad(), then you have to implement the delegate function didUpdateWeather by updating your labels with corresponding values -- which you already started
class ReportViewController: UIViewController, WeatherManagerDelegate {
var weatherManager = WeatherManager()
#IBOutlet weak var flightRulesTitleLabel: UILabel!
#IBOutlet weak var flightRulesValueLabel: UILabel!
#IBOutlet weak var visibilityValueLabel: UILabel!
#IBOutlet weak var altimeterValueLabel: UILabel!
#IBOutlet weak var cloudsTitleLabel: UILabel!
#IBOutlet weak var cloudsType1Label: UILabel!
#IBOutlet weak var cloudsAltitude1Label: UILabel!
#IBOutlet weak var cloudsType2Label: UILabel!
#IBOutlet weak var cloudsAltitude2Label: UILabel!
#IBOutlet weak var cloudsType3Label: UILabel!
#IBOutlet weak var cloudsAltitude3Label: UILabel!
#IBOutlet weak var windGTextLabel: UILabel!
#IBOutlet weak var windSpeedValueLabel: UILabel!
#IBOutlet weak var windGustValueLabel: UILabel!
#IBOutlet weak var windFromTextLabel: UILabel!
#IBOutlet weak var windDirectionValueLabel: UILabel!
#IBOutlet weak var remarksValueLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
weatherManager.delegate = self
}
func didUpdateWeather(_ weatherManager: WeatherManager, weather: WeatherModel) {
DispatchQueue.main.async {
self.flightRulesValueLabel.text = weather.flightRules
self.cloudsType1Label.text = weather.lowestCloudsType
}
}
I have a small calculator built into 3 different views. On all the calcuulators, I would like to have the keyboard disappear upon either tapping anywhere on the screen or upon pressing the button to calucate a value. Ive researched several sources and have become confused on how to implement any code for this. My calculator code is below. Thanks in advance!
class Calculators: UIViewController {
#IBOutlet var fluidIn: UITextField!
#IBOutlet var timeIn: UITextField!
#IBOutlet var dripIn: UITextField!
#IBOutlet var dripResult: UILabel!
#IBOutlet var weight: UITextField!
#IBOutlet var etomidate: UILabel!
#IBOutlet var succ: UILabel!
#IBOutlet var roc: UILabel!
#IBOutlet var ketamine: UILabel!
#IBOutlet var lbsIn: UITextField!
#IBOutlet var KgIn: UITextField!
#IBOutlet var KgOut: UILabel!
#IBOutlet var LbsOut: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func calculate(sender: UIButton) {
let Number2 = Double(weight.text!)
let etommult = (0.3)
let etomresult = Number2! * etommult
etomidate.text = "\(etomresult)"
etomidate.text = NSString(format:"%2.1f mg",etomresult)as String;
let Number3 = Double(weight.text!)
let succmult = (2.0)
let succresult = Number3! * succmult
succ.text = "\(succresult)"
succ.text = NSString(format: "%2.1f mg",succresult)as String;
let Number4 = Double(weight.text!)
let rocmult = (1.0)
let rocresult = Number4! * rocmult
roc.text = "\(rocresult)"
roc.text = NSString(format: "%2.1f mg",rocresult)as String;
let Number5 = Double(weight.text!)
let fentmult = (2.0)
let fentresult = Number5! * fentmult
ketamine.text = "\(fentresult)"
ketamine.text = NSString(format: "%2.1f mg",fentresult)as String;
}
#IBAction func KgConv(_ sender: Any) {
let kg = Double(lbsIn.text!)
let kgmult = (2.2)
let kgresult = kg! / kgmult
KgOut.text = "\(kgresult)"
KgOut.text = NSString(format: "%2.1f kg",kgresult)as String;
}
#IBAction func LbsConv(_ sender: Any) {
let lbs = Double(KgIn.text!)
let lbsmult = (2.2)
let lbsresult = lbs! * lbsmult
LbsOut.text = "\(lbsresult)"
LbsOut.text = NSString(format: "%2.1f kg",lbsresult)as String;
}
#IBAction func dripCalc(_ sender: Any) {
let cc = Double(fluidIn.text!)
let min = Double(timeIn.text!)
let fct = Double(dripIn.text!)
let dripRes = (cc! * fct!) / min!
dripResult.text = "\(dripRes)"
dripResult.text = NSString(format: "%2.1f gtts/min",dripRes)as String;
}
Call the below code whenever and wherever you want to hide the keyboard in viewController.
view.endEditing(true)
I have stored a data as below:-
viewmodel:-
typealias dummyDataSource1 = QM_RestaurtantDataSourceModel
extension dummyDataSource1{
func getJsonDataStored1() ->Array<Dictionary<String,String>>{
let jsonArray = [["name":"Anjapar","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Musheireb,Qatar"],["name":"Aryaas","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Al Muntazah,Qatar"],["name":"India Coffee","imageurl":"","city":"Doha,Qatar"],["name":"Saravana","imageurl":"https://www.planwallpaper.com/static/images/9-credit-1.jpg","city":"Al Muntazah,Qatar"],["name":"Tea Time","imageurl":"","city":"Old Airport,Qatar"]] as Array<Dictionary<String,String>>
return jsonArray
}
i need to display the imageurl:-image in UIImgeView .How to do
i tried with code:-
#IBOutlet weak var name: UILabel!
#IBOutlet weak var city: UILabel!
#IBOutlet weak var imageurl: UILabel!
#IBOutlet weak var images: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setRestaurtantData(restaurtant:QM_RestaurtantModel)
{
self.name.text = restaurtant.name
self.city.text = restaurtant.city
self.imageurl.text = restaurtant.imageurl
}
my model:-
var name :String!
var city :String!
var imageurl :String!
init?(dictionary :JSONDictionary) {
guard let name = dictionary["name"] as? String,
let imageurl = dictionary["imageurl"] as? String,
let city = dictionary["city"] as? String else {
return
}
self.name = name
self.city = city
self.imageurl = imageurl
}
i getting the value as string ,but i need to display the image