Параметры не передаются по Http после запроса? - PullRequest
0 голосов
/ 23 декабря 2019

Hai Я пытаюсь передать некоторые параметры строки в Http пост-запрос. Я создал словарь, а затем преобразовал этот словарь в данные и установил его как httpBody. Но когда я посмотрел на нашем сервере, ничего не было передано, я имею в виду, что параметры пусты. Почему? Какую ошибку я делаю? Пожалуйста, помогите мне узнать. Спасибо заранее.

func receiptValidation(productId:String,requestFrom:String)
{
    let SUBSCRIPTION_SECRET = "mySecretKey"
    let defaults = UserDefaults.standard
    let receiptPath = Bundle.main.appStoreReceiptURL?.path
    if FileManager.default.fileExists(atPath: receiptPath!){
        var receiptData:NSData?
        do {
            receiptData = try NSData(contentsOf: Bundle.main.appStoreReceiptURL!, options: NSData.ReadingOptions.alwaysMapped)
        }
        catch{
            print("ERROR: " + error.localizedDescription)
        }
        //let receiptString = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        let base64encodedReceipt = receiptData?.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)

        print(base64encodedReceipt!)
        let requestDictionary = ["receipt-data":base64encodedReceipt!,"password":SUBSCRIPTION_SECRET]

        guard JSONSerialization.isValidJSONObject(requestDictionary) else {  print("requestDictionary is not valid JSON");  return }
        do {
            let requestData = try JSONSerialization.data(withJSONObject: requestDictionary)
            let requestDataString=String(describing: requestData)
            let URLForApplication:String = String(format:"%@/api/validate-receipt-data",opcodeDetails["apiProxyBaseUrl"]!)  // this works but as noted above it's best to use your own trusted server
            SwiftyBeaver.info("URLForApplication Path:\n\(URLForApplication)")
            let url:URL! = URL.init(string: URLForApplication)
            var request = URLRequest.init(url: url)
            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            let configure = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier!)
            session1=URLSession(configuration: .default, delegate: applicationDelegate.application, delegateQueue: OperationQueue.main)

            var postString =
                ["receiptData":requestDataString,
                 "deviceType":"IOS",
                 "subscriberId":encodeString(normalString: defaults.array(forKey: "userDetails")?.first as! String),
                 "password":encodeString(normalString: defaults.array(forKey: "userDetails")?.last as! String),
                 "productId":encodeString(normalString: productId ),
                 "code":opcodeDetails["opCode"]!]
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
            } catch let error {
                print(error.localizedDescription)
            }
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

            let task = session1?.dataTask(with: request) { (data, response, error) in
                if let data = data , error == nil {
                    do {
                        let appReceiptJSON = try JSONSerialization.jsonObject(with: data)
                        print("success. here is the json representation of the app receipt: \(appReceiptJSON)")
                        // if you are using your server this will be a json representation of whatever your server provided
                    } catch let error as NSError {
                        print("json serialization failed with error: \(error)")
                    }
                } else {
                    print("the upload task returned an error: \(error)")
                }
            }
            task?.resume()
        } catch let error as NSError {
            print("json serialization failed with error: \(error)")
        }
    }
}

и какую ошибку я получаю Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...