Unable to get response from server - ios

Unable to hit the server through iPhone Simulator, But able to hit the same API through a browser (with proxies enabled in network settings).
There is no trusted certificate.
Error Log
nw_proxy_resolver_create_parsed_array PAC evaluation error: NSURLErrorDomain: -1003
NSURLSession/NSURLConnection HTTP load failed
The certificate for this server is invalid. You might be connecting to a server that is pretending to be "domain name"...
TIC SSL Trust Error

Try adding at the end of your Appdelegate class after #end,
Objective-C
#implementation NSURLRequest(ATS)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host {
return YES;
}
#end
Swift
extension URLRequest {
static func allowsAnyHTTPSCertificate(forHost host: String?) -> Bool {
return true
}
}

Related

How to connect Starscream iOS client to Java webserver

I'm running Spring Boot v2.2 with a correct WebSocketHandler(). I'm confident the server is correct because when I go to http://websocket.org/echo.html and attempt to connect to our server, we can verify connection on both the server and the browser client.
However, in iOS (I'm testing on 2 simulators - iOS 12 and iOS 13.3), I'm not able to connect. I'm now attempting to utilize Starscream. (attempting this with Socket.io led to unsolvable issues and attempting this with SocketRocket led to issues simply getting it to build on iOS 13.3.)
The issue I'm facing now is that Starscream just fails silently when attempting to connect to the address of our java server (ws://127.0.0.1:8080/socket). When I say fail silently, I mean that nothing happens on the client or server indicating that there was an error but also by debugging I can see that isConnected = false on our iOS socket.
To attempt to fix this issue I've tried:
adding App Transport Security Settings -> Allow Arbitrary Loads = YES in Info.plist.
adding NSExceptionDomains -> NSExceptionAllowsInsecureHTTPLoads = YES in Info.plist.
utilizing both localhost and 127.0.0.1, both with /socket or / and HTTP instead of ws/wss.
I was even able to effectively query google.com with a GET request using native Swift.
import Foundation
import Starscream
class WinkNetworkClient : WebSocketDelegate {
private var isConnected : Bool = false
init() {
let socket: WebSocket =
WebSocket(request:
URLRequest(url: URL(string: "ws://127.0.0.1:8080/socket")!), certPinner: FoundationSecurity(allowSelfSigned: true))
socket.delegate = self
socket.connect()
// socket.write(string: "Hi Server!")
print("Client done")
}
func didReceive(event: WebSocketEvent, client: WebSocket) {
switch event {
case .connected(let headers):
isConnected = true
print("websocket is connected: \(headers)")
case .disconnected(let reason, let code):
isConnected = false
print("websocket is disconnected: \(reason) with code: \(code)")
case .text(let string):
print("Received text: \(string)")
case .binary(let data):
print("Received data: \(data.count)")
case .ping(_):
break
case .pong(_):
break
case .viabilityChanged(_):
break
case .reconnectSuggested(_):
break
case .cancelled:
isConnected = false
case .error(let error):
isConnected = false
print("error connecting to websocket: \(String(describing: error))")
}
}
}
I'm very lost as to what the issue might be. What am I doing wrong?

Ktor client IOS and self-signed certificate

I'm using Ktor and Kotlin/native in iOS in an iOS app that accesses an internal dev server. The dev server uses a certificate issued by an internal CA which is not publicly trusted.
When trying to access the server with the following code :
internal suspend fun performHttp(url : String)
{
// URL is a self signed HTTPS: request
val client = HttpClient(Ios)
val response = client.get<String>(url)
println(response)
}
it throws the following exception :
TIC SSL Trust Error [32:0x281956dc0]: 3:0
esri2[470:136341] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
esri2[470:136341] Task <F3CC4C40-0231-4E58-97F3-F457D5A18BB0>.<1> HTTP load failed (error code: -1202 [3:-9807])
esri2[470:136417] Task <F3CC4C40-0231-4E58-97F3-F457D5A18BB0>.<1> finished with error - code: -1202
esri2[470:136211] Task <F3CC4C40-0231-4E58-97F3-F457D5A18BB0>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “server1.internal.lan” which could put your confidential information at risk." UserInfo={NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, NSErrorPeerCertificateChainKey=(
"<cert(0x12b094e00) s: server1.internal.lan i: Internal-Issuing-CA2>",
How do I convince Ktor that it should access this URL, or ignore untrusted certs? Yes, I know that one should not ignore untrusted certs, but this is a lab test.
Ktor iOS engine offers the ability to configure the underlying NSURLSession with the help of IosClientEngineConfig.kt.
With it you can configure (amongst other things) a ChallengeHandler by setting the block for handleChallenge in the config like this:
val client = HttpClient(Ios) {
engine {
handleChallenge(TrustSelfSignedCertificate())
}
}
Then you need to implement a class in Kotlin something like this:
internal data class TrustSelfSignedCertificate internal constructor(
private val validateTrust: Boolean = true
) : ChallengeHandler {
override fun invoke(
session: NSURLSession,
task: NSURLSessionTask,
challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Unit
) {
val hostname = challenge.protectionSpace.host
val serverTrust = challenge.protectionSpace.serverTrust
var result: SecTrustResultType = 0u
memScoped {
val nativeResult = alloc<SecTrustResultTypeVar>()
nativeResult.value = result
SecTrustEvaluate(serverTrust!!, nativeResult.ptr)
}
val serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)
val serverCertificateData = SecCertificateCopyData(serverCertificate)
val data = CFDataGetBytePtr(serverCertificateData)
val size = CFDataGetLength(serverCertificateData)
val cert1 = NSData.dataWithBytes(data, size.toULong())
val pathToCert = NSBundle.mainBundle.pathForResource("myOwnCert", "cer")
val localCertificate: NSData = NSData.dataWithContentsOfFile(pathToCert!!)!!
if (localCertificate == cert1) {
completionHandler(
NSURLSessionAuthChallengeUseCredential,
NSURLCredential.create(serverTrust)
)
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
}
}
}
Also, don't forget to put you certificate as a file "myOwnCert.cer" into you iOS project (maybe on the top-level).
NOTE
Ktor with iOS engine does not respect/use NSApptransportSecurity.
The code is based on this answers.
With the help of this blog-post.

