Rectangle 27 6

SBJSON *parser = [[SBJSON alloc] init];

NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];

url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];

NSData *response = [NSURLConnection sendSynchronousRequest:request  returningResponse:nil error:nil];

NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]

NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];

 NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];

    for(NSDictionary *news in news_array)
{

    @try {
        [title_arr addObject:[news valueForKey:@"gtitle"]];    //values Add to title array

    }
    @catch (NSException *exception) {

        [title_arr addObject:[NSString stringWithFormat:@""]];
    }

Thanks for providing a code sample!

objective c - iPhone/iOS JSON parsing tutorial - Stack Overflow

iphone objective-c ios json uitableview
Rectangle 27 27

I figured out the trick is to read the receipt as data then base 64 encode it from the data. Here's what worked for me if it helps anyone else. Also thanks to this thread for the base 64 encoding: Converting NSData to base64

// this returns an NSDictionary of the app's store receipt, status=0 for good, -1 for bad
- (NSDictionary *) getStoreReceipt:(BOOL)sandbox {

    NSArray *objects;
    NSArray *keys;
    NSDictionary *dictionary;

    BOOL gotreceipt = false;

    @try {

        NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];

        if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]]) {

            NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];

            NSString *receiptString = [self base64forData:receiptData];

            if (receiptString != nil) {

                objects = [[NSArray alloc] initWithObjects:receiptString, nil];
                keys = [[NSArray alloc] initWithObjects:@"receipt-data", nil];
                dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

                NSString *postData = [self getJsonStringFromDictionary:dictionary];

                NSString *urlSting = @"https://buy.itunes.apple.com/verifyReceipt";
                if (sandbox) urlSting = @"https://sandbox.itunes.apple.com/verifyReceipt";

                dictionary = [self getJsonDictionaryWithPostFromUrlString:urlSting andDataString:postData];

                if ([dictionary objectForKey:@"status"] != nil) {

                    if ([[dictionary objectForKey:@"status"] intValue] == 0) {

                        gotreceipt = true;

                    }
                }

            }

        }

    } @catch (NSException * e) {
        gotreceipt = false;
    }

    if (!gotreceipt) {
        objects = [[NSArray alloc] initWithObjects:@"-1", nil];
        keys = [[NSArray alloc] initWithObjects:@"status", nil];
        dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
    }

    return dictionary;
}



- (NSDictionary *) getJsonDictionaryWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
    NSString *jsonString = [self getStringWithPostFromUrlString:urlString andDataString:dataString];
    NSLog(@"%@", jsonString); // see what the response looks like
    return [self getDictionaryFromJsonString:jsonString];
}


- (NSDictionary *) getDictionaryFromJsonString:(NSString *)jsonstring {
    NSError *jsonError;
    NSDictionary *dictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData:[jsonstring dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
    if (jsonError) {
       dictionary = [[NSDictionary alloc] init];
    }
    return dictionary;
}


- (NSString *) getStringWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
    NSString *s = @"";
    @try {
        NSData *postdata = [dataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postlength = [NSString stringWithFormat:@"%d", [postdata length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:urlString]];
            [request setTimeoutInterval:60];
        [request setHTTPMethod:@"POST"];
        [request setValue:postlength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postdata];
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (data != nil) {
            s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }
    @catch (NSException *exception) { 
        s = @"";
    } 
    return s;
}


// from https://stackoverflow.com/questions/2197362/converting-nsdata-to-base64
- (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
getJsonStringFromDictionary
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];

To be more precise: getJsonStringFromDictionary -> NSError *error = nil; NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; NSString *postString = @""; if (! postData) { NSLog(@"Got an error: %@", error); } else { postString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]; }

NSString *password = @"your shared secret string"; objects = [[NSArray alloc] initWithObjects:receiptString, password, nil]; keys = [[NSArray alloc] initWithObjects:@"receipt-data", @"password", nil];

Hello @Tom, This approach should be used if we have our server right?

nsstring - How to get iOS appStoreReceiptURL into Base 64 Encoded Stri...

ios nsstring app-store ios7
Rectangle 27 0

SBJSON *parser = [[SBJSON alloc] init];

NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];

url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];

NSData *response = [NSURLConnection sendSynchronousRequest:request  returningResponse:nil error:nil];

NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]

NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];

 NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];

    for(NSDictionary *news in news_array)
{

    @try {
        [title_arr addObject:[news valueForKey:@"gtitle"]];    //values Add to title array

    }
    @catch (NSException *exception) {

        [title_arr addObject:[NSString stringWithFormat:@""]];
    }

Thanks for providing a code sample!

objective c - iPhone/iOS JSON parsing tutorial - Stack Overflow

iphone objective-c ios json uitableview
Rectangle 27 0

Looking for this specific error i found that this exception happens thenyou try call the method initWithData:encoding: passing a NSString instead of a NSData

please check in your code, when you save the password, do you save it as a string? if you do you don't have to initWithData:encoding: to read, you can or read as it is or NSString initWithString:

If that was the case, the code would crash every time, not just in the background.

ios - NSString from NSData crash when run in background fetch - Stack ...

ios nsstring nsdata unrecognized-selector keychainitemwrapper
Rectangle 27 0

The main problem with the example code is that many items are encoded as NSData objects where NSString objects should be used (kSecAttrAccount, kSecAttrLabel, kSecAttrDescription and kSecAttrServer). I'm surprised that this issue wouldn't result in an exception, although behavior on iOS may be different to Lion (where I looked at this).

It may also be that specifying kSecReturnRef instead of kSecReturnPersistentRef may be more appropriate (from the documentation, using kSecReturnPersistentRef vends "a persistent reference may be stored on disk or passed between processes"). It is a way to specify a keychain item for use with SecItemUpdate, SecItemDelete or SecItemCopyMatching using it with kSecMatchItemList that has the advantage of persistence between sessions (say using NSUserDefaults) or passing to another process. If the item is only used within the lifetime of the application, or it is more appropriate to find using other attributes, then the item reference using kSecReturnRef is likely more appropriate.

iphone - iOS error errSecInteractionNotAllowed or –25308 on SecItemAdd...

iphone objective-c xcode ios jailbreak
Rectangle 27 0

#define TIMEOUT_INTERVAL 60
    #define CONTENT_TYPE @"Content-Type"
    #define URL_ENCODED @"application/x-www-form-urlencoded"
    #define GET @"GET"
    #define POST @"POST"

     -(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
        {
            NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
            [req setHTTPMethod:GET];
            return req;
        }

        -(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
        {
            NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
            [req setHTTPMethod:POST];
            [req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
            [req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
            return req;
        }

@try
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSString *_postData = [NSString stringWithFormat:@"user_name=%@&password=%@",@"user_name",@"password"];
    NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
   [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)
         {
             [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
             NSLog(@"error==%@==",[error localizedDescription]);
         }
         else
         {
             NSError *errorInJsonParsing;
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];

             if(errorInJsonParsing) //error parsing in json
             {
                 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                 NSLog(@"error in json==%@==",[error localizedDescription]);
             }
             else
             {
                 //do some operations
             }
         }
     }];
}
@catch(NSException *exception)
{
    NSLog(@"error in exception==%@==",[exception description]);
}



same way it works for the get method, just call the
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url];
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];

How do you use that @try? Ive pasted this code into an NSObject class and everything is fine except for the @try line which gives an error unexpected @ in program. Does the @try@catch have to go inside a method?

iphone - HTTP Post method php and ios - Stack Overflow

iphone http-post
Rectangle 27 0

I just checked with my sample string. **If you could have given me your string then i could have checked out with my following sample code.

NSString *msg = [NSString stringWithFormat:@"tell me \"where\"\n"
                  "is\n"
                  "wrong"];
NSData *theData = [msg dataUsingEncoding:NSASCIIStringEncoding];
NSString* theString = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];

BOOL isValid = [NSJSONSerialization isValidJSONObject:theString];
NSLog(@"Value %d %@",isValid, theString);

For me The value is coming 0 and tell me "where"

iphone - converting NSString to NSData - [NSString dataUsingEncoding] ...

iphone json ios5 nsdata
Rectangle 27 0

You guys pointed me in the winning direction by questioning type of object ... I was extracting it from a dictionary and assumed it was an NSData object, but in reality it was already an NSString. Ugh. Thanks a lot!

ios - Exception on NSData to NSString? - Stack Overflow

ios objective-c
Rectangle 27 0

/**
    HTTP CONSTANTS
 **/
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE @"Content-Type"
#define URL_ENCODED @"application/x-www-form-urlencoded"
#define GET @"GET"
#define POST @"POST"

-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
    [req setHTTPMethod:POST];
    [req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
    [req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
    return req;
}


-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
    [req setHTTPMethod:GET];
    return req;
}


    NSString *_postData = {<Your postData>}
    NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:LOGIN_URL postData:_postData];
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error)// it means server error
         {
             //error while connecting server
         }
         else
         {
             NSError *errorInJsonParsing;
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
             if(errorInJsonParsing) //error parsing in json
             {
                 //error in json parsing
             }
             else
             {
                 @try
                 {
                    NSLog(@"json==%@",json);
                    // json is basically in key value format which is NSDictionary
                    // if you get the url of image inside this json, then again hit the url to get the image ( u can get the image in NSData which is declared above )
                 }
                 @catch (NSException *exception)
                 {
                     //exception
                 }

             }
         }
     }];

iphone - How do I fetch Data from a URL that contain an Image in iOS? ...

iphone ios ios6
Rectangle 27 0

The main problem with the example code is that many items are encoded as NSData objects where NSString objects should be used (kSecAttrAccount, kSecAttrLabel, kSecAttrDescription and kSecAttrServer). I'm surprised that this issue wouldn't result in an exception, although behavior on iOS may be different to Lion (where I looked at this).

It may also be that specifying kSecReturnRef instead of kSecReturnPersistentRef may be more appropriate (from the documentation, using kSecReturnPersistentRef vends "a persistent reference may be stored on disk or passed between processes"). It is a way to specify a keychain item for use with SecItemUpdate, SecItemDelete or SecItemCopyMatching using it with kSecMatchItemList that has the advantage of persistence between sessions (say using NSUserDefaults) or passing to another process. If the item is only used within the lifetime of the application, or it is more appropriate to find using other attributes, then the item reference using kSecReturnRef is likely more appropriate.

iphone - iOS error errSecInteractionNotAllowed or –25308 on SecItemAdd...

iphone objective-c xcode ios jailbreak
Rectangle 27 0

Looking for this specific error i found that this exception happens thenyou try call the method initWithData:encoding: passing a NSString instead of a NSData

please check in your code, when you save the password, do you save it as a string? if you do you don't have to initWithData:encoding: to read, you can or read as it is or NSString initWithString:

If that was the case, the code would crash every time, not just in the background.

ios - NSString from NSData crash when run in background fetch - Stack ...

ios nsstring nsdata unrecognized-selector keychainitemwrapper
Rectangle 27 0

The main problem with the example code is that many items are encoded as NSData objects where NSString objects should be used (kSecAttrAccount, kSecAttrLabel, kSecAttrDescription and kSecAttrServer). I'm surprised that this issue wouldn't result in an exception, although behavior on iOS may be different to Lion (where I looked at this).

It may also be that specifying kSecReturnRef instead of kSecReturnPersistentRef may be more appropriate (from the documentation, using kSecReturnPersistentRef vends "a persistent reference may be stored on disk or passed between processes"). It is a way to specify a keychain item for use with SecItemUpdate, SecItemDelete or SecItemCopyMatching using it with kSecMatchItemList that has the advantage of persistence between sessions (say using NSUserDefaults) or passing to another process. If the item is only used within the lifetime of the application, or it is more appropriate to find using other attributes, then the item reference using kSecReturnRef is likely more appropriate.

iphone - iOS error errSecInteractionNotAllowed or –25308 on SecItemAdd...

iphone objective-c xcode ios jailbreak
Rectangle 27 0

+ (BOOL)exportDataToURL:(NSString *)filePath error:(NSError **)error andAsset:(ALAsset *)asset
{
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    if (!handle)
        return NO;

    static const NSUInteger BufferSize = 1024 * 1024;

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;

    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:error];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch(NSException *exception) {
            free(buffer);

            return NO;
        }
    } while (bytesRead > 0);

    free(buffer);
    return YES;
}

iphone - Using ALAssetsLibrary and ALAsset take out Image as NSData - ...

iphone uiimage nsdata exif uiimagejpegrepresentation
Rectangle 27 0

NSUnicodeStringEncoding
NSASCIIStringEncoding

with this:

NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding];

iphone - converting NSString to NSData - [NSString dataUsingEncoding] ...

iphone json ios5 nsdata
Rectangle 27 0

