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 9

NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];

NSString *encReceipt = [receiptData base64EncodedStringWithOptions:0];

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

ios nsstring app-store ios7
Rectangle 27 68

Historically we would have directed you to one of the many third-party base 64 libraries (as discussed in the other answers) for converting from binary data to base 64 string (and back), but iOS 7 now has native base 64 encoding (and exposes the previously private iOS 4 methods, in case you need to support earlier versions of iOS).

Thus to convert NSData to NSString base 64 representation you can use base64EncodedStringWithOptions. If you have to support iOS versions prior to 7.0 as well, you can do:

NSString *string;

if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
    string = [data base64EncodedStringWithOptions:kNilOptions];  // iOS 7+
} else {
    string = [data base64Encoding];                              // pre iOS7
}

And to convert base 64 NSString back to NSData you can use initWithBase64EncodedString. Likewise, if you need to support iOS versions prior to 7.0, you can do:

NSData *data;

if ([NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)]) {
    data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];  // iOS 7+
} else {
    data = [[NSData alloc] initWithBase64Encoding:string];                           // pre iOS7
}

Obviously, if you don't need backward compatibility with iOS versions prior to 7.0, it's even easier, just use base64EncodedStringWithOptions or initWithBase64EncodedString, respectively, and don't bother with the run-time check for earlier iOS versions. In fact, if you use the above code when your minimum target is iOS 7 or greater, you'll actually get a compiler warning about the deprecated methods. So, in iOS 7 and greater, you would simply convert to base 64 string with:

NSString *string = [data base64EncodedStringWithOptions:kNilOptions];
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];

Perfect, thank you very much for the explanation

It's a shame this answer is buried beneath all those custom implementations. It's a weakness of SO, where a more appropriate solution may have come about long after the original question was asked, that solution now has to compete with what was previously accepted.

why the hell answers like this are not on top :( , i spent a lot of time processing all the answers above T__T

ios - How do I do base64 encoding on iphone-sdk? - Stack Overflow

ios objective-c base64
Rectangle 27 68

Historically we would have directed you to one of the many third-party base 64 libraries (as discussed in the other answers) for converting from binary data to base 64 string (and back), but iOS 7 now has native base 64 encoding (and exposes the previously private iOS 4 methods, in case you need to support earlier versions of iOS).

Thus to convert NSData to NSString base 64 representation you can use base64EncodedStringWithOptions. If you have to support iOS versions prior to 7.0 as well, you can do:

NSString *string;

if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
    string = [data base64EncodedStringWithOptions:kNilOptions];  // iOS 7+
} else {
    string = [data base64Encoding];                              // pre iOS7
}

And to convert base 64 NSString back to NSData you can use initWithBase64EncodedString. Likewise, if you need to support iOS versions prior to 7.0, you can do:

NSData *data;

if ([NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)]) {
    data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];  // iOS 7+
} else {
    data = [[NSData alloc] initWithBase64Encoding:string];                           // pre iOS7
}

Obviously, if you don't need backward compatibility with iOS versions prior to 7.0, it's even easier, just use base64EncodedStringWithOptions or initWithBase64EncodedString, respectively, and don't bother with the run-time check for earlier iOS versions. In fact, if you use the above code when your minimum target is iOS 7 or greater, you'll actually get a compiler warning about the deprecated methods. So, in iOS 7 and greater, you would simply convert to base 64 string with:

NSString *string = [data base64EncodedStringWithOptions:kNilOptions];
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];

Perfect, thank you very much for the explanation

It's a shame this answer is buried beneath all those custom implementations. It's a weakness of SO, where a more appropriate solution may have come about long after the original question was asked, that solution now has to compete with what was previously accepted.

