My IAP isn't working. Bugs at func Paymentqueue - view

When I click on either of my IAPS, a message appears saying the IAP was already purchased (which is not the case) and will be restored for free, then nothing happens, the IAP doesn't execute.
Here is what I get in my console:
No Value.
IAP is enabled, loading...
true
Product Request
Product Added
IAP id
Remove Ads
Removes ads from the app.
2
Buy: IAP id
Add Payment
nil
default: Error
Here is my code:
GameViewController.Swift
import UIKit
import StoreKit
class GameViewController: UIViewController, ADBannerViewDelegate, SKProductsRequestDelegate, SKPaymentTransactionObserver, GKGameCenterControllerDelegate,GADBannerViewDelegate{
#IBOutlet var outRemoveAds: UIButton!
#IBOutlet var outRestorePurchases: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if NSUserDefaults.standardUserDefaults().objectForKey("val") != nil {
print("Has a value.")
banner.removeFromSuperview()
bannerGoogle.removeFromSuperview()
outRemoveAds.removeFromSuperview()
outRestorePurchases.removeFromSuperview()
removeInterFrom = 1
}
else {
print("No Value.")
}
if(SKPaymentQueue.canMakePayments()){
print("IAP is enabled, loading...")
let productID:NSSet = NSSet(objects:"IAP id")
let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)
request.delegate = self
request.start()
}
else{
print("Please enable IAPS")
}
}
//IAP Ads
#IBAction func removeAds(sender: UIButton) {
for product in list{
let prodID = product.productIdentifier
if (prodID == "IAP id"){
p = product
buyProduct()
break
}
}
}
#IBAction func restorePurchases(sender: UIButton) {
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
//IAP Functions
var list = [SKProduct]()
var p = SKProduct()
func removeAds(){
banner.removeFromSuperview()
bannerGoogle.removeFromSuperview()
outRemoveAds.removeFromSuperview()
outRestorePurchases.removeFromSuperview()
let theValue = 10
NSUserDefaults.standardUserDefaults().setObject(theValue, forKey: "val")
NSUserDefaults.standardUserDefaults().synchronize()
}
func buyProduct(){
print("Buy: "+p.productIdentifier)
let pay = SKPayment (product: p)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment)
}
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
print("Product Request")
let myProduct = response.products
for product in myProduct{
print("Product Added")
print(product.productIdentifier)
print(product.localizedTitle)
print(product.localizedDescription)
print(product.price)
list.append(product as SKProduct)
}
}
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
print("Add Payment")
for transaction:AnyObject in transactions{
let trans = transaction as! SKPaymentTransaction
print(trans.error)
switch trans.transactionState{
case .Purchased:
print("IAP unlocked")
print(p.productIdentifier)
let prodID = p.productIdentifier as String
switch prodID{
case "IAP id":
print("Remove Ads")
removeAds()
default:
print("IAP not setup")
}
queue.finishTransaction(trans)
break
case .Failed:
print ("Buy error")
queue.finishTransaction(trans)
break
default:
print("default: Error")
break
}
}
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
print("Purchases Restored")
_ = []
for transaction in queue.transactions {
let t: SKPaymentTransaction = transaction as SKPaymentTransaction
let prodID = t.payment.productIdentifier as String
switch prodID{
case "IAP id":
print("Remove Ads")
removeAds()
default:
print("IAP not setup")
}
}
}
func finishTransaction(trans:SKPaymentTransaction){
print("Finshed Transaction")
}
func paymentQueue(queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
print("Remove Transaction")
}
}
MenuViewController.swift
import UIKit
import StoreKit
import Social
class MenuViewController: UIViewController, SKProductsRequestDelegate,SKPaymentTransactionObserver {
#IBOutlet var outRestart: UIButton!
#IBOutlet var outBuy: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if(SKPaymentQueue.canMakePayments()){
print("IAP is enabled, loading...")
let productID:NSSet = NSSet(objects:"IAP id")
let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)
request.delegate = self
request.start()
}
else{
print("Please enable IAPS")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buy(sender: UIButton) {
for product in list{
let prodID = product.productIdentifier
if (prodID == "IAP id"){
p = product
buyProduct()
break
}
}
}
//IAP Functions
var list = [SKProduct]()
var p = SKProduct()
func keepOn(){
buyornot = 1
Back()
}
func buyProduct(){
print("Buy: "+p.productIdentifier)
let pay = SKPayment (product: p)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment)
}
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
print("Product Request")
let myProduct = response.products
for product in myProduct{
print("Product Added")
print(product.productIdentifier)
print(product.localizedTitle)
print(product.localizedDescription)
print(product.price)
list.append(product as SKProduct)
}
}
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
print("Add Payment")
for transaction:AnyObject in transactions{
let trans = transaction as! SKPaymentTransaction
print(trans.error)
switch trans.transactionState{
case .Purchased:
print("IAP unlocked")
print(p.productIdentifier)
let prodID = p.productIdentifier as String
switch prodID{
case "IAP id":
print("Keep on")
keepOn()
default:
print("IAP not setup")
}
queue.finishTransaction(trans)
break
case .Failed:
print ("Buy error")
queue.finishTransaction(trans)
break
default:
print("default: Error")
break
}
}
}
func finishTransaction(trans:SKPaymentTransaction){
print("Finshed Transaction")
}
func paymentQueue(queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
print("Remove Transaction")
}

