I'm using OS X Server 4.1.3 and an iPhone 6 with iOS9 Beta-4.
When I try to connect to the OS X Server ("skw.local") with
let urlPath: String = "https://skw.local/"
let url: NSURL = NSURL(string: urlPath)!
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let sesh = NSURLSession(configuration: sessionConfig)
let task = sesh.dataTaskWithRequest(request) {(data, response, error) -> Void in
if error == nil {
print("Response: \(response)")
}
else {
print(error, appendNewline: true)
}
}
task.resume()
I get the following error:
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
You might be connecting to a server that is pretending to be “skw.local” which could put your confidential information at risk."
I have tried bypassing the NSAppTransportSecurity requirements by adding the following to my Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
but I get the same errors.
Anyone else having similar trouble?
edit: I also posted this over on apple's dev forum
Related
I am new to flutter development. I am trying hard to make the https calls work. Whenever I call a https url, it throws the below error:
SocketException: Failed host lookup: 'someserver.com' (OS Error: nodename nor servname provided, or not known, errno = 8)
Below is the code I am using,
final ioc = new HttpClient();
ioc.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
final http = new IOClient(ioc);
return http
.post(url, body: body, headers: headers, encoding: encoding)
.then((response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception("Error while posting data");
}
return _decoder.convert(res);
});
I have checked below few links and many more and tried all of them but nothing seems to work.
How to solve SocketException: Failed host lookup: 'www.xyz.com' (OS Error: No address associated with hostname, errno = 7)
https://github.com/flutter/flutter/issues/27883
Also please note that I am able to access the server from the browser. Same server is being access from iOS app as well(built using XCode). From iOS I am able to access the server.
Kindly help!!!
The http package provides the simplest way to fetch data from the internet.
To install the http package, add it to the dependencies section of the pubspec.yaml file. You can find the latest version of the http package to here
dependencies:
http: <latest_version>
Import the http package.
import 'package:http/http.dart' as http;
Additionally, in your AndroidManifest.xml file, add the Internet permission.
<uses-permission android:name="android.permission.INTERNET" />
Then like the below function, you will be able to get/fetch/post HTTP call
Future<http.Response> getchData() {
return http.get('https://jsonplaceholder.typicode.com/albums/1');
}
For Advanced HTTP call and management you can use Dio plugin
I am attempting to write a simple scraper with AlamoFire, vis a vis a server-side Vapor back end. AlamoFire appears to be initiated properly, but I'm not getting any action from the callback handler.
import Routing
import Vapor
import Alamofire
public func routes(_ router: Router) throws {
router.get("scrape") { req -> String in
let stuff = Stuff(id: nil, sourcecode: "This saves to the database.")
stuff.save(on: req)
let q = Alamofire.request("http://sigh-fi.com/test.txt").responseString { response in
// None of this prints to the terminal.
print("Success: \(response.result.isSuccess)")
print("Request: \(String(describing: response.response))")
print("Result: \(String(describing: response.result))")
print("String: \(String(describing: response.result.value))")
// ideally I'd like to run...
// let morestuff = Stuff(id: nil, sourcecode: response.result.value)
let morestuff = Stuff(id: nil, sourcecode: "This doesn't save to the database, so I'm not even getting that far.")
morestuff.save(on: req)
}
print(q) // prints "GET http://sigh-fi.com/test.txt" as expected
return "okay"
}
}
Unfortunately I can't tell if this is a Vapor problem, an Alamofire or Swift problem. Any suggestions would be greatly appreciated.
So it turns out that Vapor has its own HTTP client library, and it seems to work just fine. Still unsure why Alamofire fell apart, but it's moot.
Thank you for your assistance, Nick.
https://docs.vapor.codes/3.0/http/client/
I want to request the youtube-data-api v3 from my tvOS App. To do so I wrote the following class:
class YoutubeSearch {
static let sharedClient = YoutubeSearch()
private var task: NSURLSessionDataTask!
func getVideoNSURLsForTitle(title: String, completionHandler: ([String], NSError?) -> Void ) -> NSURLSessionTask {
// URL
let urlString = makeURL(title)
let url = NSURL(string: youtubeApi)
// cancel task, if there is already one
task?.cancel()
// setup new request
let request = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// No errors occured
do {
// some JSON processing
// complitionHandler is returned here
} catch let parseError {
// Some other error
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("YoutubeSearch Error: '\(jsonStr)'")
}
}
// execute request
task.resume()
return task
}
}
The code works fine in the simulator. I get a valid JSON. But on tvOS it throws an error telling me the certificate is invalid:
NSUnderlyingError=0x13e207d70 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=, _kCFNetworkCFStreamSSLErrorOriginalValue=-9814, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9814, kCFStreamPropertySSLPeerCertificates={type = immutable, count = 3, values = (
0 :
1 :
2 :
)}}}, NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “www.googleapis.com” which could put your confidential information at risk., NSErrorFailingURLKey=https://www.googleapis.com/youtube/v3/search?videoEmbeddable=true&videoType=any&videoDefinition=any&order=relevance&part=snippet&videoDimension=any&q=lets+play+berlin&videoCaption=closedCaption&videoLicense=any&videoSyndicated=true&type=video&videoDuration=short&maxResults=10&key={API-KEY}, NSErrorFailingURLStringKey=https://www.googleapis.com/youtube/v3/search?videoEmbeddable=true&videoType=any&videoDefinition=any&order=relevance&part=snippet&videoDimension=any&q=lets+play+berlin&videoCaption=closedCaption&videoLicense=any&videoSyndicated=true&type=video&videoDuration=short&maxResults=10&key={API-KEY}, NSErrorClientCertificateStateKey=0})
Yet I wasn't able to nail down the problem. I found Apples Technical Note TN2232 on HTTPS Server Trust Evaluation, but frankly said much to work through while I'm not sure if I just forgot about a simple additional thing.
I've learned that I could disable server trust. But this is not an option for me as the app is supposed to apply at the Apple Store.
Does anybody faced the same problem? Or does anybody have a clue on what to do in order to solve the problem?
Kind regards!
Using IBM Mobile First PlatForm Version 7.1 I am trying to call a Java Adapter from iOS Application using following code.
[[WLResourceRequest requestWithURL:url method:WLHttpMethodPost] sendWithJSON:#{#"one":#"two"} completionHandler:^(WLResponse *response, NSError *error) {
NSLog(#"%#",response);
NSLog(#"%#",error);
}];
Java Method on adapter side looks as following.
#POST
#Consumes("application/json")
#Produces("application/json")
public String hello(JSONObject body){
return body.toString();
}
But I get Following error in response
2016-04-20 11:31:15.520 mbs-call[15092:3787968] Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)" UserInfo={com.alamofire.serialization.response.error.response= { URL: http:/0.0.0.0:10080/mbs-api/adapters/basicadpt/users } { status code: 415, headers {
Connection = Close;
"Content-Language" = "en-US";
"Content-Length" = 0;
Date = "Wed, 20 Apr 2016 02:31:15 GMT";
"X-Powered-By" = "Servlet/3.0";
} }, NSErrorFailingURLKey=http://0.0.0.0:10080/mbs-api/adapters/basicadpt/users, com.alamofire.serialization.response.error.data=<>, NSLocalizedDescription=Request failed: unsupported media type (415)}
And it seems that in iOS SDK it adds header application/x-www-url-form-urlencoded in request when any method is called.
I have following 2 questions.
How to pass JSON Body to Java adapter?
Behaviour of sendWithJSON is different on iOS and Android. On Android it seems to add application/json header when we call adapter. Is that a bug or part of behaviour?
I believe this is a bug. I think that using sendWithJSON should automatically assume that the content type is application/json.
I suggest that you open a support request (PMR) so that they can improve the experience.
In the meantime, I found an easy workaround:
[request addHeaderValue:#"application/json" forName:#"Content-Type"]
Or in Swift:
request.addHeaderValue("application/json", forName: "Content-Type")
I had this same issue with the cordova version of an application.
var userIDTag = 'some_string';
var subTag = [userIDTag]; //<- this worked
var subTag = userIDTag; //<- this failed with the above error
var subTag = '[\'' + some_string + '\']'; //<- this also failed with the above error
The below is what I ended up doing for a Cordova app.
function subscribeByTag(userIDTag) {
var subTag = [userIDTag];
console.log("subTag: " + subTag);
WLAuthorizationManager.obtainAccessToken("push.mobileclient").then(
MFPPush.subscribe(
subTag,
function(subTag) {
navigator.notification.alert("Subscribed successfully");
},
function(failureResponse){
navigator.notification.alert("Failed to subscribe");
console.log("Failedtosubscribe:" + JSON.stringify(failureResponse));
}
)
);
}
I'm using NSUrlSessionTaskDelegate to upload files into a server, but server codes aren't given back in the didCompleteWithError. This matches the apple documentation:
Server errors are not reported through the error parameter. The only
errors your delegate receives through the error parameter are
client-side errors, such as being unable to resolve the hostname or
connect to the host.
But is there any other way I can get the server error's like a 400 Bad Request or something? Because every file upload is a success now even when I get a bad request back..
Something like this should work. But I didn't test it. It is posted as an answer just because of easier code formatting...
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
if (!error)
{
NSHTTPURLResponse *response = task.response;
NSLog(#"StatusCode: %d",response.statusCode);
if (response.statusCode != 200) //note that other 2xx codes might be valid
{
//....
}
}
else
{
NSLog(#"Error: %#",error.description);
}
}
In SWIFT 5, you can do the same like below.
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print(task.response ?? "")
if let urlResponse = task.response as? HTTPURLResponse {
print(urlResponse.statusCode)
}
}