why the hell answers like this are not on top :( , i spent a lot of time processing all the answers above T__T

ios - How do I do base64 encoding on iphone-sdk? - Stack Overflow

ios objective-c base64
Rectangle 27 2

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring{

    //Assume this array is the autocomplete array for which you get data from server

    NSMutableArray *autoCompleteArray = [[NSMutableArray alloc] initWithObjects:@"Coffee",@"Cricket",@"Volleyboll",nil];

    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

   // This is to create predicate filter for getting matched text 

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@",text];

// store matched data for autocompletion in results array and reload data in your tableview based on this array's data

   NSArray *resultArray = [[NSArray alloc] initWithArray:[autoCompleteArray filteredArrayUsingPredicate:predicate]];
}

this is logic for autocomplete search and displaying it in your tableview.

tableview is not being called now while entered text in textield

iphone - AutoComplete for UITextfield in iOS - Stack Overflow

ios iphone autocomplete textfield
Rectangle 27 2

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring{

    //Assume this array is the autocomplete array for which you get data from server

    NSMutableArray *autoCompleteArray = [[NSMutableArray alloc] initWithObjects:@"Coffee",@"Cricket",@"Volleyboll",nil];

    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

   // This is to create predicate filter for getting matched text 

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@",text];

// store matched data for autocompletion in results array and reload data in your tableview based on this array's data

   NSArray *resultArray = [[NSArray alloc] initWithArray:[autoCompleteArray filteredArrayUsingPredicate:predicate]];
}

this is logic for autocomplete search and displaying it in your tableview.

tableview is not being called now while entered text in textield

iphone - AutoComplete for UITextfield in iOS - Stack Overflow

ios iphone autocomplete textfield
Rectangle 27 3

This is based on something I originally wrote for Cut out a part of a long NSString. I copied the NSXMLParserDelegate code from that iOS project into an OS X project. It gets the text from a specific object in a web page.

@interface so7576593AppDelegate : NSObject <NSApplicationDelegate, NSXMLParserDelegate> {
    NSWindow *window;
    IBOutlet NSTextField *textField;

    NSMutableString *divCharacters;
    BOOL captureCharacters; 
}

@property (assign) IBOutlet NSWindow *window;

@end
#import "so7576593AppDelegate.h"

@implementation so7576593AppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    captureCharacters = NO;
    NSURL *theURL = [NSURL URLWithString:@"http://maxnerios.yolasite.com/"];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
    [parser setDelegate:self];
    [parser parse];
    [parser release];

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqual:@"div"] && [[attributeDict objectForKey:@"id"] isEqual:@"I3_sys_txt"]) {
        captureCharacters = YES;
        divCharacters = [[NSMutableString alloc] initWithCapacity:500];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (captureCharacters) {
        //from parser:foundCharacters: docs:
        //The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. 
        //Because string may be only part of the total character content for the current element, you should append it to the current 
        //accumulation of characters until the element changes.
        [divCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if (captureCharacters) {
        captureCharacters = NO;
        [textField setStringValue:divCharacters];
        [divCharacters release];
    }
}

@end

Thanks A lot. I was able to get it hooked up and I spent a lot of time understanding it. Now I can build on this and try more complicated ones.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

objective c - Simple and concise desktop Cocoa NSXMLParser example? - ...

objective-c cocoa nsxmlparser sax
Rectangle 27 0

- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring{

    //Assume this array is the autocomplete array for which you get data from server

    NSMutableArray *autoCompleteArray = [[NSMutableArray alloc] initWithObjects:@"Coffee",@"Cricket",@"Volleyboll",nil];

    text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];

   // This is to create predicate filter for getting matched text 

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@",text];

// store matched data for autocompletion in results array and reload data in your tableview based on this array's data

   NSArray *resultArray = [[NSArray alloc] initWithArray:[autoCompleteArray filteredArrayUsingPredicate:predicate]];
}

this is logic for autocomplete search and displaying it in your tableview.

tableview is not being called now while entered text in textield

iphone - AutoComplete for UITextfield in iOS - Stack Overflow

ios iphone autocomplete textfield
Rectangle 27 0

+ (NSString*) unescapeUnicodeString:(NSString*)string
{
// unescape quotes and backwards slash
NSString* unescapedString = [string stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
unescapedString = [unescapedString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];

// tokenize based on unicode escape char
NSMutableString* tokenizedString = [NSMutableString string];
NSScanner* scanner = [NSScanner scannerWithString:unescapedString];
while ([scanner isAtEnd] == NO)
{
    // read up to the first unicode marker
    // if a string has been scanned, it's a token
    // and should be appended to the tokenized string
    NSString* token = @"";
    [scanner scanUpToString:@"\\u" intoString:&token];
    if (token != nil && token.length > 0)
    {
        [tokenizedString appendString:token];
        continue;
    }

    // skip two characters to get past the marker
    // check if the range of unicode characters is
    // beyond the end of the string (could be malformed)
    // and if it is, move the scanner to the end
    // and skip this token
    NSUInteger location = [scanner scanLocation];
    NSInteger extra = scanner.string.length - location - 4 - 2;
    if (extra < 0)
    {
        NSRange range = {location, -extra};
        [tokenizedString appendString:[scanner.string substringWithRange:range]];
        [scanner setScanLocation:location - extra];
        continue;
    }

    // move the location pas the unicode marker
    // then read in the next 4 characters
    location += 2;
    NSRange range = {location, 4};
    token = [scanner.string substringWithRange:range];
    unichar codeValue = (unichar) strtol([token UTF8String], NULL, 16);
    [tokenizedString appendString:[NSString stringWithFormat:@"%C", codeValue]];

    // move the scanner past the 4 characters
    // then keep scanning
    location += 4;
    [scanner setScanLocation:location];
}

// done
return tokenizedString;
}

+ (NSString*) escapeUnicodeString:(NSString*)string
{
// lastly escaped quotes and back slash
// note that the backslash has to be escaped before the quote
// otherwise it will end up with an extra backslash
NSString* escapedString = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
escapedString = [escapedString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

// convert to encoded unicode
// do this by getting the data for the string
// in UTF16 little endian (for network byte order)
NSData* data = [escapedString dataUsingEncoding:NSUTF16LittleEndianStringEncoding allowLossyConversion:YES];
size_t bytesRead = 0;
const char* bytes = data.bytes;
NSMutableString* encodedString = [NSMutableString string];

// loop through the byte array
// read two bytes at a time, if the bytes
// are above a certain value they are unicode
// otherwise the bytes are ASCII characters
// the %C format will write the character value of bytes
while (bytesRead < data.length)
{
    uint16_t code = *((uint16_t*) &bytes[bytesRead]);
    if (code > 0x007E)
    {
        [encodedString appendFormat:@"\\u%04X", code];
    }
    else
    {
        [encodedString appendFormat:@"%C", code];
    }
    bytesRead += sizeof(uint16_t);
}

// done
return encodedString;
}

it must be legal to kill server-side developer, just for forcing me to use this solution. @Christoph nice working code by the way. Cheers!

Using Objective C/Cocoa to unescape unicode characters, ie \u1234 - St...

objective-c cocoa unicode
Rectangle 27 0

//Consider we have the image saved in UIImage
UIImage * myImage;

//Get the data 
NSData imageData = UIImageJPEGRepresentation(myImage, 1.0);

//I am using this extension to encode to base 64 (https://gist.github.com/Abizern/1643491)
//Article from the save author http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
NSString *encodedImage = [imageData base64EncodedString];
encodedImage

But when it's converted to a JPEG it's compressed. and because it is used on a calculation function I fear that it will result in errors.

OpenCV sending image over HTTP with base64 on iOS with C++ - Stack Ove...

c++ ios post opencv base64
Rectangle 27 0

The easiest way is to use an NSScanner, specifically the methods scanHexInt: or scanHexLongLong:. Another possibility is to get the C string from the NSString and use C-style functions such as strtol (with base 16).

objective c - How to convert hexadecimal string to decimal? - Stack Ov...

objective-c ios decimal hex
Rectangle 27 0

This is based on something I originally wrote for Cut out a part of a long NSString. I copied the NSXMLParserDelegate code from that iOS project into an OS X project. It gets the text from a specific object in a web page.

@interface so7576593AppDelegate : NSObject <NSApplicationDelegate, NSXMLParserDelegate> {
    NSWindow *window;
    IBOutlet NSTextField *textField;

    NSMutableString *divCharacters;
    BOOL captureCharacters; 
}

@property (assign) IBOutlet NSWindow *window;

@end
#import "so7576593AppDelegate.h"

@implementation so7576593AppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    captureCharacters = NO;
    NSURL *theURL = [NSURL URLWithString:@"http://maxnerios.yolasite.com/"];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
    [parser setDelegate:self];
    [parser parse];
    [parser release];

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqual:@"div"] && [[attributeDict objectForKey:@"id"] isEqual:@"I3_sys_txt"]) {
        captureCharacters = YES;
        divCharacters = [[NSMutableString alloc] initWithCapacity:500];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (captureCharacters) {
        //from parser:foundCharacters: docs:
        //The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. 
        //Because string may be only part of the total character content for the current element, you should append it to the current 
        //accumulation of characters until the element changes.
        [divCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if (captureCharacters) {
        captureCharacters = NO;
        [textField setStringValue:divCharacters];
        [divCharacters release];
    }
}

@end

Thanks A lot. I was able to get it hooked up and I spent a lot of time understanding it. Now I can build on this and try more complicated ones.

objective c - Simple and concise desktop Cocoa NSXMLParser example? - ...

objective-c cocoa nsxmlparser sax
Rectangle 27 0

This is based on something I originally wrote for Cut out a part of a long NSString. I copied the NSXMLParserDelegate code from that iOS project into an OS X project. It gets the text from a specific object in a web page.

@interface so7576593AppDelegate : NSObject <NSApplicationDelegate, NSXMLParserDelegate> {
    NSWindow *window;
    IBOutlet NSTextField *textField;

    NSMutableString *divCharacters;
    BOOL captureCharacters; 
}

@property (assign) IBOutlet NSWindow *window;

@end
#import "so7576593AppDelegate.h"

@implementation so7576593AppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    captureCharacters = NO;
    NSURL *theURL = [NSURL URLWithString:@"http://maxnerios.yolasite.com/"];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
    [parser setDelegate:self];
    [parser parse];
    [parser release];

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqual:@"div"] && [[attributeDict objectForKey:@"id"] isEqual:@"I3_sys_txt"]) {
        captureCharacters = YES;
        divCharacters = [[NSMutableString alloc] initWithCapacity:500];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (captureCharacters) {
        //from parser:foundCharacters: docs:
        //The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. 
        //Because string may be only part of the total character content for the current element, you should append it to the current 
        //accumulation of characters until the element changes.
        [divCharacters appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if (captureCharacters) {
        captureCharacters = NO;
        [textField setStringValue:divCharacters];
        [divCharacters release];
    }
}

@end

Thanks A lot. I was able to get it hooked up and I spent a lot of time understanding it. Now I can build on this and try more complicated ones.

objective c - Simple and concise desktop Cocoa NSXMLParser example? - ...

objective-c cocoa nsxmlparser sax
Rectangle 27 0

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 http://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

Rather than attempting to read the file as UTF8, have you tried NSASCIIStringEncoding?

NSString *receiptString =
    [[NSString alloc] initWithContentsOfFile:[receiptUrl path] 
                                    encoding:NSASCIIStringEncoding
                                       error:&error];

Also, given that you're unsure of the actual encoding of the file, you can use the following instead of guessing.:

NSStringEncoding *encoding = nil;
NSString *receiptString =
    [NSString stringWithContentsOfFile:[receiptUrl path]
                          usedEncoding:&encoding
                                 error:NULL];

Ascii works but the stirng is just garbage. Nil defaults to ascii. You gave me the idea to try other encodings but they didn't work either. I think there is some special way to read the receipt, but I can't find any examples.

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

ios nsstring app-store ios7
Rectangle 27 0

Rather than attempting to read the file as UTF8, have you tried NSASCIIStringEncoding?

NSString *receiptString =
    [[NSString alloc] initWithContentsOfFile:[receiptUrl path] 
                                    encoding:NSASCIIStringEncoding
                                       error:&error];

Also, given that you're unsure of the actual encoding of the file, you can use the following instead of guessing.:

NSStringEncoding *encoding = nil;
NSString *receiptString =
    [NSString stringWithContentsOfFile:[receiptUrl path]
                          usedEncoding:&encoding
                                 error:NULL];

Ascii works but the stirng is just garbage. Nil defaults to ascii. You gave me the idea to try other encodings but they didn't work either. I think there is some special way to read the receipt, but I can't find any examples.

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

ios nsstring app-store ios7