如何将数据从iOS应用传递到OneSignal

时间:2019-08-14 20:16:58

标签: ios swift onesignal

我在Web服务器上运行了以下PHP代码,该代码在加载后会正确发出OneSignal通知。我有以下在网上找到的Swift代码,这些代码链接到Xcode中的一个按钮,实际上它确实通过调用Web服务器发送通知。现在,我需要知道如何将信息从iOS应用程序传递到PHP文件,并最终传递OneSignal通知。我已经找到了示例快速代码示例。

在Web服务器上运行的PHP代码:

<?PHP
function sendMessage() {
    $content      = array(
        "en" => 'Active Shooter on Campus',
    );
    $title    = array(
        "en" => 'Panic Button Pushed'
    );
    $fields = array(
        'app_id' => "MYAPPID",
        'included_segments' => array(
            'All'
        ),
        'data' => array(
            "foo" => "bar"
        ),
        'contents' => $content,
        'headings' => $title,
    );

    $fields = json_encode($fields);
    print("\nJSON sent:\n");
    print($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic MYAPIKEY'
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode($return);

$data = json_decode($response, true);
print_r($data);
$id = $data['id'];
print_r($id);

print("\n\nJSON received:\n");
print($return);
print("\n");
?>

示例Swift代码(有效):

func panic() {
    let url = URL(string: "https://mywebsite.com/send.php")!

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //add the parameters here as needed
    let parameters = ["headings": "test", "password": "123456"]

    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    //the service response is here
        print(response)
    })

            task.resume()
}

0 个答案:

没有答案