-(void) match:(GKMatch *)match didReceiveData:(NSData *)data fromPlayer:(NSString *)playerID {
NSMutableArray* grid = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:[data bytes]];
_game.gameMap.grid = grid;
[_game updateMap:_game.localPlayer.playerFleet];
_mainGameController = [[MainGameController alloc] initMainGameControllerWithGame:_game andFrame:self.frame.size];
[self addChild:_mainGameController.containers.overallNode];
}
-(BOOL)sendMap {
NSError* error;
NSData* packet = [NSKeyedArchiver archivedDataWithRootObject:_game.gameMap.grid];
[_game.gameCenter.match sendDataToAllPlayers: packet withDataMode:GKMatchSendDataUnreliable error:&error];
if (error != nil) {
NSLog(#"error");
}
return false;
}
This code returns a bad access error on the following line:
NSMutableArray* grid = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:[data bytes]];
unarchiveObjectWithData: expects its argument to be an instance of NSData. That is not what [data bytes] returns. You probably just want data.
Related
iOS app terminates in Xcode simulator in connectionDidFinishLoading on the following line of code.
NSMutableDictionary *dict = [parser objectWithString:[[NSString alloc] initWithData:dataForConnection encoding:NSUTF8StringEncoding] error:nil];
Following the more code of this function
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSMutableData *dataForConnection = [self dataForConnection:(URLConnection*)connection];
NSInteger statusCode=[((URLConnection*)connection).response statusCode];
NSString *tag=((URLConnection*)connection).tagKey;
[self removeReceivedDataHandle:tag];
if (statusCode != 200 && statusCode!=204 && statusCode!=405){
[reportActivityIndicator stopAnimating];
[transactionsActivityIndicator stopAnimating];
[swipeHQCheckout showMessage:PHRASE_ServerCommunicationError];
return;
}
if ([reports count] == 0) {
[self removeReceivedDataHandle];
[transactionsActivityIndicator stopAnimating];
return;
}
SBJsonParser *parser = [[SBJsonParser alloc] init];
[reports removeObject:tag];
if ([tag isEqualToString:API_TransactionReport] ||
[tag isEqualToString:API_FetchTransactions]) {
NSMutableDictionary *dict = [parser objectWithString:[[NSString alloc] initWithData:dataForConnection encoding:NSUTF8StringEncoding] error:nil]; // here issue
NSString *response_code=[dict objectForKey:#"response_code"];
// more code down here
}
What could be the issue, advanced thanks for the suggestions.
It seems your NSMutableData dataForConnection is coming nil and you are initializing a NSMutableDictionary with nil value
To avoid crash :
if (dataForConnection != nil){
NSMutableDictionary *dict = [parser objectWithString:[[NSString alloc] initWithData:dataForConnection encoding:NSUTF8StringEncoding] error:nil];
}else{
NSLog(#"NO Data");
}
You should add the check at the start of the method to follow best practise, like
if (dataForConnection == nil){
NSLog(#"NO Data");
return;
}else{
//Do whatever you want to do
}
Background : I have a custom authentication mechanism on the server end that is not supported by the MPMoviePlayer. So, I decided to have a local loopback HTTP server which will take the initial request of the player and serve the HLS manifest file.
I'm at a position where the player initiates the request to my local HTTP server and after that my local HTTP server fetches manifest file from the servers and writes it back as a http response to the player. But MPMoviePlayer is not playing the video after that.
Can someone help me achieve this?
#import "QumuMediaPlayerProxy.h"
#import "GZIP.h"
#define WELCOME_MSG 0
#define ECHO_MSG 1
#define WARNING_MSG 2
#define READ_TIMEOUT 15.0
#define READ_TIMEOUT_EXTENSION 10.0
#interface QumuMediaPlayerProxy()
#property NSURL *contentURL;
#end
#implementation QumuMediaPlayerProxy
+(NSURL*)getProxyURL{
return [NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.2.11:%d%#", SERVER_PORT, #"/nkm.do"]];
}
- (id)initWithURL:(NSURL*)contentURL
{
if((self = [super init]))
{
socketQueue = dispatch_queue_create("socketQueue", NULL);
listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
isRunning = NO;
self.contentURL = contentURL;
}
return self;
}
- (void)startOnPort:(int)port
{
if(!isRunning)
{
if (port < 0 || port > 65535)
{
port = 0;
}
NSError *error = nil;
if(![listenSocket acceptOnPort:port error:&error])
{
NSLog(#"Error starting QumuMediaPlayerProxy: %#", error.debugDescription);
return;
}
NSLog(#"QumuMediaPlayerProxy started on port %hu", [listenSocket localPort]);
isRunning = YES;
}
}
-(void)stop
{
if(isRunning)
{
// Stop accepting connections
[listenSocket disconnect];
// Stop any client connections
#synchronized(connectedSockets)
{
NSUInteger i;
for (i = 0; i < [connectedSockets count]; i++)
{
// Call disconnect on the socket,
// which will invoke the socketDidDisconnect: method,
// which will remove the socket from the list.
[[connectedSockets objectAtIndex:i] disconnect];
}
}
NSLog(#"Stopped QumuMediaPlayerProxy");
isRunning = false;
}
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
// This method is executed on the socketQueue (not the main thread)
#synchronized(connectedSockets)
{
[connectedSockets addObject:newSocket];
NSLog(#"==Accepted client==");
}
[newSocket readDataWithTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
// This method is executed on the socketQueue (not the main thread)
if (tag == ECHO_MSG)
{
[sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
// This method is executed on the socketQueue (not the main thread)
dispatch_async(dispatch_get_main_queue(), ^{
#autoreleasepool {
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
if (msg)
{
NSLog(#"msg===>%#",msg);
NSLog(#"contentURL===>%#",self.contentURL.absoluteString);
NSString *getStr = [msg componentsSeparatedByString:#"\n"][0];
NSString *requestedURL = [getStr substringWithRange:NSMakeRange(4, getStr.length-9)];
//NSString *host = #"http://127.0.0.1:6910/";
NSString *host = #"http://192.168.2.11:6910/";
NSURL *requestURL = self.contentURL;
if(![requestedURL containsString:#"nkm.do"]){
NSString *actualHost = [self.contentURL.absoluteString stringByReplacingOccurrencesOfString:self.contentURL.lastPathComponent withString:#""];
requestURL = [NSURL URLWithString:[actualHost stringByAppendingString:requestedURL]];
}
NSData *manifestData = [[QumuJSONHelper getInstance] fetchM3U8Playlist:requestURL];
NSString *manifestStr = [[NSString alloc] initWithData:manifestData encoding:NSUTF8StringEncoding];
NSLog(#"manifestStr===>%#",manifestStr);
/* NSArray *manifestArray = [manifestStr componentsSeparatedByString:#"\n"];
NSString *modifiedManifest = #"";
for(int i=0;i<manifestArray.count;i++){
NSString *token = manifestArray[i];
if([token containsString:#"#EXT-X-STREAM-INF"]){
NSLog(#"== Found tag EXT-X-STREAM-INF ==");
modifiedManifest = [modifiedManifest stringByAppendingString:token];
modifiedManifest = [modifiedManifest stringByAppendingString:#"\n"];
token = manifestArray[++i];
// token = [#"https://devimages.apple.com.edgekey.net/streaming/examples/bipbop_16x9/" stringByAppendingString:token];
token = [host stringByAppendingString:token];
NSLog(#"Modified URL===>%#",token);
}
modifiedManifest = [modifiedManifest stringByAppendingString:token];
modifiedManifest = [modifiedManifest stringByAppendingString:#"\n"];
}
modifiedManifest = [modifiedManifest stringByReplacingOccurrencesOfString:#"URI=\"" withString:[NSString stringWithFormat:#"URI=\"%#",host]];
NSLog(#"modifiedManifest===>%#",modifiedManifest);*/
NSString *response = #"HTTP/1.1 200 OK";
response = [response stringByAppendingString:#"\r\nContent-Type: application/vnd.apple.mpegurl;charset=UTF-8"];
response = [response stringByAppendingFormat:#"\r\nContent-Length: %ld", (unsigned long)manifestData.length];
response = [response stringByAppendingString:#"\r\nConnection: keep-alive"];
response = [response stringByAppendingString:#"\r\n\r\n"];
NSLog(#"response header ===>%#",response);
NSData *responseData = [response dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:responseData withTimeout:-1 tag:0];
[sock writeData:manifestData withTimeout:-1 tag:0];
}
else
{
NSLog(#"Error converting received data into UTF-8 String");
}
}
});
// Echo message back to client
[sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}
/**
* This method is called if a read has timed out.
* It allows us to optionally extend the timeout.
* We use this method to issue a warning to the user prior to disconnecting them.
**/
- (NSTimeInterval)socket:(GCDAsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length
{
if (elapsed <= READ_TIMEOUT)
{
NSString *warningMsg = #"Are you still there?\r\n";
NSData *warningData = [warningMsg dataUsingEncoding:NSUTF8StringEncoding];
[sock writeData:warningData withTimeout:-1 tag:WARNING_MSG];
return READ_TIMEOUT_EXTENSION;
}
return 0.0;
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
if (sock != listenSocket)
{
dispatch_async(dispatch_get_main_queue(), ^{
#autoreleasepool {
NSLog(#"Client Disconnected");
}
});
#synchronized(connectedSockets)
{
[connectedSockets removeObject:sock];
}
}
}
-(void)dealloc{
// [self stop];
}
#end
Thanks in advance.
I was writing an additional echo message back to server in
(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
Once I removed it everything started working as expected. Just mentioning this in case some one wants to use the code posted above.
We are following the raywenderlinch tutorial from http://www.raywenderlich.com/23266/in-app-purchases-in-ios-6-tutorial-consumables-and-receipt-validation
But there are some error which I am getting when import verificationController classes in our project. Right now, I am using iOS8.
Error is: Implicit declaration of function 'checkReciptSecurity' is invalid in C99
I have also search for sample code of Verification class on apple developer site ,Their page is not found.
Please give me your view to solve this or provide the link of verification classes which are update to iOS8.
In VerificationController.h put the function prototype like this :
- (void)verifyPurchase:(SKPaymentTransaction *)transaction completionHandler:(VerifyCompletionHandler)completionHandler;
BOOL checkReceiptSecurity(NSString *purchase_info_string, NSString *signature_string, CFDateRef purchaseDate);
The reason of doing this is the line number calling the function checkReceiptSecurity is before the declaration of function.
You have to modified the VerificationController.m file code.
I have put the modified code here.
#import "VerificationController.h"
#import "NSData+Base64.h"
static VerificationController *singleton;
#implementation VerificationController {
NSMutableDictionary * _completionHandlers;
}
+ (VerificationController *)sharedInstance
{
if (singleton == nil)
{
singleton = [[VerificationController alloc] init];
}
return singleton;
}
- (id)init
{
self = [super init];
if (self != nil)
{
transactionsReceiptStorageDictionary = [[NSMutableDictionary alloc] init];
_completionHandlers = [[NSMutableDictionary alloc] init];
}
return self;
}
- (NSDictionary *)dictionaryFromPlistData:(NSData *)data
{
NSError *error;
NSDictionary *dictionaryParsed = [NSPropertyListSerialization propertyListWithData:data
options:NSPropertyListImmutable
format:nil
error:&error];
if (!dictionaryParsed)
{
if (error)
{
NSLog(#"Error parsing plist");
}
return nil;
}
return dictionaryParsed;
}
- (NSDictionary *)dictionaryFromJSONData:(NSData *)data
{
NSError *error;
NSDictionary *dictionaryParsed = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (!dictionaryParsed)
{
if (error)
{
NSLog(#"Error parsing dictionary");
}
return nil;
}
return dictionaryParsed;
}
#pragma mark Receipt Verification
// This method should be called once a transaction gets to the SKPaymentTransactionStatePurchased or SKPaymentTransactionStateRestored state
// Call it with the SKPaymentTransaction.transactionReceipt
- (void)verifyPurchase:(SKPaymentTransaction *)transaction completionHandler:(VerifyCompletionHandler)completionHandler
{
BOOL isOk = [self isTransactionAndItsReceiptValid:transaction];
if (!isOk)
{
// There was something wrong with the transaction we got back, so no need to call verifyReceipt.
NSLog(#"Invalid transacion");
completionHandler(FALSE);
return;
}
// The transaction looks ok, so start the verify process.
// Encode the receiptData for the itms receipt verification POST request.
NSString *jsonObjectString = [self encodeBase64:(uint8_t *)transaction.transactionReceipt.bytes
length:transaction.transactionReceipt.length];
// Create the POST request payload.
NSString *payload = [NSString stringWithFormat:#"{\"receipt-data\" : \"%#\", \"password\" : \"%#\"}",
jsonObjectString, ITC_CONTENT_PROVIDER_SHARED_SECRET];
NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
#warning Check for the correct itms verify receipt URL
// Use ITMS_SANDBOX_VERIFY_RECEIPT_URL while testing against the sandbox.
NSString *serverURL = ITMS_SANDBOX_VERIFY_RECEIPT_URL; //ITMS_PROD_VERIFY_RECEIPT_URL;
// Create the POST request to the server.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:payloadData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_completionHandlers[[NSValue valueWithNonretainedObject:conn]] = completionHandler;
[conn start];
// The transation receipt has not been validated yet. That is done from the NSURLConnection callback.
}
// Check the validity of the receipt. If it checks out then also ensure the transaction is something
// we haven't seen before and then decode and save the purchaseInfo from the receipt for later receipt validation.
- (BOOL)isTransactionAndItsReceiptValid:(SKPaymentTransaction *)transaction
{
if (!(transaction && transaction.transactionReceipt && [transaction.transactionReceipt length] > 0))
{
// Transaction is not valid.
return NO;
}
// Pull the purchase-info out of the transaction receipt, decode it, and save it for later so
// it can be cross checked with the verifyReceipt.
NSDictionary *receiptDict = [self dictionaryFromPlistData:transaction.transactionReceipt];
NSString *transactionPurchaseInfo = [receiptDict objectForKey:#"purchase-info"];
NSString *decodedPurchaseInfo = [self decodeBase64:transactionPurchaseInfo length:nil];
NSDictionary *purchaseInfoDict = [self dictionaryFromPlistData:[decodedPurchaseInfo dataUsingEncoding:NSUTF8StringEncoding]];
NSString *transactionId = [purchaseInfoDict objectForKey:#"transaction-id"];
NSString *purchaseDateString = [purchaseInfoDict objectForKey:#"purchase-date"];
NSString *signature = [receiptDict objectForKey:#"signature"];
// Convert the string into a date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss z"];
NSDate *purchaseDate = [dateFormat dateFromString:[purchaseDateString stringByReplacingOccurrencesOfString:#"Etc/" withString:#""]];
if (![self isTransactionIdUnique:transactionId])
{
// We've seen this transaction before.
// Had [transactionsReceiptStorageDictionary objectForKey:transactionId]
// Got purchaseInfoDict
return NO;
}
// Check the authenticity of the receipt response/signature etc.
BOOL result = checkReceiptSecurity(transactionPurchaseInfo, signature,
(__bridge CFDateRef)(purchaseDate));
if (!result)
{
return NO;
}
// Ensure the transaction itself is legit
if (![self doTransactionDetailsMatchPurchaseInfo:transaction withPurchaseInfo:purchaseInfoDict])
{
return NO;
}
// Make a note of the fact that we've seen the transaction id already
[self saveTransactionId:transactionId];
// Save the transaction receipt's purchaseInfo in the transactionsReceiptStorageDictionary.
[transactionsReceiptStorageDictionary setObject:purchaseInfoDict forKey:transactionId];
return YES;
}
// Make sure the transaction details actually match the purchase info
- (BOOL)doTransactionDetailsMatchPurchaseInfo:(SKPaymentTransaction *)transaction withPurchaseInfo:(NSDictionary *)purchaseInfoDict
{
if (!transaction || !purchaseInfoDict)
{
return NO;
}
int failCount = 0;
if (![transaction.payment.productIdentifier isEqualToString:[purchaseInfoDict objectForKey:#"product-id"]])
{
failCount++;
}
if (transaction.payment.quantity != [[purchaseInfoDict objectForKey:#"quantity"] intValue])
{
failCount++;
}
if (![transaction.transactionIdentifier isEqualToString:[purchaseInfoDict objectForKey:#"transaction-id"]])
{
failCount++;
}
// Optionally check the bid and bvrs match this app's current bundle ID and bundle version.
// Optionally check the requestData.
// Optionally check the dates.
if (failCount != 0)
{
return NO;
}
// The transaction and its signed content seem ok.
return YES;
}
- (BOOL)isTransactionIdUnique:(NSString *)transactionId
{
NSString *transactionDictionary = KNOWN_TRANSACTIONS_KEY;
// Save the transactionId to the standardUserDefaults so we can check against that later
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];
if (![defaults objectForKey:transactionDictionary])
{
[defaults setObject:[[NSMutableDictionary alloc] init] forKey:transactionDictionary];
[defaults synchronize];
}
if (![[defaults objectForKey:transactionDictionary] objectForKey:transactionId])
{
return YES;
}
// The transaction already exists in the defaults.
return NO;
}
- (void)saveTransactionId:(NSString *)transactionId
{
// Save the transactionId to the standardUserDefaults so we can check against that later
// If dictionary exists already then retrieve it and add new transactionID
// Regardless save transactionID to dictionary which gets saved to NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *transactionDictionary = KNOWN_TRANSACTIONS_KEY;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithDictionary:
[defaults objectForKey:transactionDictionary]];
if (!dictionary)
{
dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:1], transactionId, nil];
} else {
[dictionary setObject:[NSNumber numberWithInt:1] forKey:transactionId];
}
[defaults setObject:dictionary forKey:transactionDictionary];
[defaults synchronize];
}
- (BOOL)doesTransactionInfoMatchReceipt:(NSString*) receiptString
{
// Convert the responseString into a dictionary and pull out the receipt data.
NSDictionary *verifiedReceiptDictionary = [self dictionaryFromJSONData:[receiptString dataUsingEncoding:NSUTF8StringEncoding]];
// Check the status of the verifyReceipt call
id status = [verifiedReceiptDictionary objectForKey:#"status"];
if (!status)
{
return NO;
}
int verifyReceiptStatus = [status integerValue];
// 21006 = This receipt is valid but the subscription has expired.
if (0 != verifyReceiptStatus && 21006 != verifyReceiptStatus)
{
return NO;
}
// The receipt is valid, so checked the receipt specifics now.
NSDictionary *verifiedReceiptReceiptDictionary = [verifiedReceiptDictionary objectForKey:#"receipt"];
NSString *verifiedReceiptUniqueIdentifier = [verifiedReceiptReceiptDictionary objectForKey:#"unique_identifier"];
NSString *transactionIdFromVerifiedReceipt = [verifiedReceiptReceiptDictionary objectForKey:#"transaction_id"];
// Get the transaction's receipt data from the transactionsReceiptStorageDictionary
NSDictionary *purchaseInfoFromTransaction = [transactionsReceiptStorageDictionary objectForKey:transactionIdFromVerifiedReceipt];
if (!purchaseInfoFromTransaction)
{
// We didn't find a receipt for this transaction.
return NO;
}
// NOTE: Instead of counting errors you could just return early.
int failCount = 0;
// Verify all the receipt specifics to ensure everything matches up as expected
if (![[verifiedReceiptReceiptDictionary objectForKey:#"bid"]
isEqualToString:[purchaseInfoFromTransaction objectForKey:#"bid"]])
{
failCount++;
}
if (![[verifiedReceiptReceiptDictionary objectForKey:#"product_id"]
isEqualToString:[purchaseInfoFromTransaction objectForKey:#"product-id"]])
{
failCount++;
}
if (![[verifiedReceiptReceiptDictionary objectForKey:#"quantity"]
isEqualToString:[purchaseInfoFromTransaction objectForKey:#"quantity"]])
{
failCount++;
}
if (![[verifiedReceiptReceiptDictionary objectForKey:#"item_id"]
isEqualToString:[purchaseInfoFromTransaction objectForKey:#"item-id"]])
{
failCount++;
}
if ([[UIDevice currentDevice] respondsToSelector:NSSelectorFromString(#"identifierForVendor")]) // iOS 6?
{
#if IS_IOS6_AWARE
// iOS 6 (or later)
NSString *localIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *purchaseInfoUniqueVendorId = [purchaseInfoFromTransaction objectForKey:#"unique-vendor-identifier"];
NSString *verifiedReceiptVendorIdentifier = [verifiedReceiptReceiptDictionary objectForKey:#"unique_vendor_identifier"];
if(verifiedReceiptVendorIdentifier)
{
if (![purchaseInfoUniqueVendorId isEqualToString:verifiedReceiptVendorIdentifier]
|| ![purchaseInfoUniqueVendorId isEqualToString:localIdentifier])
{
// Comment this line out to test in the Simulator.
failCount++;
}
}
#endif
} else {
// Pre iOS 6
// NSString *localIdentifier = [UIDevice currentDevice].uniqueIdentifier;
// NSString *purchaseInfoUniqueId = [purchaseInfoFromTransaction objectForKey:#"unique-identifier"];
// if (![purchaseInfoUniqueId isEqualToString:verifiedReceiptUniqueIdentifier]
// || ![purchaseInfoUniqueId isEqualToString:localIdentifier])
// {
// // Comment this line out to test in the Simulator.
// failCount++;
// }
}
// Do addition time checks for the transaction and receipt.
if(failCount != 0)
{
return NO;
}
return YES;
}
#pragma mark NSURLConnectionDelegate (for the verifyReceipt connection)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failure: %#", error);
VerifyCompletionHandler completionHandler = _completionHandlers[[NSValue valueWithNonretainedObject:connection]];
[_completionHandlers removeObjectForKey:[NSValue valueWithNonretainedObject:connection]];
completionHandler(FALSE);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
BOOL isOk = [self doesTransactionInfoMatchReceipt:responseString];
VerifyCompletionHandler completionHandler = _completionHandlers[[NSValue valueWithNonretainedObject:connection]];
[_completionHandlers removeObjectForKey:[NSValue valueWithNonretainedObject:connection]];
if (isOk)
{
//Validation suceeded. Unlock content here.
NSLog(#"Validation successful");
completionHandler(TRUE);
} else {
NSLog(#"Validation failed");
completionHandler(FALSE);
}
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
NSError *error = nil;
BOOL didUseCredential = NO;
BOOL isTrusted = [self validateTrust:trust error:&error];
if (isTrusted)
{
NSURLCredential *trust_credential = [NSURLCredential credentialForTrust:trust];
if (trust_credential)
{
[[challenge sender] useCredential:trust_credential forAuthenticationChallenge:challenge];
didUseCredential = YES;
}
}
if (!didUseCredential)
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
}
}
// NOTE: These are needed for 4.x (as willSendRequestForAuthenticationChallenge: is not supported)
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
NSError *error = nil;
BOOL didUseCredential = NO;
BOOL isTrusted = [self validateTrust:trust error:&error];
if (isTrusted)
{
NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
if (credential)
{
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
didUseCredential = YES;
}
}
if (! didUseCredential) {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
}
}
#pragma mark
#pragma mark NSURLConnection - Trust validation
- (BOOL)validateTrust:(SecTrustRef)trust error:(NSError **)error
{
// Include some Security framework SPIs
extern CFStringRef kSecTrustInfoExtendedValidationKey;
extern CFDictionaryRef SecTrustCopyInfo(SecTrustRef trust);
BOOL trusted = NO;
SecTrustResultType trust_result;
if ((noErr == SecTrustEvaluate(trust, &trust_result)) && (trust_result == kSecTrustResultUnspecified))
{
NSDictionary *trust_info = (__bridge_transfer NSDictionary *)SecTrustCopyInfo(trust);
id hasEV = [trust_info objectForKey:(__bridge NSString *)kSecTrustInfoExtendedValidationKey];
trusted = [hasEV isKindOfClass:[NSValue class]] && [hasEV boolValue];
}
if (trust)
{
if (!trusted && error)
{
*error = [NSError errorWithDomain:#"kSecTrustError" code:(NSInteger)trust_result userInfo:nil];
}
return trusted;
}
return NO;
}
#pragma mark
#pragma mark Base 64 encoding
- (NSString *)encodeBase64:(const uint8_t *)input length:(NSInteger)length
{
NSData * data = [NSData dataWithBytes:input length:length];
return [data base64EncodedString];
}
- (NSString *)decodeBase64:(NSString *)input length:(NSInteger *)length
{
NSData * data = [NSData dataFromBase64String:input];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
char* base64_encode(const void* buf, size_t size) {
size_t outputLength;
return NewBase64Encode(buf, size, NO, &outputLength);
}
void * base64_decode(const char* s, size_t * data_len)
{
return NewBase64Decode(s, strlen(s), data_len);
}
#end
#pragma mark
#pragma mark Check Receipt signature
#include <CommonCrypto/CommonDigest.h>
#include <Security/Security.h>
#include <AssertMacros.h>
unsigned int iTS_intermediate_der_len = 1039;
unsigned char iTS_intermediate_der[] = {
put the hexacode here
};
BOOL checkReceiptSecurity(NSString *purchase_info_string, NSString *signature_string, CFDateRef purchaseDate)
{
BOOL valid = NO;
SecCertificateRef leaf = NULL, intermediate = NULL;
SecTrustRef trust = NULL;
SecPolicyRef policy = SecPolicyCreateBasicX509();
NSData *certificate_data;
NSArray *anchors;
/*
Parse inputs:
purchase_info_string and signature_string are base64 encoded JSON blobs that need to
be decoded.
*/
require([purchase_info_string canBeConvertedToEncoding:NSASCIIStringEncoding] &&
[signature_string canBeConvertedToEncoding:NSASCIIStringEncoding], outLabel);
size_t purchase_info_length;
uint8_t *purchase_info_bytes = base64_decode([purchase_info_string cStringUsingEncoding:NSASCIIStringEncoding],
&purchase_info_length);
size_t signature_length;
uint8_t *signature_bytes = base64_decode([signature_string cStringUsingEncoding:NSASCIIStringEncoding],
&signature_length);
require(purchase_info_bytes && signature_bytes, outLabel);
/*
Binary format looks as follows:
RECEIPTVERSION | SIGNATURE | CERTIFICATE SIZE | CERTIFICATE
1 byte 128 4 bytes
big endian
Extract version, signature and certificate(s).
Check receipt version == 2.
Sanity check that signature is 128 bytes.
Sanity check certificate size <= remaining payload data.
*/
#pragma pack(push, 1)
struct signature_blob {
uint8_t version;
uint8_t signature[128];
uint32_t cert_len;
uint8_t certificate[];
} *signature_blob_ptr = (struct signature_blob *)signature_bytes;
#pragma pack(pop)
uint32_t certificate_len;
/*
Make sure the signature blob is long enough to safely extract the version and
cert_len fields, then perform a sanity check on the fields.
*/
require(signature_length > offsetof(struct signature_blob, certificate), outLabel);
require(signature_blob_ptr->version == 2, outLabel);
certificate_len = ntohl(signature_blob_ptr->cert_len);
require(signature_length - offsetof(struct signature_blob, certificate) >= certificate_len, outLabel);
/*
Validate certificate chains back to valid receipt signer; policy approximation for now
set intermediate as a trust anchor; current intermediate lapses in 2016.
*/
certificate_data = [NSData dataWithBytes:signature_blob_ptr->certificate length:certificate_len];
require(leaf = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificate_data), outLabel);
certificate_data = [NSData dataWithBytes:iTS_intermediate_der length:iTS_intermediate_der_len];
require(intermediate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificate_data), outLabel);
anchors = [NSArray arrayWithObject:(__bridge id)intermediate];
require(anchors, outLabel);
require_noerr(SecTrustCreateWithCertificates(leaf, policy, &trust), outLabel);
require_noerr(SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef) anchors), outLabel);
if (purchaseDate)
{
require_noerr(SecTrustSetVerifyDate(trust, purchaseDate), outLabel);
}
SecTrustResultType trust_result;
require_noerr(SecTrustEvaluate(trust, &trust_result), outLabel);
require(trust_result == kSecTrustResultUnspecified, outLabel);
require(2 == SecTrustGetCertificateCount(trust), outLabel);
/*
Chain is valid, use leaf key to verify signature on receipt by
calculating SHA1(version|purchaseInfo)
*/
CC_SHA1_CTX sha1_ctx;
uint8_t to_be_verified_data[CC_SHA1_DIGEST_LENGTH];
CC_SHA1_Init(&sha1_ctx);
CC_SHA1_Update(&sha1_ctx, &signature_blob_ptr->version, sizeof(signature_blob_ptr->version));
CC_SHA1_Update(&sha1_ctx, purchase_info_bytes, purchase_info_length);
CC_SHA1_Final(to_be_verified_data, &sha1_ctx);
SecKeyRef receipt_signing_key = SecTrustCopyPublicKey(trust);
require(receipt_signing_key, outLabel);
require_noerr(SecKeyRawVerify(receipt_signing_key, kSecPaddingPKCS1SHA1,
to_be_verified_data, sizeof(to_be_verified_data),
signature_blob_ptr->signature, sizeof(signature_blob_ptr->signature)),
outLabel);
/*
Optional: Verify that the receipt certificate has the 1.2.840.113635.100.6.5.1 Null OID
The signature is a 1024-bit RSA signature.
*/
valid = YES;
outLabel:
if (leaf) CFRelease(leaf);
if (intermediate) CFRelease(intermediate);
if (trust) CFRelease(trust);
if (policy) CFRelease(policy);
return valid;
}
I have a nsdictionary from a json which responses that:
({
email = "something#gmail.com";
name = "User1";
},
{
email = "something2#gmail.com";
name = "user2";
})
This is my code in de .m file:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
int errorCode = httpResponse.statusCode;
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString];
NSLog(#"response is %d, %#", errorCode, fileMIMEType);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//NSLog(#"data is %#", data);
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"string is %#", myString);
NSError *e = nil;
usersDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSLog(#"dictionary is %#", usersDictionary);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// inform the user
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NombreUsuario = [[NSMutableArray alloc] initWithCapacity:[usersDictionary count]];
}
I use this to return the numbers of rows in section:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [usersDictionary count];
}
But I don't realize how to put the pair of data email,name into a tableview in which each cell have to show the main label for the name, and the subtitle for the email.
Thanks in advance.
I will answer my own question for future reference for who may need it.
First I had to store the json response in an NSMutableArray instead of an dictionary.
As I have an array of dictionaries I have two levels of information, I was trying to decompose it into new objects, but it wasn't the proper approach, so to access the second level I have to navigate to it:
cell.textLabel.text = [[NombreUsuario objectAtIndex:indexPath.row]objectForKey:#"name"];
With this [NombreUsuario objectAtIndex:indexPath.row] I access the first level of information, and then with objectForKey:#"name" I get all the values that match the key "name".
For the detail label text is the same:
cell.detailTextLabel.text = [[NombreUsuario objectAtIndex:indexPath.row]objectForKey:#"email"];
Thanks everybody for your help.
I won't write your code for you, but you need to look at how to implement a UITableViewDataSource. In particular, what you are looking to do will be within the - tableView:cellForRowAtIndexPath: method. There are thousands of good examples on the Internet for you.
I have a simple JSON array that is returned from a zip code passed to a third party service.
http://api.geonames.org/findNearbyPostalCodes?postalcode=94115&country=US&radius=5&username=frequentz
I get an unknown error when trying to deserialize the results and I'm not sure what is going wrong.
Here is my connectionDidFinishLoading method, which fires as anticiapated but always fails...and I get the error in the last else if. Ideas?
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading...");
self.zipCodes = [NSMutableArray array];
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject != nil && error == nil) {
NSLog(#"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(#"Deserialized JSON Dictionary = %#", deserializedDictionary);
for (NSDictionary *item in jsonObject) {
NSString *city = [item objectForKey:#"adminName2"];
NSString *stateAbbreviation = [item objectForKey:#"adminCode1"];
NSString *postalCode = [item objectForKey:#"postalCode"];
NSString *distance = [item objectForKey:#"distance"];
NSString *country = [item objectForKey:#"country"];
NSString *stateName = [item objectForKey:#"stateName"];
ZipCodes *zipCode = [[ZipCodes alloc] initWithName:city stateAbbrev:stateAbbreviation postalCode:postalCode distanceFromGPSZip:distance country:country stateFullName:stateName];
[self.zipCodes addObject:zipCode];
}
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(#"Deserialized JSON Array = %#", deserializedArray);
}
else {
/* Some other object was returned. We don't know how to deal
with this situation as the deserializer returns only dictionaries or arrays */
}
}
else if (error != nil){
NSLog(#"An error happened while deserializing the JSON data.");
}
}
I think you're using the wrong service --it should be ...findNearbyPostalCodesJSON.... To use the JSON service as far as I can tell from their website. This is their example URL:
http://api.geonames.org/findNearbyPostalCodesJSON?postalcode=8775&country=CH&radius=10&username=demo