简体   繁体   English

将数组从PHP发送到NSURLSession

[英]Sending array from PHP to NSURLSession

I'm currently trying to send an array, which contains text and images, from my PHP file to my iOS application using NSURLSession. 我目前正在尝试使用NSURLSession将包含文本和图像的数组从我的PHP文件发送到我的iOS应用程序。 Initially, I've tested with a text-only array which I've converted in JSON format before sending to my application: everything worked fine, but now I need to send an array with text and images, so I've done something like this: 最初,我测试了一个纯文本数组,该数组在发送到应用程序之前已经转换为JSON格式:一切正常,但是现在我需要发送一个包含文本和图像的数组,所以我做了类似的事情这个:
Here is the code: 这是代码:
- PHP (sorry for non - english comments and variable names) -PHP(对非英语注释和变量名表示抱歉)

<?php

    // Connessione al server mediante le credenziali.
    $con = mysql_connect("localhost", "mobdev2015", "Pistacchio1");
    if(!$con){
        die("Server non trovato" . mysql_error());
    }

    // Seleziono il database.
    $db = mysql_select_db("gandalf", $con);
    if(!$db){
        die("Database non trovato" . mysql_error());
    }
    // Mi metto in ascolto per ricevere l'user dall'utente.
    $user = file_get_contents('php://input');


    // Prelevo i dati dello studente, controllando se tutto va bene.
    $sql = "SELECT * FROM Studente WHERE nomeUtente = '$user' ";

    if(!mysql_query($sql, $con))
        die ("Errore nella ricerca dello studente" . mysql_error());

    // Prelevo i valori delle colonne del result set.
    $result = mysql_query($sql, $con);
    $resultSet = mysql_fetch_row($result);

    // Prelevo il percorso dell'immagine dell'università dello studente, dato l'id nel risultato,
    // Facendo sempre i vari controlli del caso.
    $queryImmagineUni = "SELECT immagine FROM Universita WHERE id = '$result[5]'";
    if(!mysql_query($queryImmagineUni, $con))
        die ("Errore nella ricerca dell'università" . mysql_error());
    $result = mysql_query($queryImmagineUni, $con);
    $pathImmagine = mysql_result($result, 0);

    //Inserisco tutti i dati nell'array, ottenendo le immagini mediante file_get_contents.
    $datiutente = array(
        "nome" => $resultSet[1],
        "cognome" => $resultSet[2],
        "email" => $resultSet[4],
        "nomeUtente" => $resultset[6],
        "immagineProfilo" => file_get_contents($resultSet[3]),
        "immagineUni" => file_get_contents($pathImmagine)

    );

    //Mando in output il risultato e chiudo la connessione.
    echo $datiutente;
    mysql_close($con);
?>

immagineProfilo and (aka profileImage) and immagineUni (aka universityImage) are two paths retrieved from database (like "./folder/image.jpg"). immagineProfilo和(aka profileImage)和immagineUni(aka universityImage)是从数据库检索的两条路径(例如“ ./folder/image.jpg”)。

  • iOS: iOS:

     // Setting up the url of the request (we will call a php file). NSURL *url = [[NSURL alloc]initWithString:@"http://inserturlhere.com/userdata.php"]; // Creating the NSMutableRequest object, which will contain the HTML headers and the nickname needed to retrieve data. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url]; // Converting the NSString into NSData to append at MutableURLRequest. NSData *postData = [user dataUsingEncoding:NSASCIIStringEncoding]; //Setting the method to post [request setHTTPMethod:@"POST"]; // Setting the body of the post to the reqeust [request setHTTPBody:postData]; // /* NSURLSession needs a NSURLSessionConfiguration to run, so we instiate a NSURLSessionConfiguration object saying we want to use a default Session, then we create a session with that configuration */ NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; // Starting a dataTask with the request previously defined. The completion handler will be used to manage the response // from the server, stored in a NSURLResponse object. [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSArray *datiUtente = [NSKeyedUnarchiver unarchiveObjectWithData:data]; NSLog(@"%@", datiUtente); }]resume]; 

The problem in this solution is I can't print the content of the array which should contain the contents of the PHP array, but using the debugger I can see data is not NULL, so it seems like something is sent. 此解决方案中的问题是我无法打印应该包含PHP数组内容的数组内容,但是使用调试器,我可以看到数据不是NULL,因此似乎发送了一些东西。

Your PHP line says: 您的PHP行说:

echo $datiutente;

