Question

With the help from another SO expert user, I am implementing a method to connect a viewController to a remote PHP file to update a MySQL field value and getting it to update also a UILabel.

The JSON value I am echoing from the PHP file is of this format: ["34"].

And this is the method:

- (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;
        });    
    });
}

This is the exception thrown:

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) 

This is the part from the PHP file which echoes the JSON array :

$arr = array();

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

Solution

You have to make an object of NSURLConnection instead of NSData and in response you will be get data in NSURLConnection's delegate method.

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..
}

OTHER TIPS

There is a lot wrong with this code. Let's start with this line:

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

That will return an instance of NSURLConnection, but you are assigning it to an NSData variable. That implies a fundamental misunderstanding of how NSURLConnection works. Since you are using initWithRequest:delegate: the connection will be handled asynchronously, which means you will not be able to update your label inside votarAction:.

You will need to implement some methods from the NSURLConnectionDataDelegate protocol to read the data. Once you detect the connection has closed you can process the data and write it to your label.

At the very least you need to implement:

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

To get the responseData. You should really implement additional delegate methods to handle the response status, failures, etc... Or, just go use AFNetworking and forget about most of these details until later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top