Firebase Task finished with error - code: -1200

I am unable to access data from Firebase storage on my iOS app on my current connection. When I connect to a VPN, it allows me to connect and download data from Firebase Storage normally. I have also tried to allow arbitrary loads but to no use. Any suggestions?
The following is the code:
let tempImageRef = storage.child("CoverArt/Issue15.jpg")
tempImageRef.getData(maxSize: 1*1000*1000) { (data, error) in
if (error == nil)
{ //Do something }
else { print(error!.localizedDescription) } }
The following is the error:
Task <D343DC6F-2D37-4246-A0BA-4044BF36C83D>.<1> finished with error - code: -1200 An unknown error occurred, please check the server response.
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)

Error Loading objects from a Web Server

I use this code to get my objects on web like the Ikea app, but it's not working and gives me the error below.
func loadModel() {
let virtualObjectURL: URL!
virtualObjectURL = URL(string: "https://example.com/\(modelName).\(fileExtension)")
let virtualObjectScene = try! SCNScene(url: virtualObjectURL)
let wrapperNode = SCNNode()
for child in virtualObjectScene.rootNode.childNodes {
child.geometry?.firstMaterial?.lightingModel = .physicallyBased
child.movabilityHint = .movable
wrapperNode.addChildNode(child)
}
self.addChildNode(wrapperNode)
modelLoaded = true
}
It looks like an SSL certificate error, but I tried AllowArbitaryLoads and it didn't work.
Must I use MySQL or something? I feel like if I don't have any SSL certificate errors, it gives me another error.
2017-11-15 18:18:05.669124+0300 ARKitProject[2908:2157180] Strict Trust Evaluation yielded status(-9802) for [1:0x1c416f780]
2017-11-15 18:18:05.669206+0300 ARKitProject[2908:2157180] TIC SSL Trust Error [1:0x1c416f780]: 3:0
2017-11-15 18:18:05.669430+0300 ARKitProject[2908:2157180] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-11-15 18:18:05.669469+0300 ARKitProject[2908:2157180] Task <DF717E27-6EC4-4800-8B1A-01D6B796CFE7>.<0> HTTP load failed (error code: -1200 [3:-9802])
2017-11-15 18:18:05.670112+0300 ARKitProject[2908:2157268] NSURLConnection finished with error - code -1200

iOS Mapkit get directions works in Playground , but not in app update:

Here's a simple app with a VC that asks for directions from MapKit. It compiles and executes, but doesn't work properly. Below is the complete code, followed by the log results:
//
// ViewController.swift
// MapKitDirections
//
import UIKit
import MapKit
class ViewController: UIViewController {
func getDistance() {
let source = MKMapItem(placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(-41.27, 173.28), addressDictionary: nil))
let destination = MKMapItem(placemark: MKPlacemark(
coordinate: CLLocationCoordinate2DMake(-41.11, 173), addressDictionary: nil))
let directionsRequest = MKDirectionsRequest()
directionsRequest.source = source
directionsRequest.destination = destination
let directions = MKDirections(request: directionsRequest)
print("before: directions.calculateDirectionsWithCompletionHandler")
directions.calculateDirectionsWithCompletionHandler({(response, error) in
print("\nwithin: completion handler\n")
print("\n error: \(error)")
print("\n response: \(response?.routes.first?.distance)")
})
print("after: directions.calculateDirectionsWithCompletionHandler\n")
}
override func viewDidLoad() {
super.viewDidLoad()
getDistance()
}
}
before: directions.calculateDirectionsWithCompletionHandler
after: directions.calculateDirectionsWithCompletionHandler
2015-07-03 21:32:09.536 MapKitDirections[293:69261] CFNetwork SSLHandshake failed (-9824)
2015-07-03 21:32:09.541 MapKitDirections[293:69261] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
2015-07-03 21:32:09.545 MapKitDirections[293:69218] PBRequester failed with Error Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo=0x12f660710 {_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x12f713a00 "An SSL error has occurred and a secure connection to the server cannot be made.", NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://gsp-ssl.ls.apple.com/directions.arpc, NSErrorFailingURLStringKey=https://gsp-ssl.ls.apple.com/directions.arpc, _kCFStreamErrorDomainKey=3}
within: completion handler
error: Optional(Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo=0x12f660710 {_kCFStreamErrorCodeKey=-9824, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSUnderlyingError=0x12f713a00 "An SSL error has occurred and a secure connection to the server cannot be made.", NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://gsp-ssl.ls.apple.com/directions.arpc, NSErrorFailingURLStringKey=https://gsp-ssl.ls.apple.com/directions.arpc, _kCFStreamErrorDomainKey=3})
response: nil
This question was previously posted as "iOS Mapkit get directions works in Playground , but not in app". but #matt wanted to see the code within an app instead of a Playground.
Admittedly, this is a very simple app -- that does nothing but attempt to get directions. I did it this way to focus on the issue and avoid the distraction of unnecessary code.
FWIW, the same code executed in a Playground returns the directions, as shown in the original post.

Resources