ios – Swift, could not get incomes particulars from AdMob and AdSense

[ad_1]

I am engaged on my app (iOS) to get AdMob and AdSense earnings data. However I have been having hassle getting specifics from them. I’ve already created the credentials and shopper ID from my Google account, however I am unsure the place to place them.

I attempted rigorously following many strategies from this hyperlink however was by no means profitable.

My first step: Throughout startup, test to see in case you are logged in or out.

import FirebaseAuth
import GoogleSignIn

var currentPID = ""

func checkGoogleAccountStatus() {
    GIDSignIn.sharedInstance.restorePreviousSignIn { consumer, error in
        if error != nil || consumer == nil {
            print("Signed out")
            self.loginButton()
        } else {
            print("Signed in")
            let userAccess: String = consumer!.authentication.accessToken
            self.googledSignedInSuccess(googleToken: userAccess, tokenID: consumer!.authentication.idToken!)
            
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "MMMM d, yyyy  h:mm:ss a"
            let expiredToken = consumer?.authentication.accessTokenExpirationDate
            print("Token Expired: (dateformatter.string(from: expiredToken!))")
        }
    }
}

Profitable

My second step: After I tapped the button to log in, an alert controller appeared to see if the log in was profitable. It would show the alert controller’s profile image, title, and electronic mail tackle.

@objc func loginTapped() {
    let adMobScope = "https://www.googleapis.com/auth/admob.report"
    let adSenseScope = "https://www.googleapis.com/auth/adsensehost"
    let additionalScopes = [adMobScope,adSenseScope]
    let signInConfig = GIDConfiguration.init(clientID: "<My URL Schemes>")
    
    GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self, trace: nil, additionalScopes: additionalScopes) { consumer, error in
        guard error == nil else { return }
        guard let consumer = consumer else { return }
        if let profiledata = consumer.profile {
            
            let grantedScopes = consumer.grantedScopes
            if grantedScopes == nil || !grantedScopes!.comprises(adMobScope) {
                print("AdMob not Granted...")
            } else {
                print("AdMob Granted!")
            }
            
            if grantedScopes == nil || !grantedScopes!.comprises(adSenseScope) {
                print("AdSense not Granted...")
            } else {
                print("AdSense Granted!")
            }
            
            //let userId: String = consumer.userID ?? ""
            let givenName: String = profiledata.givenName ?? ""
            let familyName: String = profiledata.familyName ?? ""
            let electronic mail: String = profiledata.electronic mail
            let userToken: String = consumer.authentication.idToken!
            let userAccess: String = consumer.authentication.accessToken
            
            let credential = GoogleAuthProvider.credential(withIDToken: userToken, accessToken: userAccess)
            Auth.auth().signIn(with: credential) { end result, error in
                if let error = error {
                    print(error.localizedDescription)
                    
                    let alert = UIAlertController(title: "Error", message: "One thing went mistaken, please strive once more.", preferredStyle: .alert)
                    let motion = UIAlertAction(title: "OK", type: .cancel, handler: {_ in return })
                    
                    alert.addAction(motion)
                    self.current(alert, animated: true, completion: nil)
                }
                if let imgurl = consumer.profile?.imageURL(withDimension: 300) {
                    let absoluteurl: String = imgurl.absoluteString
                    let alert = UIAlertController(title: "(givenName) (familyName)", message: "nnnnnnn(electronic mail)nLogin Profitable", preferredStyle: .alert)
                    let motion = UIAlertAction(title: "OK", type: .cancel, handler: {_ in
                        // MARK: Do one thing to replace
                        self.checkGoogleAccountStatus()
                    })
                    
                    let imgViewTitle = UIImageView()
                    imgViewTitle.translatesAutoresizingMaskIntoConstraints = false
                    imgViewTitle.layer.borderColor = UIColor(named: "Font Coloration")?.cgColor
                    imgViewTitle.layer.borderWidth = 3
                    imgViewTitle.layer.cornerRadius = 50
                    imgViewTitle.clipsToBounds = true
                    alert.view.addSubview(imgViewTitle)
                    imgViewTitle.centerYAnchor.constraint(equalTo: alert.view.centerYAnchor, fixed: -28).isActive = true
                    imgViewTitle.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor).isActive = true
                    imgViewTitle.widthAnchor.constraint(equalToConstant: 100).isActive = true
                    imgViewTitle.heightAnchor.constraint(equalToConstant: 100).isActive = true
                    
                    DispatchQueue.international().async {
                        if let information = strive? Information(contentsOf: URL(string: absoluteurl)! ) { if let picture = UIImage(information: information) { DispatchQueue.primary.async { imgViewTitle.picture = picture } } }
                    }
                    
                    alert.addAction(motion)
                    self.current(alert, animated: true, completion: nil)
                    
                } else {
                    let alert = UIAlertController(title: "(givenName) (familyName)", message: "(electronic mail)nLogin Profitable", preferredStyle: .alert)
                    let motion = UIAlertAction(title: "OK", type: .cancel, handler: {_ in
                        // MARK: Do one thing to replace
                        self.checkGoogleAccountStatus()
                    })
                    
                    alert.addAction(motion)
                    self.current(alert, animated: true, completion: nil)
                }
            }
        }
    }
}