Instead, you want to return JSON, which can be easily parsed by the client. 相反,您想返回JSON,客户端可以轻松地对其进行解析。 So, you should specify that the response will be JSON (and do this before you echo anything): 因此,您应该指定响应为JSON(并在echo任何内容之前执行此操作):

header('Content-type: application/json');

And then, the echoing of the response data would be: 然后,响应数据的回显将是:

echo json_encode($datiutente);

And then to parse it on the client side, you want: 然后在客户端解析它,您需要:

[[session  dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"%@", error);
    }
    if (!data) {
        return;
    }
    NSError *parseError;
    NSArray *datiUtente = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (datiUtente) {
        NSLog(@"responseObject = %@", datiUtente);
    } else {
        NSLog(@"parseError = %@", parseError);
        NSLog(@"responseString = %@", [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding]);
    }
}] resume];

By the way, when you build a JSON response, you cannot include binary data (namely, the image payload). 顺便说一下,构建JSON响应时,不能包含二进制数据(即图像有效负载)。 So if you're going to include the image(s) in the JSON response, make sure to base64_encode them (and then decode them on the client side): 因此,如果要将图像包含在JSON响应中,请确保对它们进行base64_encode (然后在客户端将其解码):

$datiutente = array(
    "nome" => $resultSet[1],
    "cognome" => $resultSet[2],
    "email" => $resultSet[4],
    "nomeUtente" => $resultset[6],
    "immagineProfilo" => base64_encode(file_get_contents($resultSet[3])),
    "immagineUni" => base64_encode(file_get_contents($pathImmagine)),
    "success" => true
);

Personally, I would not be inclined to include the image payload in the JSON ar all (because it increases the size of the response by several orders of magnitude, slowing it down). 就我个人而言,我不会倾向于将图像有效负载包含在JSON ar中(因为它会将响应的大小增加了几个数量级,从而降低了响应速度)。 I might prefer to just include a URL for the image in the response, and let the client request the image itself, if and when it needs it. 我可能更愿意在响应中包含图像的URL,并让客户端在需要图像时以及在需要图像时请求图像本身。 You can make the app more responsive with that sort of design. 您可以通过这种设计使应用程序具有更高的响应速度。 But that's up to you. 但这取决于你。

Note, in addition to the above change, I also added a success code. 注意,除了上述更改之外,我还添加了success代码。 This can be useful so that the client can quickly determine whether the response was successful or not. 这很有用,以便客户端可以快速确定响应是否成功。

Obviously, you want to JSON encode failures, too. 显然,您也想对失败进行JSON编码。 For example, if the MySQL connection failed, you should indicate that in a JSON response (and include the appropriate information provided by MySQL): 例如,如果MySQL连接失败,则应在JSON响应中指出这一点(并包括MySQL提供的适当信息):

if (!$con) {
    $response = array(
        "success" => false, 
        "message" => "Server non trovato",
        "sqlerror" => mysql_error(), 
        "sqlerrno" => mysql_errno()
    );

    echo json_encode($response);
    exit();
}

Once you get this working, a few other observations: 完成这项工作后,还有其他一些观察结果:

  1. Do not just take the posted data and use it in a query. 不要仅仅获取发布的数据并在查询中使用它。 That exposes you to SQL injection attacks. 这使您容易受到SQL注入攻击。 Remember to mysql_real_escape_string that input before using it in a query. 在查询中使用输入之前,请记住先输入mysql_real_escape_string

  2. I'd probably change the request created by the client code to be a application/x-www-form-urlencoded request (eg, user=... ) or a application/json request (eg use NSJSONSerialization dataWithJSONObject to build request that looks like {"user": "..."} ). 我可能NSJSONSerialization dataWithJSONObject客户端代码创建的请求更改为application/x-www-form-urlencoded请求(例如, user=... )或application/json请求(例如,使用NSJSONSerialization dataWithJSONObject来构建看起来像这样的请求像{"user": "..."} )。 and then parse it on the server side. 然后在服务器端解析它。

  3. Note this MySQL interface is deprecated. 请注意,不建议使用此MySQL接口。 As the docs say: 正如文档所说:

    This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. 此扩展在PHP 5.5.0中已弃用,在PHP 7.0.0中已删除。 Instead, the MySQLi or PDO_MySQL extension should be used. 相反,应使用MySQLiPDO_MySQL扩展。 See also MySQL: choosing an API guide and related FAQ for more information. 另请参见MySQL:选择API指南和相关的FAQ,以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM