# Getting Started with the TTC SDK for iOS

# Prerequisites for Using the SDK

To get started, simply download the SDK for iOS

# Install

The TTC TReE SDK can be installed by using CocoaPods.

# open use_frameworks!
use_frameworks!

pod 'TTCSDK'

Note: For Object-C projects, please select the swift version 4.1+..

# Add the URL Scheme

Follow the followng naming guideline for the URL Scheme.

"TTC-" + APP Bundle identifier e.g : TTC-com.tataufo.TTC-SDK-iOS-Demo

# Initiate

This method is called when the DAPP starts.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window!.rootViewController = ViewController()
    window!.makeKeyAndVisible()

    TTCSDK.register(appId: "AppId", secretKey: "SecretKey") { (result, error) in
        if result {
            print("register success")
        } else {
            print("register failure:\(error!)")
        }
    }

    return true
}

# Handle Wallet Bindings

The system provides three methods, and it should be noted that if all are implemented, only the latest one will be taken..

// after iOS 9
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
    let result = TTCSDK.handleApplication(openURL: url)
    return result
}

// iOS 4.2 - iOS 9
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    let result = TTCSDK.handleApplication(openURL: url)
    return result
}

//iOS 2 - iOS 9
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
    let result = TTCSDK.handleApplication(openURL: url)
    return result
}

# Login

When login succeeds, the callback method's parameter contains all of the user's information.

let user = TTCUserInfo(userId: userId)

TTCSDK.login(userInfo: user) { (success, error, _) -> Void in

    if success {
        print("login success")
    } else {
        print(error!)
    }
}

# Update User Information

The user is what the user update. The callback method's will contain the user information if successful.

func updataUser(user: TTCUserInfo) {

    TTCSDK.update(userInfo: user) { (success, error, _) -> Void in

        if success {
            print("Update user information success")
            TWToast.showToast(text: "Update user information success")
            self.dismiss(animated: true, completion: nil)
        } else {
            print("Update information failed:\(error ?? "未知错误")")
            TWToast.showToast(text: "Update information failed:\(error ?? "")")
        }
    }
}

# Log out

When the user logs out, make sure to call the method to clear local information;

TTCSDK.logout()

# Get Account Balance

The account balance is the balance of TTC coin in your service, which is not synchronized to the TTC Connect.

TTCSDK.queryAccountBalance { (success, error, balance) in

    if success {
        print("balance: \(balance)")
    } else {
        print("error: \(error!)")
    }
}

# Get Wallet Balance

TTCSDK.queryWalletBalance { (success, error, balance) in
    if success {
        print("balance: \(balance)")
    } else {
        print("error: \(error!)")
    }
}

# Unbind Wallet

This method is used to terminate the binding between your service and the TTC Connect.

TTCSDK.unBindWallet { (success, error) in
    if success {
        print("Untied success")
    } else {
        print("error: \(error!)")
    }
}

# Upload User Behaviors

The actionType must be greater than 100. The extra must be a json structure string.

let timestamp = Int64(Date().timeIntervalSince1970 * 1000)
let extra = "{'actionType':101, 'userID':\(TTCUser.shared.userId ?? ""), 'content':'发了一个帖子哈哈哈哈哈哈','timestamp':\(timestamp)}"

TTCUploadAction.uploadAction(actionType: 101, extra: extra) { (success, error) in
    if success {
        print("Record success")
    } else {
        print("Record failure:\(error!)")
    }
}

# Change SDK Status

By default, SDK is set to be "available" (true). If you want to make the SDK unavailable, set it to false.

TTCSDK.sdk(isEnabled: false)

# Error Type

A method may return an error with TTCSDKError, including an error code and errorDescription.

@objc public class TTCSDKError: NSObject {
    /// Error number
    @objc public var code: String = ""
    /// Error Description
    @objc public var errorDescription: String = ""
}

# Error Codes

Error code documentations

# TTCAd

# Initialize Ad

Before loading an ad, the app should call the configure: class method in TTCAdMob and pass it an AdMob app ID to initialize the TTC ad. This operation only needs to be performed once, preferably when the application starts.

The following example shows how to call the configure: method in the AppDelegate:

func application(_ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
	 TTCAdMob.configure(appID: "YOUR_ADMOB_APP_ID")
   return true
  }
}

A banner ad is a rectangular or text ad that occupies a place in the app layout. When a user interacts with an app, the ad stays on the screen and automatically refreshes after a while.

Create TTCAdBanner

	var banner: TTCAdBanner!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        banner = TTCAdBanner(adSize: .LargeBanner)
        banner.rootViewController = self
		  banner.delegate = self
        banner.adUnitID = "ca-app-pub-3940256099942544/2934735716"
        view.addSubview(banner.bannerView)
        banner.bannerView.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.bottom.equalTo(-34)
        }
    }

Load ad

let request = TTCAdRequest()
//        request.testDevices = [TTCkAdSimulatorID, "a6f4cc131cbe0effa815572262d24262"]
        banner.loadRequest(requset: request)

Ad Delegate

Each method in TTCAdBannerDelegate is an optional method, so you only need to implement the methods you need.