After I logged in, it requested for permission to entry AdMob and AdSense, adopted by a pop-up alert that mentioned I had efficiently logged in.

My third step: Getting the PID from Google AdMob / AdSense

import CurlDSL
import Gzip

func googledSignedInSuccess(googleToken: String, tokenID: String) {
    guard let url = URL(string: "https://admob.googleapis.com/v1/accounts/") else { return }
    
    do {
        strive CURL(#"curl -H "Authorization: Bearer #(googleToken)" "#(url)""#).run { information, response, error in
            if let error = error { print("Error came about (error)"); return }
            if let response = response as? HTTPURLResponse {
                if response.statusCode != 200 {
                    print("Error: (response)")
                } else {
                    if let information = information {
                        do {
                            if let rawJSON = strive? JSONDecoder().decode(GetAdMobInfo.self, from: information) {
                                currentPID = rawJSON.account[0].publisherID
                                print("Profitable: (currentPID)")
                                self.adMob_gettingReport(pid: currentPID, token: googleToken)
                            }
                        }
                    }
                }
            }
        }
    } catch { print("Failed.") }
}



struct GetAdMobInfo: Codable {
    let account: [Account]
}

struct Account: Codable {
    let title, publisherID, reportingTimeZone, currencyCode: String

    enum CodingKeys: String, CodingKey {
        case title
        case publisherID = "publisherId"
        case reportingTimeZone, currencyCode
    }
}

It was success, I used to be in a position to get my PID and writed to currentPID as string.

My remaining step, which failed:

func adMob_gettingReport(pid: String, token: String) {
    guard let url = URL(string: "https://admob.googleapis.com/v1/accounts/(pid)/mediationReport:generate") else { return }
    let reportData = "--data @- << EOF {"report_spec": {"date_range": {"start_date": {"12 months": 2020, "month": 4, "day": 1}, "end_date": {"12 months": 2020, "month": 4, "day": 1} },"dimensions": ["AD_SOURCE", "AD_UNIT", "PLATFORM"], "metrics": ["ESTIMATED_EARNINGS"]}} EOF"
    do {
        strive CURL(#"curl -X POST "#(url)" -H "Authorization: Bearer #(token)" -H "Content material-Sort: software/json" #(reportData)"#).run { information, response, error in
            if let error = error { print("Error came about (error)"); return }
            if let response = response as? HTTPURLResponse {
                if response.statusCode != 200 {
                    print("Error: (response)")
                } else {
                    if let information = information {
                        print("Getting AdMob Profitable")
                        let decompressedData: Information
                        if information.isGzipped { decompressedData = strive! information.gunzipped() }
                        else { decompressedData = information }
                        
                        var getLineFromString: [String] = []
                        getLineFromString += String(information: decompressedData, encoding: .utf8)!.parts(separatedBy: "n")
                        
                        for checkLine in getLineFromString {
                            print("Line: (checkLine)")
                        }
                    }
                }
            }
        }
    } catch { print("Failed.") }
}

Making an attempt to acquire earnings data from AdMob and AdSense, however it stored saying failing in print. That is the place I have been for practically two months. What did I overlook?

[ad_2]

Leave a Reply