How do I loop through Safari tabs? - objective-c

So I have this code that returns the current safari tab's URL
int main(int argc, const char * argv[]) {
NSAppleScript *script= [[NSAppleScript alloc] initWithSource:#"tell application \"Safari\" to return URL of front document as string"];
NSDictionary *scriptError = nil;
NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
if(scriptError) {
NSLog(#"Error: %#",scriptError);
} else {
NSAppleEventDescriptor *unicode = [descriptor coerceToDescriptorType:typeUnicodeText];
NSData *data = [unicode data];
NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];
NSLog(#"Result: %#",result);
}
return 0;
}
How can I implement a loop to switch through all my tabs so it can output all the tab's URLs?

This AppleScript code returns the URLs of all tabs
tell application "Safari" to return URL of tabs of window 1
The result is a list descriptor which must be converted to an NSArray object
int main(int argc, const char * argv[]) {
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:#"tell application \"Safari\" to return URL of tabs of window 1"];
NSDictionary *scriptError = nil;
NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
if(scriptError) {
NSLog(#"Error: %#",scriptError);
} else {
NSAppleEventDescriptor *listDescriptor = [descriptor coerceToDescriptorType:typeAEList];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSInteger i = 1; i <= [listDescriptor numberOfItems]; ++i) {
NSAppleEventDescriptor *URLDescriptor = [listDescriptor descriptorAtIndex:i];
[result addObject: URLDescriptor.stringValue];
}
NSLog(#"Result: %#", [result copy]);
}
return 0;
}

Maybe not what you want but here's a solution with Scripting Bridge:
SafariApplication *SafariApp = [SBApplication applicationWithBundleIdentifier:#"com.apple.Safari"];
for (SafariWindow *window in SafariApp.windows)
{
for (SafariTab *tab in window.tabs)
NSLog(#"%#", tab.URL);
}

Related

How to append array in file

I am trying to write main array in a file and this main array contain sub array . Now whenever I write main array the sub array get overwritten .
Below is my code.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
char fname[10];
printf("Type your first name:\n");
scanf("%s",fname);
NSString *firstname = [[NSString alloc] init];
firstname = [NSString stringWithUTF8String:fname];
char lname[10];
printf("Type your last name:\n");
scanf("%s",lname);
NSString *lastname = [[NSString alloc] init];
lastname = [NSString stringWithUTF8String:lname];
long mnumber = 0;
printf("Enter your register mobile number:\n");
scanf("%ld",&mnumber);
NSNumber *mobilenumber = [NSNumber numberWithLong:mnumber];
long anumber = 0;
printf("Enter your account number:\n");
scanf("%ld",&anumber);
NSNumber *accountnumber = [NSNumber numberWithLong:anumber];
NSURL *docdir = [[NSFileManager defaultManager] URLForDirectory:NSDesktopDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *filepath = [docdir URLByAppendingPathComponent:#"Dexter_apps/filetesting/data.plist"];
NSArray *data = #[firstname,lastname,mobilenumber,accountnumber];
NSMutableArray *mainarray = [[NSMutableArray alloc]init];
mainarray = #[data];
[mainarray writeToURL:filepath atomically:NO];
}
return 0;
}

initWithData:encoding always return null

I am working on an iphone application which need to encode and decode a string,so I code a small script on obj-c to test my code. This is my code which I am using to test:
this code block is not work, the string AwEMT... is a encoded string by dataUsingEncoding:NSUTF8StringEncoding and base64EncodedStringWithOptions:0, just like the working code block but when i decode it is not work and return null
int main (int argc, const char * argv[]) {
NSData *decodedData1 = [[NSData alloc] initWithBase64EncodedString:#"AwEMTqu5FyZFurKQ7givyJEUruVaMg8TBWU8yyMbP2exbOQW9BgDFwxdoD6cuVb4/fR/Jb7J9uryofUAJi1QVDOwl4dzEj+8JzKHS9/zCmryKa3qN5RUCqSrJ//5gTG7b17mfGEqiObZ7a6xJatyfjRJ42+KW1xSH8SSZlnyk5LvtMuSjYRX18NxXCA9E4dmY2po6ehr8cy+UEm9qcjJZ9d6X7z+xubzy/XYv9aPYvxwBe7ZK/kXLEnt2vtafygag/msDuSnLk43wzhAnNnl4YwxFPsx8uZHpsxwBZEvG7wS+YpqhKIZQF9yBqPFkOQXaa55r6p4uChCoVShKGXq4GZtUf6TwF0S2zmlFCpEImonEJa8IIAAhEuU8OTwPCHFga3DhWpXGiWXxtNpCSFlLzXsoPFgYN2OFkf9TH4fIVHAiOm2Xl8SkbXZ/TBTGNevaJNHAEjg+YZmVwnQcCOvcoRdJhx+2ylDdQOswFTsIbkKRARlfHbz4LWqJNW9YTeA21m26dnvCkNWe+tG64j2gse36r2zwya3ULN63AGXtNT8+A==" options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedData1 );
return 0;
}
And this is working code block, I encode the "Developer" string the same way as encoded string: "AwEMT.... But the encoded string from "Developer" can eassily decode by these code.
int main (int argc, const char * argv[]) {
NSString *myString = #"Developer";
NSData *myData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [myData base64EncodedStringWithOptions:0];
NSLog(#"%#", base64String);
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedString);
return 0;
}
Anyone know what I have done wrong on this? please point me out

Check auto-renewable subscription expire date from validate receipt

I am calling receipt validation method in app delegate to check the renewable process. Its working fine in development mode but after releasing from app store its always returning yes, even though user have not purchase the product. Please Suggest what wrong I am doing. In sandbox mode its working fine but after release I found the issue that its always returning true. For validating receipt I am using below code
// Validate the receipt
+(BOOL ) getStoreReceipt:(BOOL)sandbox andTrasaction:(SKPaymentTransaction *)tractaion{
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];
NSLog(#"receiptString Value---->= %#",receiptString);
NSString *encReceipt = [receiptData base64EncodedStringWithOptions:0];
NSLog(#"receiptString Value ======>= %#",encReceipt);
if (receiptString != nil) {
NSString *strSharedSecrect = #"MY_Secrect_Key";
objects = [[NSArray alloc] initWithObjects:receiptString,strSharedSecrect, nil];
keys = [[NSArray alloc] initWithObjects:#"receipt-data",#"password", nil];
dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSString *postData = [self getJsonStringFromDictionary:dictionary];
NSLog(#"postData Value---->= %#",receiptString);
NSString *urlSting = #"https://buy.itunes.apple.com/verifyReceipt";
// if (sandbox) urlSting = #"https://sandbox.itunes.apple.com/verifyReceipt";
dictionary = [self getJsonDictionaryWithPostFromUrlString:urlSting andDataString:postData];
NSLog(#"dictionary Value for receipt---->= %#",dictionary);
if ([dictionary objectForKey:#"status"] != nil) {
if ([[dictionary objectForKey:#"status"] intValue] == 0) {
gotreceipt = true;
}
}
}
}//623065
} #catch (NSException * e) {
gotreceipt = false;
return NO;
NSLog(#"NSException---->= %#",e);
}
if (!gotreceipt) {
NSLog(#"Not gotreceipt---->=");
objects = [[NSArray alloc] initWithObjects:#"-1", nil];
keys = [[NSArray alloc] initWithObjects:#"status", nil];
dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
return NO;
}else{
BOOL isPurchased = [self PurchasedSubscriptionStatues:dictionary];
return isPurchased;
}
return NO;
}
Checking if pending for renewable is there or not...
+(BOOL)PurchasedSubscriptionStatues:(NSDictionary *)transactionReceipt
{
if ([[transactionReceipt allKeys] containsObject:#"pending_renewal_info"]) {
NSArray *arrData = [transactionReceipt objectForKey:#"pending_renewal_info"];
NSDictionary *dicPendinRenew = [arrData objectAtIndex:0];
if ([[dicPendinRenew allKeys] containsObject:#"expiration_intent"] || [[dicPendinRenew objectForKey:#"auto_renew_status"] integerValue]==0) {
return NO;
}else if ([[dicPendinRenew objectForKey:#"auto_renew_status"] integerValue]==1) {
return YES;
}else{
return NO;
}
}else{
return YES;
}
return NO;
}
Convert String To Dictionary
+(NSString *)getJsonStringFromDictionary:(NSDictionary *)dicVal
{
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicVal options:NSJSONWritingPrettyPrinted error:&error];
NSString *postString = #"";
if (! postData) {
NSLog(#"Got an error: %#", error);
return nil;
}
else { postString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
return postString;
}
}
Convert Dictionary to string
+(NSDictionary *) getJsonDictionaryWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
NSString *jsonString = [self getStringWithPostFromUrlString:urlString andDataString:dataString];
NSLog(#"getJsonDictionaryWithPostFromUrlString-->%#", 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;
}
//Request for post method to get the recipt
+ (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];
}
------------------------------------------------------------------------
I think your PurchasedSubscriptionStatues method has an error: if the receipt does not contain pending_renewal_info key, it returns YES. Try creating a new sandbox user and see if the receipt contains this key, if not - then this method should return NO in such case.
Also, you can try using some library that can manage InApp purchases, like RMStore, to ease on the receipt verification.

How to get data to write to a text file?

Here is the method that I'm using for a console output. How can I output to a text file?
#implementation GetMoves
- (id)initWithDevice:(Device *)device{
if(self = [super init]){
_device = device;
}
return self;
}
- (void)Render{
[super ClearConsole];
printf("MOVES INFO\n");
printf("==================================\n");
NSArray* data = [_device GetData:NULL];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
if(data != nil){
for(int i = 0; i < data.count; i++){
DataPoint* current = [data objectAtIndex:i];
NSMutableString* output = [[NSMutableString alloc] init];
[output appendFormat:#"%d",(i+1)];
[output appendString:#" - "];
[output appendString:[dateFormatter stringFromDate:current.RecordedAt]];
[output appendString:#" - "];
[output appendFormat:#"%d",current.StepCount];
printf("%s\n", [output UTF8String]);
}
}
else
printf("No new data found on device.\n");
printf("\n");
printf("==================================\n");
printf("\n");
printf("Press ENTER to continue.");
fgetc(stdin);
}
#end
You can simply write as :
NSString *path = [#"~" stringByExpandingTildeInPath] ;
//change your path here
path=[path stringByAppendingString:#"/Documents/*REPORTS/"];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/TWCodeFile.txt",path];
//create content - four lines of text
NSString *content = #"The content of file, can be more by appending string.";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];

iOS NSMutableData *data = [[NSMutableData alloc] init]; crashes

I m using below mentioned line in a function
NSMutableData *data = [[NSMutableData alloc] init];
And I m calling this function a no of time (e.g. 100 times). So my problem is that initially for about 60 times or more it is working properly but after that it gives me "BAD_EXC_ACCESS"
Function is given below
+ (NSString *) recvToFile:(NSString *)_fileName {
#try {
int _sz = [self recvNumber:4];
uint8_t t[_sz];
NSMutableData *data = [[NSMutableData alloc] init];
NSMutableData *fileData = [[NSMutableData alloc] init];
long _pos = 0;
NSString *_fullPath = _fileName;
while (_sz > _pos) {
long _c = [m_sin read:t maxLength:_sz];
_pos += _c;
data = [NSData dataWithBytes:t length:_c];
if([Misc checkFileExists:_fileName]==nil)
[[NSFileManager defaultManager] createFileAtPath:_fullPath contents:nil attributes:nil];
[fileData appendData:data];
}
[fileData writeToFile:_fullPath atomically:YES];
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:_fullPath error:nil];
long long length = [[attr valueForKey:#"NSFileSize"] intValue];
if (length >= _sz)
return (_fullPath);
}
#catch (NSException * e) {
}
return (nil);
}
And I m calling this function every time i receive a file. I want to save file from bytes
You should not initialize data here:
NSMutableData *data = [[NSMutableData alloc] init];
just initialize the variable to nil;
NSMutableData* data = nil;
Try adding data like this to nsmutabledata
[data appendBytes:t length:_c];