Category: software-development

Software development is the process of conceiving, specifying, designing, programming, documenting, testing, and bug fixing involved in creating and maintaining applications, frameworks, or other software components. Software development involves writing and maintaining the source code, but in a broader sense, it includes all processes from the conception of the desired software through to the final manifestation of the software, typically in a planned and structured process. Software development also includes research, new development, prototyping, modification, reuse, re-engineering, maintenance, or any other activities that result in software products.

  • Auto-renewable subscriptions with SwiftUI

    Auto-renewable subscriptions with SwiftUI

    Auto-renewable subscriptions with SwiftUI

    Read about App Store Server Integration in Laravel

    Auto-renewable subscriptions provide access to content, services, or premium features in your app on an ongoing basis. They automatically renew at the end of their duration until the user chooses to cancel. Subscriptions are available on iOS, iPadOS, macOS, watchOS, and tvOS.

    Great subscription apps justify the recurring payment by providing ongoing value and continually innovating the app experience. If you’re considering implementing the subscription model, plan to regularly update your app with feature enhancements or expanded content.

    To offer subscriptions, youʼll need to configure them in App Store Connect and use StoreKit APIs in your app. You’ll also need to assign each subscription to a subscription group (a group of subscriptions with different access levels, prices, and durations that people can choose from), then add details such as a name, price, and description. This information displays in the In-App Purchases section of your app’s product page on the App Store. Ensure that the subscriptions are available across all device types that your app supports. Consider allowing a way for subscribers to see the status of their subscription within your app, along with upgrade, crossgrade, and downgrade options, as well as a way to easily manage or turn off their auto-renewable subscription. Make sure to follow our design and review guidelines.

    To get ready:

    Before creating any subscription make sure you have done all these steps and all are showing Active status. 

    Auto-renewable subscriptions with SwiftUI

    Go here https://appstoreconnect.apple.com/agreements/#

    Creating subscriptions

    Go to app detail page and click on the In-App purchase link under Feature. 

    Select Auto-Renewable Subscription and click the Create button.

    Auto-renewable subscriptions with SwiftUI

    SwiftUI View-Model

    //
    //  AppStoreManager.swift
    //  ARSubscription
    //
    //  Created by Smin Rana on 2/1/22.
    //
    
    import SwiftUI
    import StoreKit
    import Combine
    
    class AppStoreManager: NSObject, ObservableObject, SKProductsRequestDelegate, SKPaymentTransactionObserver {
    
        @Published var products = [SKProduct]()
        
        override init() {
            super.init()
            
            SKPaymentQueue.default().add(self)
        }
        
        func getProdcut(indetifiers: [String]) {
            print("Start requesting products ...")
            let request = SKProductsRequest(productIdentifiers: Set(indetifiers))
            request.delegate = self
            request.start()
        }
        
        func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
            print("Did receive response")
                    
            if !response.products.isEmpty {
                for fetchedProduct in response.products {
                    DispatchQueue.main.async {
                        self.products.append(fetchedProduct)
                    }
                }
            }
            
            for invalidIdentifier in response.invalidProductIdentifiers {
                print("Invalid identifiers found: \(invalidIdentifier)")
            }
        }
        
        func request(_ request: SKRequest, didFailWithError error: Error) {
            print("Request did fail: \(error)")
        }
        
        // Transaction
        
        @Published var transactionState: SKPaymentTransactionState?
        
        func purchaseProduct(product: SKProduct) {
            if SKPaymentQueue.canMakePayments() {
                let payment = SKPayment(product: product)
                SKPaymentQueue.default().add(payment)
            } else {
                print("User can't make payment.")
            }
        }
        
        struct PaymentReceiptResponseModel: Codable {
            var status: Int
            var email: String?
            var password: String?
            var message: String?
        }
        
        func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
            for transaction in transactions {
                switch transaction.transactionState {
                case .purchasing:
                    self.transactionState = .purchasing
                case .purchased:
                    print("===============Purchased================")
                    UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
                    if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
                        FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
    
                        do {
                            let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
                            let receiptString = receiptData.base64EncodedString(options: [])
                            
                            // TODO: Send your receiptString to the server and verify with Apple
                            // receiptString should be sent to server as JSON
                            // {
                            //    "receipt" : receiptString
                            // }
                            
                            self.transactionState = .purchased // only if server sends successful response
                        }
                        catch { print("Couldn't read receipt data with error: " + error.localizedDescription) }
                    }
                case .restored:
                    UserDefaults.standard.setValue(true, forKey: transaction.payment.productIdentifier)
    
                    queue.finishTransaction(transaction)
                    print("==================RESTORED State=============")
                    self.transactionState = .restored
                case .failed, .deferred:
                    print("Payment Queue Error: \(String(describing: transaction.error))")
                    queue.finishTransaction(transaction)
                    self.transactionState = .failed
                default:
                    print(">>>> something else")
                    queue.finishTransaction(transaction)
                }
            }
        }
        
        func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
            print("===============Restored================")
            if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
                FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
    
                do {
                    let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
                    let receiptString = receiptData.base64EncodedString(options: [])
                    
                    // TODO: Send your receiptString to the server and verify with Apple
                    // receiptString should be sent to server as JSON
                    // {
                    //    "receipt" : receiptString
                    // }
                    
                    
                    self.transactionState = .purchased // only if server sends successful response
                }
                catch { print("Couldn't read receipt data with error: " + error.localizedDescription) }
            }
        }
        
        func restorePurchase() {
            SKPaymentQueue.default().restoreCompletedTransactions()
        }
    }
    
    

    Testing with .storekit file on simulator:

    https://youtu.be/e7Tflo6AUH4

    Server side with PHP and Laravel:

    Create app specific shared secret

    Auto-renewable subscriptions with SwiftUI

    PHP and Laravel

    <?php 
    
    // Laravel and GuzzleHTTP\Client
    
    function verifyReceiptWithApple() {
            $input = file_get_contents('php://input');
            $request = json_decode($input);
    
            $d = $request->receipt;
            $secret = 'your_app_purchase_secret';
    
            //$url = 'https://sandbox.itunes.apple.com/verifyReceipt';
            $url = 'https://buy.itunes.apple.com/verifyReceipt';
    
            // Replace with curl if you are not using Laravel
            $client = new Client([
                'headers' => [ 'Content-Type' => 'application/json' ]
            ]);
            
            $response = $client->post($url,
                ['body' => json_encode(
                    [
                        'receipt-data' => $d,
                        'password' => $secret,
                        'exclude-old-transactions' => false
                    ]
                )]
            );
    
            $json = json_decode($response->getBody()->getContents());
            if ($json->status == 0) {
    
                $email = "";
    
                // Get original transaction id
                $receipts = $json->receipt->in_app;
                if (!empty($receipts) && count($receipts) > 0) {
                    $first_receipt = $receipts[0];
                    if ($first_receipt->in_app_ownership_type == "PURCHASED") {
                        $original_transaction_id = $first_receipt->original_transaction_id;
    
                        // Create email address with transaction id 
                        // Create new user if not exists
                        $email = $original_transaction_id.'@domain.com';
                        $have_user = "check_with_your_database";
                        if (!$have_user) {
                            // New purchase -> user not found
                        } else {
                            // Restore purchase -> user found 
                            
                        }
                    }
                }
    
                return response()->json(["status" => 1, "message" => "Receipt is verified"]);
            } else {
                return response()->json(["status" => 0, "message" => "Invalid receipt"]);
            }
        }

    Things to include in-app purchase

    • Value proposition
    • Call to action
    • Clear terms
    • Signup
    • Multiple tiers
    • Log in
    • Restore
    • Terms and conditions

    Read more

    App store distribution and marketing: https://developer.apple.com/videos/app-store-distribution-marketing

    Auto-Renewable Subscriptions: https://developer.apple.com/design/human-interface-guidelines/in-app-purchase/overview/auto-renewable-subscriptions/

    Architecting for subscriptions: https://developer.apple.com/videos/play/wwdc2020/10671/

    Download full source code

    Spread the love
  • Firebase getToken is deprecated

    Firebase getToken is deprecated

    If you are still using old style to get FireBase token, it is time to change it.

    Old way

    String token = FirebaseInstanceId.getInstance().getToken();

    New way

    FirebaseInstanceId.getInstance().getInstanceId()
    				.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
    					@Override
    					public void onComplete(@NonNull Task<InstanceIdResult> task) {
    						if (!task.isSuccessful()) {
    							Log.w("FB token e: ", "getInstanceId failed", task.getException());
    							return;
    						}
    
    						// Get new Instance ID token
    						String token = task.getResult().getToken();
    						Log.d("FB token", token);
    						if (!token.equals("")) {
    // send to your server						}
    					}
    				});
    Spread the love
  • Flutter video player example

    Flutter video player example

    Very easy Flutter video player example, using chewie and and video_player library.

    The app plays video from a remote HTTP URL and it plays in portrait mode, when you exit the video player it maintains portrait mode on your device.

    pubspec.yaml

    name: video_player
    description: Flutter video player project.
    
    # The following line prevents the package from being accidentally published to
    # pub.dev using `pub publish`. This is preferred for private packages.
    publish_to: 'none' # Remove this line if you wish to publish to pub.dev
    
    # The following defines the version and build number for your application.
    # A version number is three numbers separated by dots, like 1.2.43
    # followed by an optional build number separated by a +.
    # Both the version and the builder number may be overridden in flutter
    # build by specifying --build-name and --build-number, respectively.
    # In Android, build-name is used as versionName while build-number used as versionCode.
    # Read more about Android versioning at https://developer.android.com/studio/publish/versioning
    # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
    # Read more about iOS versioning at
    # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.12.0 <3.0.0"
    
    dependencies:
      flutter:
        sdk: flutter
    
    
      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^1.0.2
      video_player: ^2.1.14
      chewie: ^1.2.2
      
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
    
    # For information on the generic Dart part of this file, see the
    # following page: https://dart.dev/tools/pub/pubspec
    
    # The following section is specific to Flutter.
    flutter:
    
      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true
    
      # To add assets to your application, add an assets section, like this:
      #assets:
      #   - images/a_dot_ham.jpeg
    
      # An image asset can refer to one or more resolution-specific "variants", see
      # https://flutter.dev/assets-and-images/#resolution-aware.
    
      # For details regarding adding assets from package dependencies, see
      # https://flutter.dev/assets-and-images/#from-packages
    
      # To add custom fonts to your application, add a fonts section here,
      # in this "flutter" section. Each entry in this list should have a
      # "family" key with the font family name, and a "fonts" key with a
      # list giving the asset and other descriptors for the font. For
      # example:
      # fonts:
      #   - family: Schyler
      #     fonts:
      #       - asset: fonts/Schyler-Regular.ttf
      #       - asset: fonts/Schyler-Italic.ttf
      #         style: italic
      #   - family: Trajan Pro
      #     fonts:
      #       - asset: fonts/TrajanPro.ttf
      #       - asset: fonts/TrajanPro_Bold.ttf
      #         weight: 700
      #
      # For details regarding fonts from package dependencies,
      # see https://flutter.dev/custom-fonts/#from-packages
    

    In your main function, make sure you run the app in portrait mode,

    void main() {
      WidgetsFlutterBinding.ensureInitialized();
    
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
          .then((_) {
        runApp(MyApp());
      });
    }

    main.dart

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:inspiration_show/pages/home.dart';
    
    void main() {
      WidgetsFlutterBinding.ensureInitialized();
    
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
          .then((_) {
        runApp(MyApp());
      });
    }
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Video Player',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.red,
          ),
          home: MyHomePage(title: 'Video Player Demo Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key, required this.title}) : super(key: key);
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      String appBarTitle = "Home";
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(appBarTitle),
          ),
          body: HomeWidget(),
        );
      }
    }
    

    home.dart

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:video_player/video_player.dart';
    import 'package:chewie/chewie.dart';
    
    class HomeWidget extends StatefulWidget {
      @override
      _VideoWidget createState() => _VideoWidget();
    }
    
    class _VideoWidget extends State<HomeWidget> {
      late VideoPlayerController videoPlayerController;
      late ChewieController chewieController;
    
      bool isReady = false;
    
      @override
      void initState() {
        super.initState();
        initializeVideoPlayer();
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          margin: const EdgeInsets.all(16),
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            Center(
              child: Container(
                height: 200,
                child: isReady == true
                    ? Chewie(controller: chewieController)
                    : Center(child: CircularProgressIndicator()),
              ),
            ),
          ]),
        );
      }
    
      @override
      void dispose() {
        super.dispose();
        videoPlayerController.dispose();
        chewieController.videoPlayerController.dispose();
    
        SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
      }
    
      Future<void> initializeVideoPlayer() async {
        videoPlayerController = VideoPlayerController.network(
            "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_1920_18MG.mp4");
        await Future.wait([videoPlayerController.initialize()]);
    
        chewieController = ChewieController(
            videoPlayerController: videoPlayerController,
            autoPlay: false,
            aspectRatio: 16 / 9,
            autoInitialize: true);
    
        setState(() {
          isReady = true;
        });
    
        chewieController.addListener(() {
          if (!chewieController.isFullScreen) {
            SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
          }
        });
      }
    }
    

    Download source code

    Spread the love