Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php &引用;JSON文本未以数组或对象开头,并且未设置允许片段的选项;_Php_Json_Swift_Post_Error Handling - Fatal编程技术网

Php &引用;JSON文本未以数组或对象开头,并且未设置允许片段的选项;

Php &引用;JSON文本未以数组或对象开头,并且未设置允许片段的选项;,php,json,swift,post,error-handling,Php,Json,Swift,Post,Error Handling,发出POST请求时,Xcode调试器显示错误 Error Domain=NSCOCAERRORDOMAIN Code=3840“JSON文本未以数组或对象开头,允许未设置片段的选项。”UserInfo={NSDEBUGSCRIPTION=JSON文本未以数组或对象开头,允许未设置片段的选项。} 这是POST函数 func startArchive() { let app_Id = (appId.base64Decoded()!) let job_Id = (j

发出POST请求时,Xcode调试器显示错误

Error Domain=NSCOCAERRORDOMAIN Code=3840“JSON文本未以数组或对象开头,允许未设置片段的选项。”UserInfo={NSDEBUGSCRIPTION=JSON文本未以数组或对象开头,允许未设置片段的选项。}

这是POST函数

 func startArchive() {

        let app_Id = (appId.base64Decoded()!)
        let job_Id = (jobId.base64Decoded()!)

        var response_ = 0

        guard let url = URL(string: "https://xxx.yyyy.com/question/abc") else {return}
        let request = NSMutableURLRequest(url:url)
        request.httpMethod = "POST"
        let postString = "session_id=\(pSessionId)&job_id=\(job_Id)&app_id=\(app_Id)&action=start"
        print(postString)
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = postString.data(using: String.Encoding.utf8)

        let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            do {
                if let responseJSON = try JSONSerialization.jsonObject(with: data!) as? [String:AnyObject]{
                    print(responseJSON)
                    print(responseJSON["status"]!)                   
                    response_ = responseJSON["status"]! as! Int                    
                    print(response_)

                    //Check response from the sever
                    if response_ == 200
                    {
                        OperationQueue.main.addOperation {
                            print("Login Successful")
                        }                        
                    }                        
                    else
                    {
                        OperationQueue.main.addOperation {

                            print("Login Failed")

                        }                      
                    }
                }
            }
            catch {
                print("Error -> \(error)")
            }
        }
        task.resume()
    }
我已经尝试使用header,但仍然出现相同的错误

request.setValue(“text/html;charset=UTF-8”,forHTTPHeaderField:“内容类型”)

下面是用于上述请求的PHP函数

public function abc(Request $request)
{        $session_id = !empty($request->input('session_id')) ? $request->input('session_id') : '';
    $action = $request->input('action');
    $archiveId = !empty($request->input('archive_id')) ? $request->input('archive_id') : '';

    $data = array();

    $opentok = new \OpenTok\OpenTok($_SERVER['TOKBOX_' . strtoupper($this->tenantName) . '_API_KEY'], $_SERVER['TOKBOX_' . strtoupper($this->tenantName) . '_SECRET']);

    if ($action == 'start') { // Start recording
        try {
            // Create an archive using custom options
            $archiveOptions = array(
                'name' => 'Important Presentation', // default: null
                'hasAudio' => true, // default: true
                'hasVideo' => true, // default: true
                'outputMode' => \OpenTok\OutputMode::COMPOSED  // default: OutputMode::COMPOSED
            );

            $archive = $opentok->startArchive($session_id, $archiveOptions);

            $job_id = $request->input('job_id');
            $app_id = $request->input('app_id');

            // check record exist or not
            $check_archive = DB::table('practice_question_recordings')
                ->where('job_id', $job_id)
                ->where('app_id', $app_id)
                ->get();

            if (empty($check_archive)) { // insert data
                $insert_data = array();
                $insert_data['job_id'] = $job_id;
                $insert_data['app_id'] = $app_id;
                $insert_data['archive_id'] = $archive->id;
                $insert_data['archive_url'] = '';

                DB::table('practice_question_recordings')->insert($insert_data);
            } else {  // Update data
                $update_data = array();
                $update_data['job_id'] = $job_id;
                $update_data['app_id'] = $app_id;
                $update_data['archive_id'] = $archive->id;
                $update_data['archive_url'] = '';

                DB::table('practice_question_recordings')
                    ->where('job_id', $job_id)
                    ->where('app_id', $app_id)
                    ->update($update_data);
            }

            $data['status'] = 200;
            $data['archive_id'] = $archive->id;
            $data['message'] = 'Recording started successfully.';
        } catch (Exception $ex) {

            $data['status'] = 500;
            $data['message'] = $ex->getMessage();
        }
    } else { // Stop recording
        try {
            $archive_detail = $opentok->stopArchive($archiveId);

            $data['status'] = 200;
            $data['archive_detail'] = $archive_detail;
            $data['message'] = 'Recording stopped successfully.';
        } catch (Exception $ex) {
            $data['status'] = 500;
            $data['message'] = $ex->getMessage();
        }
    }

    return response()->json($data);
}

所以我终于发现了这个问题。问题出现在URL的子域中

由于我正在使用另一个子域[OpenTok]的会话id并将其作为参数传递,因此出现了状态代码500

此外,我将我的职位职能结构改为:

    func startArchive() {

    let app_Id = (appId.base64Decoded()!)
    let job_Id = (jobId.base64Decoded()!)

    let parameters: [String: Any] = ["session_id": pSessionId, "job_id":job_Id, "app_id":app_Id, "action":"start"]

    print("Parameter:\(parameters)")
    guard let url = URL(string: "https://first.yyyy.com/question/abc") else {return}

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("iOS", forHTTPHeaderField: "deviceType")
    guard let httpbody = try? JSONSerialization.data(withJSONObject: parameters, options:[]) else {return}
    request.httpBody = httpbody

    let session = URLSession.shared
    session.dataTask(with: request) {data, response, error  in
        if let response = response {
            print(response)
        }
        if let data = data{

            let mdata = String(data: data, encoding: .utf8)
            print("This is data: \(mdata!)")

            do{
                //                    print("\(String(data: data, encoding: .utf8) ?? "")")
                if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary {
                    DispatchQueue.main.async {
                        _archiveId = (json["archive_id"] as! String)
                        print(json)
                    }
                }
            } catch {
                print(error)
            }
        }
        }.resume()
}

它对我来说效果很好,返回的数据是JSON

你能发布预期的JSON吗?你能打印
字符串(数据:数据:编码:.utf8)
?此外,您可能希望为Accepped内容类型标题添加
application/json
。请将代码段以及生成的json添加到问题中,而不是作为注释发布在。因此,所有重要信息都集中在一个点上。在执行
JSONSerialization
之前,您是否可以打印
字符串(数据:数据:编码:.utf8)
?并非所有iOS开发人员都会说php(至少我不会),但我们可能会指出问题所在。HTML,而不是JSON。我可能觉得你有个错误。一些404错误。