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 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题