【问题标题】:JSON from PHP to iOS and update from UILabelJSON 从 PHP 到 iOS 并从 UILabel 更新
【发布时间】:2014-03-01 05:51:45
【问题描述】:

在另一位 SO 专家用户的帮助下,我正在实现一种将 viewController 连接到远程 PHP 文件以更新 MySQL 字段值并使其也更新 UILabel 的方法。

我从 PHP 文件中回显的 JSON 值是这种格式:["34"]。

这就是方法:

- (IBAction)votarAction:(id)sender {
    //URL definition where php file is hosted
    dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

    dispatch_async(backgroundQueue, ^{

        int categoriaID = [[detalleDescription objectForKey:@"idEmpresa"] intValue];

        NSString *string = [NSString stringWithFormat:@"%d", categoriaID];
        NSLog(@"ID EMPRESA %@",string);
        NSMutableString *ms = [[NSMutableString alloc] initWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
        [ms appendString:string];
        // URL request
        NSLog(@"URL = %@",ms);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
        //URL connection to the internet
        NSData *responseData = [[NSURLConnection alloc]initWithRequest:request delegate:self];
        NSLog(@"responseData= %@",responseData);

        //Parse JSON
        NSError *error = nil;
        NSArray  * json = [NSJSONSerialization
                                       JSONObjectWithData:responseData
                                       options: NSJSONReadingMutableContainers
                           error: &error];           

        int valoracionNumber = [[json objectAtIndex:0] integerValue];      



        dispatch_async(dispatch_get_main_queue(), ^{
            //update your label

            NSString *labelValue = [NSString stringWithFormat:@"%d", valoracionNumber];
            self.valoracionLabel.text = labelValue;
        });    
    });
}

这是抛出的异常:

2014-02-28 22:45:16.921 Vive Gran Canaria[928:582b] responseData= <NSURLConnection: 0xf050bc0> { request: <NSURLRequest: 0x9de3d40> { URL: http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id=25 } }
2014-02-28 22:45:16.922 Vive Gran Canaria[928:582b] -[NSURLConnection bytes]: unrecognized selector sent to instance 0xf050bc0
2014-02-28 22:45:16.947 Vive Gran Canaria[928:582b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLConnection bytes]: unrecognized selector sent to instance 0xf050bc0'
*** First throw call stack:
(
    0   CoreFoundation                      0x00fca5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x02c5c8b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01067903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x00fba90b ___forwarding___ + 1019
    4   CoreFoundation                      0x00fba4ee _CF_forwarding_prep_0 + 14
    5   Foundation                          0x029a308c -[_NSJSONReader findEncodingFromData:withBOMSkipLength:] + 36
    6   Foundation                          0x029a323b -[_NSJSONReader parseData:options:] + 63
    7   Foundation                          0x029a3800 +[NSJSONSerialization JSONObjectWithData:options:error:] + 161
    8   Vive Gran Canaria                   0x00009bca __44-[DetalleEmpresaViewController votarAction:]_block_invoke + 602
    9   libdispatch.dylib                   0x02f5b7f8 _dispatch_call_block_and_release + 15
    10  libdispatch.dylib                   0x02f704b0 _dispatch_client_callout + 14
    11  libdispatch.dylib                   0x02f5e07f _dispatch_queue_drain + 452
    12  libdispatch.dylib                   0x02f5de7a _dispatch_queue_invoke + 128
    13  libdispatch.dylib                   0x02f5ee1f _dispatch_root_queue_drain + 83
    14  libdispatch.dylib                   0x02f5f137 _dispatch_worker_thread2 + 39
    15  libsystem_c.dylib                   0x03288e72 _pthread_wqthread + 441
    16  libsystem_c.dylib                   0x03270daa start_wqthread + 30
)
libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) 

这是 PHP 文件中与 JSON 数组相呼应的部分:

$arr = array();

$rs = mysql_query("SELECT * FROM tbempresas where idEmpresa='$id'");
while ($obj = mysql_fetch_assoc($rs)) {
    $arr[] = $obj['valoracionEmpresa'];
}
echo json_encode($arr);

【问题讨论】:

    标签: ios json nsurlconnection nsurlrequest


    【解决方案1】:

    您必须创建NSURLConnection 的对象而不是NSData,作为响应,您将在NSURLConnection 的委托方法中获取数据。

    NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];     
    
    #pragma NSURLConnection Delegate Methods
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        //buffer is the object Of NSMutableData and it is global,so declare it in .h file
        buffer = [NSMutableData data];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
    {
        [buffer appendData:data];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        //Here You will get the whole data 
        NSArray *array = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&jsonParsingError];
        //And you can used this array
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        //if any error occurs..
    }
    

    【讨论】:

    • 谢谢您,我认为您是对的,但是您的代码存在一些小问题。在 [buffer appendData:data] 行;有一个编译器警告:“数据”的本地声明隐藏了实例变量。第二个问题是永远不会调用方法 connectionDidFinishLoading。我已经放了一个 NSLog,它没有出现在记录应用程序时。
    • 对于第一个问题:您还采用了全局数据的实例名称,它的名称类似于委托方法,这就是它显示警告的原因。所以请更改全局实例变量的名称,即'webData ' 而不是 '数据'。可以详细说明第二个问题吗??
    • 谢谢Arpit,我已经解决了第一个问题。第二个问题是从未调用方法 connectionDidFinishLoading。我已经放了一个 NSLog 来检查它,它在执行应用程序时没有显示。
    • 游标没有到达四个 NSURLConnection 委托方法中的任何一个,但是在 MySQL 数据库中更新了字段值。
    【解决方案2】:

    这段代码有很多错误。让我们从这一行开始:

    NSData *responseData = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    

    这将返回一个NSURLConnection 的实例,但您将它分配给NSData 变量。这意味着对NSURLConnection 的工作原理存在根本性的误解。由于您使用的是initWithRequest:delegate:,因此连接将被异步处理,这意味着您将无法在votarAction: 中更新您的标签。

    您需要实现NSURLConnectionDataDelegate 协议中的一些方法来读取数据。一旦您检测到连接已关闭,您就可以处理数据并将其写入您的标签。

    至少你需要实现:

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    

    获取响应数据。你真的应该实现额外的委托方法来处理响应状态、失败等......或者,直接使用AFNetworking,然后忘记大部分这些细节。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      相关资源
      最近更新 更多