CNLiveAdViewModel.swift 4.06 KB
//
//  CNLiveAdViewModel.swift
//  metaCode
//
//  Created by zx on 2025/4/22.
//

import Foundation
import CNLiveRequestBastKit
import CNLiveBusinessTools

class CNLiveAdViewModel:NSObject,URLSessionTaskDelegate{
    static let shared = CNLiveAdViewModel()
    
    func getAdData(resultBlock: @escaping downSlideResultBlock){
        let param = NSMutableDictionary()
        param.setValue("IOS", forKey: "deviceType")
        param.setValue("C", forKey: "type")
        param.setValue("apple", forKey: "app_channel_id")
        let kAppBundleID = Bundle.main.bundleIdentifier ?? ""
        let uuid : String = UIDevice.current.identifierForVendor?.uuidString.replacingOccurrences(of: "-", with: "") ?? ""
        let ver : String = Bundle.main.infoDictionary?["CFBundleVersion"] as! String
        let p : Dictionary = ["platform_id":kAppBundleID,"uuid":uuid,"plat":"i","ver":ver,"appId":APPId,"timestamp":String(NSNumber(floatLiteral: Date().timeIntervalSince1970).intValue),"clientPlat":"i","frmId":"ios"]
       
        param.setValue(kAppBundleID, forKey: "platform_id")
        param.setValue(uuid, forKey: "uuid")
        param.setValue("i", forKey: "plat")
        param.setValue(ver, forKey: "ver")
        param.setValue(CNLiveMCEnvironmentManager.shared.appId_wjj, forKey: "appId")
        param.setValue(String(NSNumber(floatLiteral: Date().timeIntervalSince1970).intValue), forKey: "timestamp")
        param.setValue("i", forKey: "clientPlat")
        param.setValue("ios", forKey: "frmId")
        
        let signStr = CNLiveBusinessTools.signvalue(param as! [AnyHashable : Any])
        let string1 = "\(signStr)&key=\(CNLiveMCEnvironmentManager.shared.appKey_wjj)"
        let signString1 = CNLiveBusinessTools.sha1(string1).uppercased()
        param.setValue(signString1, forKey: "sign")
       
        
        let adUrl =  APPBaseWjjUrl+"/Daren/common/getNewestVersion.action"
        let videourl = "\(adUrl)?\(signStr)&sign=\(signString1)"
        print("111111URL:\(videourl)")
        
        // 创建一个可变URL请求
        let urlRequest = NSMutableURLRequest(url: URL(string: videourl)!)
        urlRequest.httpMethod = "POST"
        urlRequest.timeoutInterval = 60
        
        let config = URLSessionConfiguration.default
        config.requestCachePolicy = .reloadIgnoringLocalCacheData
        
        let urlSession = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.current)
        let task = urlSession.dataTask(with: urlRequest as URLRequest) { data, response, error in
            if let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 301 || urlResponse.statusCode == 302  {
                // do something ...
                resultBlock("", .failed)
            }else if let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 || urlResponse.statusCode == 0{
                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: data ?? Data(), options: []) as? [String: Any]{
                        resultBlock(jsonResult["data"], .success)
                    }else{
                        resultBlock("", .failed)
                    }
                } catch {
                    print("JSON 解析错误")
                    resultBlock("", .failed)
                }
            }
        }
        
        task.resume()
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
        print("\(response.statusCode)") // 302
        print("\(response.allHeaderFields["Location"] as? String ?? "无重定向地址")") // 重定向地址URL
        
        // 根据业务需求决定是否使用新的请求继续任务
        // completionHandler(request) // 使用新的请求继续任务
        // completionHandler(nil) // 不使用新的请求,取消重定向
        
        // 在这个例子中,我们简单地取消重定向(即不使用新的请求)
        completionHandler(nil)
    }

        
}