NSURLConnection not being called properly in objective c for Mac app

160 Views Asked by At

Im calling the below function to have speech converted to text using the google api. Im doing this in the latest version of xcode and Im making this app for mac. The issue is the below function appears to break at NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil]; so I cant check for speech. I've tried an asynchronous dispatch but it didn't seem to help. I also tried a @autoreleasepool {} but it also didn't seem to help . Any help is appreciated!

-(void)processSpeech {
    NSURL *url = [NSURL fileURLWithPath:@"/Users/marcus/Documents/testvoices/okSpeak.query.flac"];

    NSData *flacFile = [NSData dataWithContentsOfURL:url];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?lang=en-US"]];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"Content-Type" forHTTPHeaderField:@"audio/x-flac; rate=16000"];
    [request addValue:@"audio/x-flac; rate=16000" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:flacFile];
    [request setValue:[NSString stringWithFormat:@"%ld",[flacFile length]] forHTTPHeaderField:@"Content-length"];
    NSHTTPURLResponse *urlResponse = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    NSString *rawData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Raw: %@",rawData);

    return rawData;
}
1

There are 1 best solutions below

0
On

If you suspect a problem at your sendSynchronousRequest, you should consider at least three things:

  • Look at the NSHTTPURLResponse object. What did it report? Notably, for HTTP requests, you'll see a statusCode, which can be informative.

  • You should pass it an NSError address pointer, too, and make sure that the error was nil, too:

    NSError *error = nil;
    NSHTTPURLResponse *urlResponse = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    if (!responseData) 
        NSLog(@"sendSynchronousRequest error: %@", error);
    else {
        NSLog(@"sendSynchronousRequest response = %@", urlResponse);
        NSString *rawData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"responseData = %@", rawData);
    }
    
  • What did you get as your rawData string?

By the way, if you're wondering, you want the Content-Type as the header field, not as the value.

// [request addValue:@"Content-Type" forHTTPHeaderField:@"audio/x-flac; rate=16000"];
[request addValue:@"audio/x-flac; rate=16000" forHTTPHeaderField:@"Content-Type"];