I am using following code in my iOS app, to favourite a tweet by particular tweet id.
+ (void)favTweetForUser:(NSString )tweet_id withAccount:(ACAccount)twitterAccounts andCompletion:(resultCompletion)completion
{
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/favorites/create.json"];
NSNumber * myNumber =[NSNumber numberWithLongLong:[tweet_id longLongValue]];
NSDictionary *params = #{#"id" : myNumber};
[self postRequestWithAcc:twitterAccounts param:params url:url andCompletion:completion];
}
I am getting following response from twitter
{
errors = (
{
code = 38;
message = "id parameter is missing.";
}
);
}
I am not understanding this error, I am passing "id" parameter, but still getting that error, please suggest me changes to work it
Related
I am currently writing an iOS application utilising a credit card SDK from a company called eWAY.
I am attempting to get it working in a sandbox test environment but I keep receiving a null error.
NSLog output (The "EWAY ERROR" is part of my NSLog message)
2015-10-15 12:25:40.127 EwayTest[1351:37919] EWAY ERROR: <null> ()
Im literally using the example on the webpage: https://www.eway.com.au/developers/sdk/ios
Gateway:
I am using the URL: https://api.sandbox.ewaypayments.com/ gateway as specified.
My code:
- (IBAction)btnPress:(id)sender
{
Transaction *transaction = [[Transaction alloc] init];
Customer *customerObj = [[Customer alloc] init];
customerObj.Reference = #"A12345";
customerObj.Title = #"Mr.";
customerObj.FirstName = #"Nico";
customerObj.LastName = #"Vulture";
customerObj.CompanyName = #"All Web Pty Ltd";
customerObj.JobDescription = #"Developer";
customerObj.Phone = #"09 889 0986";
customerObj.Mobile = #"09 889 0986";
Address *customerAddress = [[Address alloc] init];
customerAddress.Street1 = #"Level 5";
customerAddress.Street2 = #"369 Queen Street";
customerAddress.City = #"Sydney";
customerAddress.State = #"NSW";
customerAddress.PostalCode = #"2010";
customerAddress.Country = #"au";
customerObj.Address = customerAddress;
CardDetails *cardDetails = [[CardDetails alloc] init];
cardDetails.Name = #"Nico Vulture";
cardDetails.Number = #"378282246310005";
cardDetails.ExpiryMonth = #"10";
cardDetails.ExpiryYear = #"19";
cardDetails.CVN = #"836";
customerObj.CardDetails = cardDetails;
transaction.Customer = customerObj;
//payment
Payment *payment = [[Payment alloc] init];
payment.Payment = 100;
payment.InvoiceNumber = #"Inv 21540";
payment.InvoiceDescription = #"Individual Invoice Description";
payment.InvoiceReference = #"513456";
payment.CurrencyCode = #"AUD";
transaction.Payment = payment;
//Make payment
[RapidAPI submitPayment:transaction completed:^(SubmitPaymentResponse *submitPaymentResponse) {
if(submitPaymentResponse.Status == Accepted)
{
NSLog(#"EWAY: Accepted");
}
else if (submitPaymentResponse.Status == Success)
{
// The API Call completed successfully.
NSLog(#"EWAY: Success");
}
else if(submitPaymentResponse.Status == Error)
{
// An error occurred with the API Call.
[RapidAPI userMessage:submitPaymentResponse.Errors Language:#"EN" completed:^(UserMessageResponse *userMessageResponse) {
NSString *msg = [NSString stringWithFormat:#"%# \n %#",userMessageResponse.Errors, userMessageResponse.Messages];
NSLog(#"EWAY ERROR: %#",msg);
}];
}
}];
}
I have however noticed when I change up the gateway (URL) https://api.ewaypayments.com/DirectPayment.json I get an error output of:
EWAY ERROR: S9990
(null)
Which as on the website indicates a "Library does not have Endpoint initialised, or not initialise to a URL" error.
I have been in contact with the company, it must be me doing something wrong here. Has anyone had any experience with this and could provide some insight as to what I'm missing?
Just to update anyone who is or was experiencing this problem. The code works perfectly there was a bug in the SDK that has since been fixed.
I found this sample code to get all local IP addresses, but I don't find an easy solution to get the public IP.
A legacy class from Apple allowed to do that
... but it's legacy ...
It's as simple as this:
NSString *publicIP = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"https://icanhazip.com/"] encoding:NSUTF8StringEncoding error:nil];
publicIP = [publicIP stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; // IP comes with a newline for some reason
I have used ALSystemUtilities in the past. You basically have to make a call externally to find this out.
+ (NSString *)externalIPAddress {
// Check if we have an internet connection then try to get the External IP Address
if (![self connectedViaWiFi] && ![self connectedVia3G]) {
// Not connected to anything, return nil
return nil;
}
// Get the external IP Address based on dynsns.org
NSError *error = nil;
NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
encoding:NSUTF8StringEncoding
error:&error];
if (!error) {
NSUInteger an_Integer;
NSArray *ipItemsArray;
NSString *externalIP;
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:theIpHtml];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:#"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:#">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
theIpHtml = [theIpHtml stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:#"%#>", text]
withString:#" "] ;
ipItemsArray = [theIpHtml componentsSeparatedByString:#" "];
an_Integer = [ipItemsArray indexOfObject:#"Address:"];
externalIP =[ipItemsArray objectAtIndex:++an_Integer];
}
// Check that you get something back
if (externalIP == nil || externalIP.length <= 0) {
// Error, no address found
return nil;
}
// Return External IP
return externalIP;
} else {
// Error, no address found
return nil;
}
}
Source from ALSystemUtilities
Thanks #Tarek for his answer
Here, code in Swift 4 version
func getPublicIPAddress() -> String {
var publicIP = ""
do {
try publicIP = String(contentsOf: URL(string: "https://www.bluewindsolution.com/tools/getpublicip.php")!, encoding: String.Encoding.utf8)
publicIP = publicIP.trimmingCharacters(in: CharacterSet.whitespaces)
}
catch {
print("Error: \(error)")
}
return publicIP
}
NOTE1: To get public IP address, we must have external site to return public IP. The website I use is business company website, so, it will be their until the business gone.
NOTE2: You can made some site by yourself, however, Apple require HTTPS site to be able to use this function.
For those of us using Swift, here's my translation of Andrei's answer with the addition of NSURLSession to run it in the background. To check the network, I use Reachability.swift. Also, remember to add dyndns.org to NSExceptionDomains for NSAppTransportSecurity in your info.plist.
var ipAddress:String?
func getIPAddress() {
if reachability!.isReachable() == false {
return
}
guard let ipServiceURL = NSURL(string: "http://www.dyndns.org/cgi-bin/check_ip.cgi") else {
return
}
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(ipServiceURL, completionHandler: {(data, response, error) -> Void in
if error != nil {
print(error)
return
}
let ipHTML = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String
self.ipAddress = self.scanForIPAddress(ipHTML)
})
task.resume()
}
func scanForIPAddress(var ipHTML:String?) -> String? {
if ipHTML == nil {
return nil
}
var externalIPAddress:String?
var index:Int?
var ipItems:[String]?
var text:NSString?
let scanner = NSScanner(string: ipHTML!)
while scanner.atEnd == false {
scanner.scanUpToString("<", intoString: nil)
scanner.scanUpToString(">", intoString: &text)
ipHTML = ipHTML!.stringByReplacingOccurrencesOfString(String(text!) + ">", withString: " ")
ipItems = ipHTML!.componentsSeparatedByString(" ")
index = ipItems!.indexOf("Address:")
externalIPAddress = ipItems![++index!]
}
if let ip = externalIPAddress {
print("External IP Address: \(ip)")
}
return externalIPAddress
}
I use ipify and with no complaints.
NSURL *url = [NSURL URLWithString:#"https://api.ipify.org/"];
NSString *ipAddress = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"My public IP address is: %#", ipAddress);
In case you want to retrieve IP asynchronously, there is a way to do that using ipify.org and Alamofire in 1 line of code:
Alamofire.request("https://api.ipify.org").responseString { (response) in
print(response.result.value ?? "Unable to get IP")
}
You can call a public IP address lookup services to get this? I have set up http://ipof.in as a service that returns the device IP address as JSON / XML or plain text. You can find them here
For JSON with GeoIP data
http://ipof.in/json
https://ipof.in/json
For XML response
http://ipof.in/xml
https://ipof.in/xml
For plain text IP address
http://ipof.in/txt
https://ipof.in/txt
You have to query an external server to find out the public IP. Either set up your own server (1 line of php code) or use one of the many available ones which return the IP as plain text or json upon http query. Like for example http://myipdoc.com/ip.php .
I find both Andrei and Tarek's answers helpful.
Both are relying a web URL to query the "public IP" of the iOS/OS X device.
However, there is an issue with this approach in some part of the world where URL such as "http://www.dyndns.org/cgi-bin/check_ip.cgi" is censored as in andrei's answer:
NSString *theIpHtml = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.dyndns.org/cgi-bin/check_ip.cgi"]
encoding:NSUTF8StringEncoding
error:&error];
In this case, we will need to use an "uncensored" URL within the region such as http://1212.ip138.com/ic.asp
Note that the web URL could use a different HTML and encoding than what Andrei's answer could parse - in the URL above, some very gentle changes can fix it by using kCFStringEncodingGB_18030_2000 for http://1212.ip138.com/ic.asp
NSURL* externalIPCheckURL = [NSURL URLWithString: #"http://1212.ip138.com/ic.asp"];
encoding:NSUTF8StringEncoding error:nil];
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *theIpHtml = [NSString stringWithContentsOfURL: externalIPCheckURL
encoding: encoding
error: &error];
i'm making a request which sometimes can return a error message example error:"no live games".
How can i check if the valueforkey: error exists?
pseudo
if (error exists) {
//nothing
} else {
//return other value for keys
}
my request
NSDictionary* headers3 = #{#"X-Mashape-Authorization": #"key"};
NSDictionary* parameters3 = #{};
UNIHTTPJsonResponse* response3 = [[UNIRest get:^(UNISimpleRequest* request3) {
[request3 setUrl:#"https://willjw-statsfc-competitions.p.mashape.com/live.json?key=uNzRmnUdCEYKdOoe1e1bBpwtmczNVLUZYbIlOX9O&competition=europa-league&timezone=Europe%2FLondon"];
[request3 setHeaders:headers3];
[request3 setParameters:parameters3];
}] asJson];
NSData* rawBody3 = [response3 rawBody];
results3 = [NSJSONSerialization JSONObjectWithData:rawBody3 options:NSJSONReadingMutableContainers error:nil];
Seems like your API returns "message" instead of "error". Anyway, here's what you do:
if (result3[#"message"]) { // equavalent of [result3 objectForKey:#"message"], which will return nil if there's no "message" key in the dictionary
// your error handler condition
}
else {
// process retrieved data
}
I am trying to create a Application which lists all contacts from the iPhone address book with the following code (coffeescript)
listContacts: ->
options = new ContactFindOptions()
options.filter = '';
options.multiple = true
fields = ["id", "photos", "name", "phoneNumbers"]
navigator.contacts.find(fields, #onSuccess, #onError, options)
onSuccess: (contacts) ->
console.log contacts.length
onError: (error) ->
console.log error
this seems to work nice for a bunch of contacts. but with 3000 the contacts will never return. the funny thing though this works perfectly on the iOsSimulator.
are there any limitations to the number of contacts which can be retrieved?
I had the same problem with 300 contacts, it took around 5 minutes. After I patched it only takes 10 seconds.
Here is my pull request : https://github.com/phonegap/phonegap/pull/19
They have to generate a temp file for each picture and they are using a crazy loop to find a free file path. Something like :
do {
filePath = [NSString stringWithFormat:#"%#/photo_%03d.jpg", docsPath, i++];
} while ([fileMgr fileExistsAtPath:filePath]);
Now I use mktemp and everything is faster.
If you don't need full res pictures, you can also replace :
CFDataRef photoData = ABPersonCopyImageData(self.record);
by :
CFDataRef photoData = ABPersonCopyImageDataWithFormat(self.record, kABPersonImageFormatThumbnail);
I hope that'll help you !
Edit :
IOS'll flush the temp directory each time you start the application:
You are responsible for deleting any temporary files that you created.
The system will clean them up at startup, but that could be a very
long time away.
From: http://cocoadev.com/wiki/NSTemporaryDirectory
If you don't want to slow down the bootstrap of your application, you should use always the same filepath based on the contact id. You'll save cleanup and write time if the file already exists :
- (NSObject*)extractPhotos
{
NSMutableArray* photos = nil;
if (ABPersonHasImageData(self.record)) {
//CFDataRef photoData = ABPersonCopyImageDataWithFormat(self.record, kABPersonImageFormatThumbnail);
CFDataRef photoData = ABPersonCopyImageData(self.record);
NSData* data = (__bridge NSData*)photoData;
// write to temp directory and store URI in photos array
// get the temp directory path
NSString* docsPath = [NSTemporaryDirectory ()stringByStandardizingPath];
NSError* err = nil;
int recordId = ABRecordGetRecordID(self.record);
NSFileManager* fileMgr = [[NSFileManager alloc] init];
NSString* filePath = [NSString stringWithFormat:#"%#/photo_%03d.jpg", docsPath, recordId];
BOOL hasImage = NO;
if ([fileMgr fileExistsAtPath:filePath]) {
hasImage = YES;
} else if ([data writeToFile:filePath options:NSAtomicWrite error:&err]) {
hasImage = YES;
}
if (hasImage) {
photos = [NSMutableArray arrayWithCapacity:1];
NSMutableDictionary* newDict = [NSMutableDictionary dictionaryWithCapacity:2];
[newDict setObject:filePath forKey:kW3ContactFieldValue];
[newDict setObject:#"url" forKey:kW3ContactFieldType];
[newDict setObject:#"false" forKey:kW3ContactFieldPrimary];
[photos addObject:newDict];
}
CFRelease(photoData);
}
return photos;
}
Edit (08/01/2013):
FYI : merged in cordova : http://git-wip-us.apache.org/repos/asf/cordova-ios/commit/c6a1dbe3
First you have to add plugin from terminal command line
$ cordova plugin add org.apache.cordova.contacts
onDeviceReady you can call a method to open contact list
function chooseContact() {
var options = new ContactFindOptions();
options.fields = ["displayName", "name", "emails", "phoneNumbers"];
navigator.contacts.chooseContact(onSuccess, options);
}
function onSuccess(id, contact) {
console.log(JSON.stringify(contact));
}
I am using Facebook Graph API...for fetching the data of news feed of the facebook profile..
and here is the response that i am getting in the console
{
application = {
id = 2309869772;
name = Links;
};
"created_time" = "2011-02-10T09:44:27+0000";
from = {
id = 1845195019;
name = "Paritosh Raval";
};
icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
id = "1845195019_192144087475935";
likes = {
count = 1;
data = (
{
id = 1845195019;
name = "Paritosh Raval";
}
);
};
link = "http://www.facebook.com/AMDAVAD";
name = "once you live in AHMEDABAD u cannot live anywhere else in the world..";
picture = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/203562_115963658443669_4129246_n.jpg";
properties = (
{
name = Page;
text = "21,803 people like this.";
}
);
type = link;
"updated_time" = "2011-02-10T09:44:27+0000";
},
{
application = {
id = 2392950137;
name = Video;
};
"created_time" = "2011-02-02T04:18:22+0000";
description = "must watch and explore :))";
from = {
id = 1845195019;
name = "Paritosh Raval";
};
icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
id = "1845195019_194836027209359";
likes = {
count = 1;
data = (
{
id = 100000701228096;
name = "Bhargav Jani";
}
);
};
link = "http://www.facebook.com/video/video.php?v=152586058110610&comments";
name = "It Happens Only in....";
"object_id" = 152586058110610;
picture = "http://vthumb.ak.fbcdn.net/hvthumb-ak-snc4/50893_152586468110569_152586058110610_18299_1832_t.jpg";
properties = (
{
name = Length;
text = "0:54";
}
);
source = "http://video.ak.fbcdn.net/cfs-ak-ash2/70137/56/152586058110610_53804.mp4?oh=481e53b824f6db8e3195fc9c0d07571d&oe=4DAFC300&__gda__=1303364352_7670272db65e93ec75dcaaed16b6d805";
type = video;
"updated_time" = "2011-02-02T04:18:22+0000";
}
And I want to show every data in the organized structure in the console. Can anyone help me with this?
it's unclear what you exactly asking but I try to answer.
First of all you need to parse this response in the method
- (void)request:(FBRequest *)request didLoad:(id)result of Facebook iOS SDK
result can be a string, a NSArray if you have multiple results and NSDictionary
In you console output we can see NSDictionary with included arrays and dictionaries in it.
I have little tutorial about it but it's on russian only and site is down today :( so i just copy one example from my article.
Let say we want to know what facebook user Likes
- (IBAction)getUserInfo:(id)sender {
[_facebook requestWithGraphPath:#"me/likes" andDelegate:self];
}
if we try this Graph API response in browser or output to console we can see what this request returns. It returns dictionary with one and only key - "data" and corresponded array to this key. This array contents dictionary objects again with keys -
«name»,"category","id","created_time". Dont forget request «user_likes» permission before.
So we have parsing method like that:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"owner"]) {
[self.label setText:#"Photo upload Success"];
} else if ([result objectForKey:#"data"]){
NSArray *likes = [result objectForKey:#"data"];
NSString *text=#"You don't like Steve";
for (NSDictionary* mylike in likes) {
NSString *mylikeName = [mylike objectForKey:#"name"];
if ([mylikeName isEqualToString:#"Steve Jobs"]) {
text=#"You like Steve";
break;
}
}
[self.label setText:text];
}
};
You can parse you result same way and fill your object's variables and then use it to display information in TableView for example. good luck!