func adViewDidReceiveAd(_ banner: TTCAdBanner) {
        print("adViewDidReceiveAd")
    }

    func adViewDidFailToReceiveAd(banner: TTCAdBanner, error: Error) {
        print("adViewDidFailToReceiveAd")
    }

    func adViewWillPresentScreen(banner: TTCAdBanner) {
        print("adViewWillPresentScreen")
    }

    func adViewWillDismissScreen(banner: TTCAdBanner) {
        print("adViewWillDismissScreen")
    }

    func adViewDidDismissScreen(banner: TTCAdBanner) {
        print("adViewDidDismissScreen")
    }

    func adViewWillLeaveApplication(banner: TTCAdBanner) {
        print("adViewWillLeaveApplication")
    }

# Interstitial Ad

An interstitial is a full-screen ad that covers the entire app interface until the user closes it. These ads are typically displayed at natural transition points of the app flow (for example, pauses between events or between game levels). When an app shows an interstitial, the user can choose to tap the ad, visit their destination URL, or close it and return to the app.

Create an interstitial ad and load the ad

override func viewDidLoad() {
        super.viewDidLoad()
		interstitial = TTCAdInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self
        let request = TTCAdRequest()
//        request.testDevices = [TTCkAdSimulatorID, "a6f4cc131cbe0effa815572262d24262"]
        interstitial.loadRequest(requset: request)
    }

show Ad

To display an interstitial, check the isReady property on TTCAdInterstitial to verify that the load is complete before calling present.

@IBAction func doSomething(_ sender: AnyObject) {
  ...
  if interstitial.isReady {
    interstitial.present(rootViewController: self)
  } else {
    print("Ad wasn't ready")
  }
}

TTCAdInterstitial is a one-time object, which means that when an interstitial ad is displayed, hasBeenUsed returns true and no more ads can be loaded with the interstitial ad object. To request another interstitial, you need to create a new TTCAdInterstitial object. If you try to reuse an interstitial ad object, you will receive the following error response: "Request Error: Will not send request because interstitial object has been used".

Advertising event agent

func interstitialDidReceiveAd(ad: TTCAdInterstitial) {
        print("interstitialDidReceiveAd")
    }

    func interstitialDidFailToReceiveAdWithError(ad: TTCAdInterstitial, error: Error) {
        print("interstitialDidFailToReceiveAdWithError")
    }

    func interstitialWillPresentScreen(ad: TTCAdInterstitial) {
        print("interstitialWillPresentScreen")
    }

    func interstitialDidFailToPresentScreen(ad: TTCAdInterstitial) {
        print("interstitialDidFailToPresentScreen")
    }

    func interstitialWillDismissScreen(ad: TTCAdInterstitial) {
        print("interstitialWillDismissScreen")
    }

    func interstitialDidDismissScreen(ad: TTCAdInterstitial) {
        print("interstitialDidDismissScreen")
    }

    func interstitialWillLeaveApplication(ad: TTCAdInterstitial) {
        print("interstitialWillLeaveApplication")
    }

# Incentive video ad

Incentive video ads are full-screen video ads that users can choose to watch in full-screen mode in exchange for in-app rewards.

Incentive video ads initialize and request ads TTCAdRewardBasedVideoAd has a single instance design

var rewardBasedVideo: TTCAdRewardBasedVideoAd!
override func viewDidLoad() {
        super.viewDidLoad()

        rewardBasedVideo = TTCAdRewardBasedVideoAd.sharedInstance
        rewardBasedVideo.delegate = self
        let request = TTCAdRequest()
//            request.testDevices = [TTCkAdSimulatorID, "a6f4cc131cbe0effa815572262d24262"]
            rewardBasedVideo.loadRequest(request: request, adUnitID: "ca-app-pub-3940256099942544/1712485313")
    }

Show incentive video ads

if rewardBasedVideo.isReady {
                rewardBasedVideo.present(rootViewController: self)
            }

Ad Delegate

func rewardBasedVideoAd(rewardBasedVideoAd: TTCAdRewardBasedVideoAd, didRewardUserWithReward reward: TTCAdReward) {
        print("receve: \(reward.amount?.description ?? "null") \(reward.rewardType?.description ?? "what?")")
    }

    func rewardBasedVideoAd(rewardBasedVideoAd: TTCAdRewardBasedVideoAd, didFailToLoadWithError error: Error)  {
        adRequestInProgress = false
        print("didFailTo" + error.localizedDescription)
    }

    func rewardBasedVideoAdDidReceiveAd(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        adRequestInProgress = false
        print("DidReceiveAd")
    }

    func rewardBasedVideoAdDidOpen(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        print("rewardBasedVideoAdDidOpen")
    }

    func rewardBasedVideoAdDidStartPlaying(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        print("rewardBasedVideoAdDidStartPlaying")
    }

    func rewardBasedVideoAdDidCompletePlaying(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        print("rewardBasedVideoAdDidCompletePlaying")
    }

    func rewardBasedVideoAdDidClose(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        print("rewardBasedVideoAdDidClose")
    }

    func rewardBasedVideoAdWillLeaveApplication(rewardBasedVideoAd: TTCAdRewardBasedVideoAd) {
        print("rewardBasedVideoAdWillLeaveApplication")
    }