MyUpdate *myUpdate = [[MyUpdate alloc] init];

    [[RKClient sharedClient].HTTPHeaders setValue:RKMIMETypeJSON forKey:@"Content-Type"];      

    // Prepare the request
    NSMutableDictionary *requestDictionary = [[NSMutableDictionary alloc] init];
    [requestDictionary setObject:yourIndexVar forKey:@"Index"];
    [requestDictionary setObject:fileName forKey:@"fileName"];

    NSError* error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestDictionary options:NSJSONWritingPrettyPrinted error:&error];

    NSString *JSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    RKParams *params = [RKRequestSerialization serializationWithData:[JSON dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON]; 


    // Prepare the response mapping
    RKObjectMapping* objectMapping = [RKObjectMapping mappingForClass:MyUpdate class]];
    [objectMapping mapKeyPath:@"name" toAttribute:@"Name"];    
    [objectMapping mapForKeyPath:@"value" toAttribute:@"Value"];

    [objectMapping mapKeyPath:@"update" toRelationship:@"Update" withMapping:objectMapping];


    RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"BASE_URL"];  
    [manager setClient:[RKClient sharedClient]];
    [manager.mappingProvider setMapping:objectMapping forKeyPath:@"****Result"];  

    RKObjectLoader *objectLoader = [manager loaderWithResourcePath:@"RELATIVE_PATH"];   

    // For example:
    // BASE_URL = "http://mysite.com/"
    // RELATIVE_PATH (service end-point uri) = "/ServiceName/SaveFile/"
    // **** = "SaveFile"

    objectLoader.targetObject = myUpdate;
    objectLoader.method = RKRequestMethodPOST;
    objectLoader.params = params;
    objectLoader.delegate = self;

    @try 
    {
        [objectLoader send];
    }
    @catch (NSException *exception) 
     {
         NSLog(@"NSException - Name: %@, Reason: %@", exception.name, exception.reason);
     }

iphone - Getting an error when using RestKit's RKObjectMapping and RKO...

iphone objective-c json restkit
Rectangle 27 0

Seems that your "delegate" method gets called with a NSString instead of a NSData. Copying the received object won't help you in this case, as you're just copying a string into another string. You'll need to dig deeper and see why dataReceived: doesn't receive the expected NSData object.

ios - Exception Parsing Copy of NSData to NSString - Stack Overflow

ios objective-c nsstring nsdata
Rectangle 27 0

- (void)viewDidLoad
{


 @try {

    [super viewDidLoad];

    self.wordToSpeech = @"What do functional foods mean? According to the April 2009 position on functional foods by the American Dietetic Association (ADA), all foods are functional at some level, because they provide nutrients that furnish energy, sustain growth, or maintain and repair vital processes. While the functional food category, per se, is not officially recognized by the Food and Drug Administration, the ADA considers functional foods to be whole foods and fortified, enriched, or enhanced foods that have a potentially beneficial effect on health. Thus a list of functional foods might be as varied as nuts, calcium-fortified orange juice, energy bars, bottled teas and gluten-free foods. While many functional foodsfrom whole grain breads to wild salmonprovide obvious health benefits, other functional foods like acai berry or brain development foods may make overly optimistic promises. Thus, its important to evaluate each functional food on the basis of scientific evidence before you buy into their benefits";

    [self sentenceToSpeech];
}
@catch (NSException *exception)
{
    NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
}

}

- (void)sentenceToSpeech{

@try {

    NSString *sentenceToSpeech = @"";

    if (0 == self.totalCountPlayed) {

        sentenceToSpeech = [self.wordToSpeech substringToIndex:100];
        self.totalCountPlayed = 100;

    }
    else{

        NSString *tempString = [self.wordToSpeech substringFromIndex:self.totalCountPlayed];

        if (100 <= [tempString length]) {

            sentenceToSpeech = [tempString substringToIndex:100];
            self.totalCountPlayed += 100;
        }
        else
        {
            sentenceToSpeech = tempString;
            self.totalCountPlayed = 0;
        }
    }

    [self speechUsingGoogleTTS:sentenceToSpeech];
}
@catch (NSException *exception)
{
    NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
}

}

