doufu6504 2013-09-15 12:46
浏览 46
已采纳

从从php检索的值设置UILabel文本

I need to automatically get a variable from an existing php file to replace the text of a label when the view controller changes. The change of view controller happens with the push of a button (if this is relevant?) I already made the database on our hosting, and the variables are in place.

1) I need to know how to adress the automation problem
2) I need to know how to get the variable from the php file
  • 写回答

1条回答 默认 最新

  • drbz99867 2013-09-15 14:32
    关注

    Your PHP should return the contents in the variable in a format easily consumed by your Objective-C program, for example JSON. So, for example,

    <?php
    
    // retrieve the value of $result variable any way you want. I'm going to just set the literal
    
    $result = "Hello World!"; 
    
    // now convert to an array
    
    $result_array = array("result" => $result);
    
    // return the json_encoded rendition
    
    echo json_encode($result_array);
    
    ?>
    

    That will end up returning a result that looks like:

    {"result":"Hello World!"}
    

    Now, that JSON can be consumed by your Objective-C code, e.g.:

    NSURL *url = [NSURL URLWithString:@"..."]; // put your URL in here
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    
        // make sure there wasn't a connection error
    
        if (connectionError) {
            NSLog(@"%s: sendAsynchronousRequest error: %@", __FUNCTION__, connectionError);
            return;
        }
    
        // parse the JSON data
    
        NSError *error = nil;
        NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
        // make sure there wasn't a JSON parsing error
    
        if (error) {
            NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, error);
            return;
        }
    
        // now grab the "result" value from the dictionary we parsed from the JSON
        // make sure to do all UI stuff on the main queue, though
    
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.label.text = jsonDictionary[@"result"];
        }];
    }];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大