I found the solution !
Delete
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
everywhere you have it and put it once (ONLY ONCE) in a place where it will be executed each time your app boots up ( I put it in viewDidLoad()).
This will check for all unfinished transactions and terminate them once the app has loaded, thus removing any possible errors before your users triggers an IAP.
(If this answer, or this question helped you, don't forget to upvote ;))
P.S.: Also, this wasn't my issue, but make sure to finishTransaction() for each PurchaseState like here:
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
print("Add Payment")
for transaction:AnyObject in transactions{
let trans = transaction as! SKPaymentTransaction
print(trans.error)
switch trans.transactionState{
case .Purchased:
print("IAP unlocked")
print(p.productIdentifier)
let prodID = p.productIdentifier as String
switch prodID{
case "IAP id":
print("Keep on")
keepOn()
default:
print("IAP not setup")
}
queue.finishTransaction(trans)
break
case .Failed:
print ("Buy error")
queue.finishTransaction(trans)
break
default:
print("default: Error")
break
}
}
}
Never forget this:
queue.finishTransaction(trans)

Related

to look at the suffix of the text of the text field

I want to let the people login to the certain domain, but it always shows a error.
Cannot convert value of type 'String' to expected argument type 'Int').
how can I deal with it?
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
#IBOutlet var emailTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
#IBAction func signUp(_ sender: Any) {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (result, error) in
if error != nil{
print(error)
}else{
self.performSegue(withIdentifier: "createdUser", sender: self)
}
}
}
#IBAction func signIn(_ sender: Any) {
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (result, error) in
if error != nil{
print(error)
}else{
var hi = self.emailTextField.text
if hi?.suffix("#hkugac.edu.hk"){ //error here
self.performSegue(withIdentifier: "logged", sender: self)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Try using the hasSuffix method. https://developer.apple.com/documentation/swift/string/1541149-hassuffix
var hi = self.emailTextField.text
if let mail = hi, mail.haSuffix("#hkugac.edu.hk")
{
self.performSegue(withIdentifier: "logged", sender: self)
}
else
{
// Dome some error handling here.
}
Also, I think it would be better to check the mail before you call the signIn function.

Can't set default value UIPicker swift 2

I have a swift project with a custom cell from a tableview, ans inside it I have a label to display the value of a UIPicker. The UiPicker appear in the keyboard when you press the label, I wan't to be able to set default values to my UIPicker, I tried a lot of differents technics with the 2 methods :
selectRow(), without success, here is my CustomCell code :
import UIKit
class CustomCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var answer: UITextField!
var delegate: QuestionSelectorCellDelegate?
var pickOption: [String] = []
var pickerView:UIPickerView = UIPickerView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBAction func editBeginQuestionSelectorCell(sender: UITextField) {
pickerView = UIPickerView()
pickerView.delegate = self
sender.inputView = pickerView
}
func displayBlock(block: Block){
if block.answers != nil {
pickOption = block.answers! // block.answers! = ["blue","red","green"] for example
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row < pickOption.count {
answer.text = pickOption[row]
delegate?.updateQuestionSelectorCell(self, rep: pickOption[row])
}
}
}
Updated your code.
You didn't set the pickerView.dataSource!
If i understood your question, you want an element to be selected by default, other than element at index 0.
I also added that.
import UIKit
class CustomCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var answer: UITextField!
var delegate: QuestionSelectorCellDelegate?
var pickOption: [String] = []
var pickerView:UIPickerView = UIPickerView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBAction func editBeginQuestionSelectorCell(sender: UITextField) {
pickerView = UIPickerView()
pickerView.delegate = self
// --- Thats what I added ---
pickerView.dataSource = self
let indexOfDefaultElement = 1 // Make sure that an element at this index exists
pickerView.selectRow(indexOfDefaultElement, inComponent: 0, animated: false)
sender.inputView = pickerView
}
func displayBlock(block: Block){
if block.answers != nil {
pickOption = block.answers! // block.answers! = ["blue","red","green"] for example
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row < pickOption.count {
answer.text = pickOption[row]
delegate?.updateQuestionSelectorCell(self, rep: pickOption[row])
}
}
}

Same view with valid reference which becoming nil when referenced from delegate

The func yesBtSetTextTo prints not nil when called from the grey button in the pink area, but the same func print nil when is called from the yellow button. I am lost on this one.
My main veiwController.swift does not have a prepareForSegue since I did not thing it is needed here.
The func in question is at the end of this code block,
MainBtVC.swift
protocol MainBtDelegate {
func yesBtSetTextTo(name: String)
}
class MainBtVC: UIViewController, MainBtDelegate {
#IBOutlet weak var yesBt: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func yesBtSetTextTo(name: String) {
print("called")
if yesBt == nil {
print("button is nil")
} else {
print("button not nil")
}
// yesBt.setTitle("Exit", forState: UIControlState.Normal)
}
#IBAction func yesBtTapped(sender: AnyObject) {
yesBtSetTextTo("dummy")
}
TopVC.swift
class TopVC: UIViewController {
var delegate: MainBtDelegate?
override func viewDidLoad() {
super.viewDidLoad()
delegate = MainBtVC()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func buttonTapped(sender: AnyObject) {
delegate?.yesBtSetTextTo("Exit")
}

AVPlayer Freezes once moved to background

I have the following code that loads a video and loops it. However, when pressing home and returning to the application the video freezes and will not play again. I feel like the answer is in the AppDelegate functions but can not seem to get them to work.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController, UIApplicationDelegate {
var videoPlayer: AVPlayer!
var playerLayer: AVPlayerLayer?
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")
let url = NSURL(fileURLWithPath: path!)
let playerItem = AVPlayerItem(URL: url)
self.videoPlayer = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: self.videoPlayer)
self.playerLayer!.frame = self.view.frame
self.videoPlayer!.play()
self.view.layer.addSublayer(self.playerLayer!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerDidReachEnd:"), name: AVPlayerItemDidPlayToEndTimeNotification, object:nil)
}
func playerDidReachEnd(notification: NSNotification) {
self.videoPlayer.seekToTime(kCMTimeZero)
self.videoPlayer.play()
}
func applicationWillResignActive(application: UIApplication) {
videoPlayer.pause()
}
func applicationDidBecomeActive(application: UIApplication) {
videoPlayer.play()
}
func applicationDidEnterBackground(application: UIApplication) {
videoPlayer.pause()
}
func applicationWillEnterForeground(application: UIApplication) {
videoPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Here is what I used to fix it.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController, UIApplicationDelegate {
var videoPlayer: AVPlayer!
var playerLayer: AVPlayerLayer?
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("video", ofType:"mp4")
let url = NSURL(fileURLWithPath: path!)
let playerItem = AVPlayerItem(URL: url)
self.videoPlayer = AVPlayer(playerItem: playerItem)
self.playerLayer = AVPlayerLayer(player: self.videoPlayer)
self.playerLayer!.frame = self.view.frame
self.videoPlayer!.play()
self.view.layer.addSublayer(self.playerLayer!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("continueVideo:"), name: "continueVideo", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playerDidReachEnd:"), name: AVPlayerItemDidPlayToEndTimeNotification, object:nil)
}
func playerDidReachEnd(notification: NSNotification) {
self.videoPlayer.seekToTime(kCMTimeZero)
self.videoPlayer.play()
}
func continueVideo(notification: NSNotification) {
self.videoPlayer.play()
}
func applicationWillResignActive(application: UIApplication) {
videoPlayer.pause()
}
func applicationDidBecomeActive(application: UIApplication) {
videoPlayer.play()
}
func applicationDidEnterBackground(application: UIApplication) {
videoPlayer.pause()
}
func applicationWillEnterForeground(application: UIApplication) {
videoPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
And the app delegate portion
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
NSNotificationCenter.defaultCenter().postNotificationName ("continueVideo", object:nil)
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
This is a simple fix, you need to create a NSNotification and call it from your AppDelegate:
func applicationWillEnterForeground(application: UIApplication) {
NSNotificationCenter.defaultCenter().postNotificationName("continueVideo", object: nil)
}
SWIFT3 Update
func applicationWillEnterForeground(_ application: UIApplication) {
// NOTE: Notification.Name raw value should be global
NotificationCenter.default.post(name: Notification.Name(rawValue: "com.yourappname.continueVideo"), object:self)
}
And the receive that notification in the normal way:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "<funcName>:", name: "continueVideo", object: nil)
SWIFT3 Update
NotificationCenter.default.addObserver(self, selector: #selector(<funcName>), name: Notification.Name(rawValue: "com.yourappname.continueVideo"), object: nil)

itemForActivityType not being called

i just made one wrapper class for share helper my code is as follow.
let activityVC = UIActivityViewController(activityItems: [message], applicationActivities: nil)
activityVC.setValue(subject, forKey: "subject")
activityVC.completionWithItemsHandler = {(activityType: String!, completed:Bool, objects:[AnyObject]!, error:NSError!) in
}
fromVC.presentViewController(activityVC, animated: true, completion: nil)
problem starts here, UIActivityItemSource methods not being call
override func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
switch activityType
{
case UIActivityTypeMail:
return msg
case UIActivityTypeMessage:
return msg
case UIActivityTypePostToFacebook:
return msg
case UIActivityTypePostToTwitter:
return strTwitterShare
default:
return msg
}
}
thanks for help
It should work if you use let activityVC = UIActivityViewController(activityItems: [self], applicationActivities: nil)
... then your message is provided inside your itemForActivityType method.

Resources