Alternatives to NSHost in iPhone app - iphone

I'm currently using this code
NSHost *host = [NSHost hostWithAddress:hostname];
if (host == nil) {
host = [NSHost hostWithName:hostname];
if (host == nil) {
[self setMessage:#"Invalid IP address or hostname:"];
return;
}
}
to retrive my IP Address for a networking app I'm working on, however I'm aware that NSHost is a private API that will be rejected. Can anyone help me with working this code to produce the same results without using NSHost? I'm not really sure where to start.
EDIT:
Following suggestions that seem damn near perfect below I've added this code into my app in the place of the code above
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = #"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
if (result == TRUE) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result == TRUE) {
NSLog(#"Resolved");
} else {
NSLog(#"Not resolved");
}
I've removed the 4th line (as I have this information from elsewhere already) but I get errors being based around CFHostRef being undeclared. How would I resolve that? It seems to be my only big hurdle, as other errors are only based upon the lack of being able to see hostRef after that.
EDIT: Scratch that I also get kCFHostAddresses undeclared.

You can use CFHost to achieve the same. On the top of the CFHost Reference is a cookbook recipe for making the lookup.
The following code does very, very basic synchronous resolution (as yours above would with NSHost). Note that you don't want to do this since it can render your app unresponsive because it doesn't return until it's resolved or the timeout hits.
Use asynchronous lookup instead (CFHostSetClient and CFHostScheduleWithRunLoop as described in the CFHost documentation above). Also, depending on what you're planning to do, you may want to look into using the reachability APIs. Check out the WWDC sessions on networking available on the iPhone developer website.
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = #"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
if (result == TRUE) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result == TRUE) {
NSLog(#"Resolved");
} else {
NSLog(#"Not resolved");
}
// Don't forget to release hostRef when you're done with it

Look at this: http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone

http://developer.apple.com/iphone/library/qa/qa2009/qa1652.html
Got a great little answer through the Developer Support system, this worked perfectly.

Related

Flutter Plugin for automatic wifi connection without prompting something from the user

The specific use case is for a wearable application (Wear OS) that I want to automatically connect to a wifi network that is specified in a config file for easy cross-site deployments without even telling that it is being done. I have tried wifi_iot and plugin_wifi_connect with some odd results. Both seemed to connect to the correct ssid, but they gave some sort of weird prompt that said something about connecting to the device and seemed to actually mess up the connection afterward.
wifi_iot implementation:
check for wifi setting
WiFiForIoTPlugin.isEnabled().then((val) {
_isEnabled = val;
});
print('isEnabled: $_isEnabled');
//check if connected to wifi
WiFiForIoTPlugin.isConnected().then((val) {
_isConnected = val;
});
print('isConnected: $_isConnected');
//enable and connect if not
if (!_isEnabled) {
//enable wifi
WiFiForIoTPlugin.setWiFiAPEnabled(true);
WiFiForIoTPlugin.setEnabled(true);
}
if (!_isConnected) {
//connect to wifi
WiFiForIoTPlugin.connect(_ssid,
password: _psk, security: NetworkSecurity.WPA);
}
plugin_wifi_connect implementation:
var _connectedTo = await PluginWifiConnect.ssid;
print("Comparing $_connectedTo to $_ssid"); //#_connectedTo returns <unidentified_ssid>#
if (_connectedTo.toString() != _ssid) { //#this always fails
try {
await PluginWifiConnect.connectToSecureNetwork(_ssid, _psk,
saveNetwork: true);
print("Connected to $_ssid");
} catch (e) {
print("Couldn't connect to $_ssid");
}
} else {
print("Already connected to $_ssid");
}
Does anyone have any experience with this? Possibly that I am not using the correct permissions for this or if I need to make something if this is even possible anymore. There seemed to be some changes for API above 29 that changed certain things about it. The plugin_wifi_connect did not have much documentation and seems like it might be based on an older package that wasn't null safe that was not really up to date with the same documentation.

Get host server name through email address in mail core2 framework for iOS

I want to know the default host name through the name of the email address....
I found a method in a class "MCONetService.h"....
hostnameWithEmail:
the reference link..
http://libmailcore.com/mailcore2/api/Classes/MCONetService.html
...but my problem is that i am unable to find the proper way to use this method because it is an instance method which requires the "MCONetService" class object to call that method,and i am getting null because it seems this object need some value before the use...
my code ...
MCONetService *netService=[[MCONetService alloc]init];
[netService hostnameWithEmail:#"email#gmail.com"];
This is not a good way of coding but did't found any other way to try this method...
Any help will be appreciable....
Here's how to do it:
First, make sure that you include providers.json in the resources of your app.
Here's how to get the IMAP server related to a given email address.
NSString * email = #"email#gmail.com";
MCOMailProvider * provider = [[MCOMailProvidersManager sharedManager]
providerForEmail:email];
NSString * hostname = nil;
if ([[provider imapServices] count] > 0) {
MCONetService * service = [[provider imapServices] objectAtIndex:0];
hostname = [service hostnameWithEmail:email];
}
if (hostname == nil) {
NSLog(#"no IMAP server found");
}
else {
NSLog(#"IMAP server: %#", hostname);
}

changing ABRecordRef property

I have the following cpde:
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, ABRecordGetRecordID(self.recordRef_));
CFErrorRef error = NULL;
if ([self.nameTextField_.text isNotNull]){
NSArray *nameStringArray = [self.nameTextField_.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)([nameStringArray objectAtIndex:0]), NULL);
if ([nameStringArray count] > 1){
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)([nameStringArray lastObject]), &error);
}
}
However, after this code it gives me this error:
Error Domain=ABAddressBookErrorDomain Code=0 "The operation couldn’t be completed. (ABAddressBookErrorDomain error 0.)"
Any idea why this is?
The error message seems to be pretty useless, but as the rest of your code looks to be valid, my guess is that your application hasn't been authorized by the user to access the Address Book database. Use code like the following to check your authorization status before attempting to access the Adress Book:
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// We're good to go
} else {
// Hasn't been authorized by the user
// You can check the exact authorization status for more information on the
// exact reason why you can't access the Address Book (e.g. denied, restricted, etc.)
}
This happens when the Contact backend that you are using doesn't handle the field you are trying to add to the contact. In your case, I suspect your backend doesn't handle write operations at all.. which is quite the surprise.
See Apple documentation on the subject:
enum {
kABOperationNotPermittedByStoreError = 0,
kABOperationNotPermittedByUserError
};
kABOperationNotPermittedByStoreError
The operation is not allowed by the Address Book database, because the contact’s source does not support it.
Available in iOS 2.0 and later.
kABOperationNotPermittedByUserError
The operation is not allowed because the user denied access to the Address Book database.
Available in iOS 6.0 and later.

How do I use code generated from WSDL2OBJC

hi everyone i am new to iphone development and started with some sample application.
In sample application i am using webservices..i went through this tutorial http://code.google.com/p/wsdl2objc/wiki/UsageInstructions and understood about wsdl2objc..
but this tutorial is too short so can anyone suggest similar like tutorial or examples so tat is still more clear...
thank u
All depends on your web service class name etc as wsdl2objc makes up alot of your NSObjects and methods based upon this, however,
suggesting that you are using soap 1.2 bindings and your web service was called 'SimpleService', the following would call a web method named 'MobileTestService and return back the integer value from the xml generated.
-(NSString *)returnThatStringFromWebServiceResult {
SimpleServiceSoap12Binding * binding = [SimpleService SimpleServiceSoap12Binding];
binding.logXMLInOut = YES; // shows all in the console log.
SimpleService_concat * testParams = [[SimpleService_concat new]autorelease];
testParams.s1 = someTextField.text; // parameters all become properties of this testParams object
testParams.s2 = anotherTextField.text;
SimpleServiceSoap12BindingResponse * response= [binding SimpleService_concatUsingParameters:testParams];
[response self]; // removes compile error
NSArray * responseBodyParts = response.bodyParts;
NSError * responseError = response.error;
if (responseError!=NULL) {
return #""; // if error from ws use [responeError code]; for http err code
}
for (id bodyPart in responseBodyParts)
{
if ([bodyPart isKindOfClass:[SimpleService_concat_Response class]])
{
SimpleService_concatResponse* body = (SimpleService_concatResponse*) bodyPart;
return body.SimpleService_concatResult; // if you are returning a string from your WS then this value will be a string,
}
}
}

iphone programmatically read proxy settings

I'm looking at adding proxy support to my iphone svn client. When you set up a system wide vpn in the iphone settings you can add a global proxy. Is it possible for external apps to read this information through the api?
Apple has created a sample application for this purpose, called CFProxySupportTool.
CFProxySupportTool shows how to use the CFProxySupport APIs to determine whether a network connection should pass through a proxy; this is useful if you're not using Apple's high-level networking APIs (like CFNetwork and the Foundation URL loading system) but still want to interpret the system-supplied proxy settings.
It's currently available at
https://developer.apple.com/library/mac/#samplecode/CFProxySupportTool/Introduction/Intro.html
The code isn't exactly terse (more than 1000 lines), and is written in plain C. You can also look at the source code of ASIHTTPRequest's startRequest function, which seems to be based on CFProxySupportTool.
Here's a start:
systemProxySettings = [(NSDictionary *) CFNetworkCopySystemProxySettings() autorelease];
proxies = [(NSArray *) CFNetworkCopyProxiesForURL((CFURLRef) URL, (CFDictionaryRef) systemProxySettings) autorelease];
if (!proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
if (nil != (pacScriptURL = [firstProxySettings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]))
{
CFErrorRef cfErrorRef = NULL;
NSError *nsError = nil;
NSString *script;
script = [NSString stringWithContentsOfURL:pacScriptURL
usedEncoding:NULL
error:&nsError];
if (nsError)
return;
proxies = [(NSArray *) CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef) script, (CFURLRef) URL, &cfErrorRef) autorelease];
if (cfErrorRef || !proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
}
/* Now use `firstProxySettings' */
A Swift 4 version (special thanks to mortehu for providing the initial example).
//Shown this way for clarity, you may not want to waste cycles in your production code
if let url = URL(string: "https://someurloutthere.com") {
let systemProxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() ?? [:] as CFDictionary
let proxiesForTargetUrl = CFNetworkCopyProxiesForURL(url as CFURL, systemProxySettings).takeUnretainedValue() as? [[AnyHashable: Any]] ?? []
for proxy in proxiesForTargetUrl {
print("Proxy: \(String(describing: proxy))")
//Print the proxy type
print("Proxy Type: \(String(describing: proxy[kCFProxyTypeKey]))")
//There different proxy value keys depending on the type, this is an example of getting the proxy config script if the type is kCFProxyTypeAutoConfigurationURL. If the proxy type were kCFProxyTypeSOCKS you would want to access the SOCKS property keys to see/get the SOCKS proxy values
print("Proxy Autoconfig script URL: \(String(describing: proxy[kCFProxyAutoConfigurationURLKey]))"
}
}
Have you investigated using something like ASIHttpRequest, see the section in the how to document describing proxy support.
At the very least the source code should contain some helpful guidance.
Take a look at the CFProxySupport API, in particular CFNetworkCopyProxiesForURL() will let you read the proxies that are needed to get to a particular URL.