OGeek|极客世界-中国程序员成长平台

标题: php - 使用 NSData 将日期从 xCode 传递到 PHP [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 06:31
标题: php - 使用 NSData 将日期从 xCode 传递到 PHP

我正在尝试将日期从 Xcode 传递到 PHP 页面(将日期存储到 mysql DB)但是 NSData 似乎不喜欢日期的格式。

//Format date for mysql & PHP
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat"yyyy-MM-dd HH:mm:ss"];
NSString *strToday = [dateFormatter  stringFromDate:[NSDate date]];

NSString *strURL = [NSString stringWithFormat"http://www.TESTSERVER.com/Items.php?uID=123456789&item1=30&item2=5&startDate=%@&endDate=%@", strToday, strToday];

//strURL=[strURL stringByReplacingOccurrencesOfString" " withString"%20"];

NSLog(@"%@", strURL);

NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(@"%@", strResult);

我已经通过手动输入数据测试了 PHP 页面,它可以正常工作。但是,当我运行上面的代码时它不起作用,我已将问题隔离到日期,并且我认为 NSData 在我的日期格式中的空间(日期和时间之间)存在问题。

我尝试使用 %20(URL 编码等)填补空白,并与数据库建立了连接,但日期字段的格式不正确,因此它在 mysql 数据库中显示为空。

我不想在我的 PHP 中开始解析字符串,有人知道如何解决这个问题吗?

下面是我的 PHP 代码:-

<?PHP

$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$database = "XXX";

$db_handle = mysql_connect($hostname, $username, $password);
$db_found = mysql_select_db($database, $db_handle);


$uID = $_GET['uID'];
$item1 =$_GET['item1'];
$item2 =$_GET['item2'];
$startDate =$_GET['startDate'];
$endDate =$_GET['endDate'];

if ($db_found) {

    $sql = "INSERT INTO Items (uID, item1, item2, startDate, endDate) VALUES  ('$uID','$item1','$item2','$startDate','$endDate');";

    //$cleanSQL = str_replace("%20"," ",$sql);
    $result = mysql_query($sql);

    mysql_close($db_handle);

    print "Records added to the database";

} else {

    print "Database NOT Found ";
    mysql_close($db_handle);
}

?>



Best Answer-推荐答案


此代码存在许多问题,但根据所提供的有限信息,无法诊断出您所描述的问题的确切原因。几点观察:

  1. 您肯定需要对日期字符串进行百分比转义。 URL 中的空格是 Not Acceptable (标准 x-www-form-urlencoded 请求的正文也是如此)。

  2. 如果你要插入数据,你应该发出 POST 请求,而不是将这些东西添加到 URL,实际上是发出 GET 请求。

  3. 您不应使用 dataWithContentsOfURL 发出请求。不仅是GET,而且是同步的,不报错。

  4. 如果你仍然有问题,你应该使用 Charles 或类似的工具来观察这个请求。观察您通过网络浏览器处理的相同请求并进行比较和对比。

  5. 就个人而言,当我遇到问题时,我会临时更改我的 PHP 代码以返回我传递给它的数据,这样我就可以确保一切都被正确接收。这是一种简单但有效的方式来确认所有内容都已正确接收。

  6. 如果您将日期字符串传递给服务器,您通常应该使用 GMT 时区,以避免由于服务器不知道用户设备所在的时区而导致的问题。同样,您应该使用 en_US_POSIX 语言环境,以避免出现非公历的问题。请参阅 Apple Technical Q&A 1480

综合起来,你最终会得到类似的东西:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // if you REALLY want to use local timezone, eliminate this line, but I'd really advise sticking with GMT when using formatters to create and parse date strings that you're sending to a remote server
NSString *strToday = [dateFormatter  stringFromDate:[NSDate date]];

NSURL *url = [NSURL URLWithString"http://www.TESTSERVER.com/Items.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod"OST"];

NSString *body = [[NSString stringWithFormat"uID=123456789&item1=30&item2=5&startDate=%@&endDate=%@", strToday, strToday] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

[request setValue"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  // not necessary, but good practice

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // use the data/error/response objects here

    if (data) {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"responseString = %@", responseString);
    } else {
        NSLog(@"error = %@", error);
        NSLog(@"response = %@", response);
    }
}];
[task resume];

// don't try to use the string here, because the above happens asynchronously

坦率地说,我不喜欢这种设置 body 的过于简单的机制(如果任何字段包含特殊字符,例如 +&,以上行不通)。但是,如果参数与您在问题中概述的完全相同,那么这个简单的解决方案应该可以工作。但是,如果您想要在这方面更强大一些,请参阅 https://stackoverflow.com/a/22887238/1271826 中显示的 encodePostParameters 方法。

顺便说一句,我建议考虑使用 AFNetworking ,因为这样可以让您摆脱手动构建请求的麻烦。

但是,回到您最初的问题,如果没有看到服务器代码或您进行更多调试(Charles,确认正确接收到值等),我们无法为您提供进一步的建议。

关于php - 使用 NSData 将日期从 xCode 传递到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29780462/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4