- (void)speechUsingGoogleTTS:(NSString *)sentenceToSpeeh{

@try {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.mp3"];

    NSString *urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=en&q=%@",sentenceToSpeeh];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url] ;
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" forHTTPHeaderField:@"User-Agent"];
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    [data writeToFile:path atomically:YES];


    NSError        *err;
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:
                       [NSURL fileURLWithPath:path] error:&err];

        [self.player prepareToPlay];
        [self.player setNumberOfLoops:0];
        [self.player setDelegate:self];
        [self.player play];

    }
}
@catch (NSException *exception)
{
    NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
}
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

@try {

    if (0 != self.totalCountPlayed) {

        [self sentenceToSpeech];
    }
}
@catch (NSException *exception)
{
    NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
}
}

iphone - Text to speech not working - Stack Overflow

iphone ios text-to-speech
Rectangle 27 0

- (IBAction)startSOAP:(id)sender

{   
       NSLog(@"\n{AppDelegate} startSOAP start");

       // create the request
       NSError **myError;
       NSHTTPURLResponse **serverResponse;
       NSData *serverData;
       NSDictionary *headerFieldsDict = [NSDictionary
                                      dictionaryWithObjectsAndKeys:@"Apple iPhone",@"User-   Agent",
                                      @"text/xml; charset=utf-8", @"Content-Type",
                                      @"soapAction",@"SOAP_ACTION",nil];
       @try {

        // 1) The Request String.
        // Note: smsXMLString contains the entire SMS SOAP envelope, without the <? XML declaration command >.
        NSString *smsXMLPath = [[NSBundle mainBundle] pathForResource:@"sms" ofType:@"xml"];
        self.smsXMLString = [NSString stringWithContentsOfFile:smsXMLPath encoding:NSUTF8StringEncoding error:myError];

        // -----------------------
        // 2)  Create the request.
        NSMutableURLRequest  *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theServerURL]
                                                                 cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                             timeoutInterval:10.0];

        // -----------------------
        // 2a)  Modify the Request from default 'GET' to 'POST':
        [theRequest setHTTPMethod:@"POST"];

        // 2b) Modify the Headers:
        [theRequest setAllHTTPHeaderFields:headerFieldsDict];

        // 2c) Sent the Contents of the Body to the SOAP/XML data:
        [theRequest setHTTPBody:[self.smsXMLString dataUsingEncoding:NSUTF8StringEncoding]];
        // -----------------------
        // 3)  Get Synchronous Data:
        serverData = [NSURLConnection sendSynchronousRequest:theRequest
                                           returningResponse:serverResponse
                                                       error:myError];

        // -----------------------
        // 4)  Convert Synchronous Data into Human-Readable String (Unicode 8) format:
        NSString *serverDataString = [[[NSString alloc] initWithData:serverData encoding:NSUTF8StringEncoding] retain];

        [[soapResponse layoutManager]replaceTextStorage:[[NSTextStorage alloc] initWithString:serverDataString]];

        [serverDataString release];

    } 
     @catch (id e) {
        NSLog(@"\n**** {startSOAP} EXCEPTION: %@ ****\n",e);
        self.statusLine.stringValue = [NSString stringWithFormat:@"*** Exception flagged: %@ ***",e];
                } 
    @finally {

        NSLog(@"\n{startSoap} end.");
    }
}

ios - How to send request with XML - Stack Overflow

ios objective-c xml cocoa-touch nsurlrequest
Rectangle 27 0

User defaults is, basically, a property list. Property lists are similar to JSON and can only store specific types of data -- NSString, NSNumber, NSData, NSDate, NSArray, NSDictionary. If you try to store anything else in a user default, you'll get an exception. Property lists also can't handle arbitrary object graphs, only trees.

You could always take your custom state and convert it into a property-list compatible data structure, then store it in user defaults; but then you're basically implementing an object serialization mechanism, and you might as well use the more powerful one that's already provided by NSArchiver.

objective c - When do you use encodeWithCoder: and initWithCoder: on t...

iphone objective-c cocoa-touch initwithcoder
Rectangle 27 0

Looking for this specific error i found that this exception happens thenyou try call the method initWithData:encoding: passing a NSString instead of a NSData

please check in your code, when you save the password, do you save it as a string? if you do you don't have to initWithData:encoding: to read, you can or read as it is or NSString initWithString:

If that was the case, the code would crash every time, not just in the background.

ios - NSString from NSData crash when run in background fetch - Stack ...

ios nsstring nsdata unrecognized-selector keychainitemwrapper