Iam using libjingle_peerconnection library for webrtc connection,
this is the init of rtc connection, i works for the same network,
not for other networks
what i need to do for turn server to work???
func initalizeWebRTC() -> Void {
RTCPeerConnectionFactory.initializeSSL()
self.webRtcClient = RTCPeerConnectionFactory.init()
let stunServer = self.defaultStunServer()
let turnServer = self.getTurn()
let defaultConstraint = self.createDefaultConstraint()
let array = [turnServer, stunServer]
print(array)
self.peerConnection = self.webRtcClient?.peerConnection(withICEServers: array, constraints: defaultConstraint, delegate: self)
print(peerConnection)
self.localVideoView.delegate = self
self.remoteVideoView.delegate = self
// webrtc initalized local rendering of video on
self.addLocalMediaStrem()
}
func defaultStunServer() -> RTCICEServer {
let url = URL.init(string: "stun:stun.l.google.com:19302");
let iceServer = RTCICEServer.init(uri: url, username: "", password: "")
return iceServer!
}
func getTurn() -> RTCICEServer {
let url = URL.init(string: "turn:xxx.xxx.xx.xxx:xxxx");
let iceServer = RTCICEServer.init(uri: url, username: "xxxx", password: "xxxxxxxxxxxx")
return iceServer!
}
Related
As I don't have enough rep points for comment for this question URL Encoding swift IOS, I created a new question. I would like to receive feedback on making it more swifty for use cases like this one.
My understanding of OP question is inside API response or from data, there is multiple links of URLs for image, with possibility of different host domains.
In such cases, the host URL could be first retrieved like in this answer. In similar way, the path can also be retrieved separately.
The path can be encoded like as below and concat back to host string later.
addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
This is what I initially tried out in playground.
import Foundation
extension String {
var encoded: String? {
return self.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
}
}
let urlStrings:[String] = ["https://example.com/test.jpg"
"https://example.cc/test2.jpg",
"https://example.dev.cc/test3.jpg"]
var encodedUrlStrings: [String] = []
urlStrings.forEach { urlString in
print(urlString)
guard let url = URL(string: urlString),
let domain = url.host,
let encodedPath = url.path.encoded else { return }
let encodedUrlString = domain + encodedPath
encodedUrlStrings.append(encodedUrlString)
}
encodedUrlStrings.count
encodedUrlStrings.forEach { print($0) }
But the weird thing I notice from OP's question is the url itself should not be already including character like space or any unicode character.
https://ftximages.apk.in/test Fretailer_Point-6685.jpg
For such string, converting into URL will always return nil with URL(String:) method. Same result for using URLComponents as well as the characters in path are still not usable in URL. So this need to make more agreements with backedn dev or anyone who's sending such URL string without encoded characters.
Just in case the backend dev is making a fuss, following codes will gives example of encoded URL strings.
String extension from #Claudio's answer.
import Foundation
extension String {
var encoded: String? {
return self.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
}
}
let urlStrings:[String] = ["https://example.com.cc/folder/test.jpg",
"https://example.com/test.jpg",
"https://Ftximages.apk.in/test Fretailer_Point-6685.jpg",
"https://example.com/원 더 우먼.jpg",
"https://example.dev.cc/刺客聶隱娘-6685.jpg",
"https://example.cc/बाजीराव मस्तानी.jpg"]
var encodedUrlStrings: [String] = []
func encodeURL(scheme: String, host: String, path: String) -> String? {
var components = URLComponents()
components.scheme = scheme
components.host = host
components.path = path
return components.url?.absoluteString ?? URL(string: "\(scheme)://\(host)/\(path)")?.absoluteString
}
func encodeWeirdUrlString(_ urlString: String) -> String? {
var urlSplitStrings = urlString.components(separatedBy: ["/"])
urlSplitStrings.removeAll(where: { $0.isEmpty })
guard urlSplitStrings.indices.contains(0), urlSplitStrings.indices.contains(1) else { return nil }
let scheme = String(urlSplitStrings[0].dropLast())
let host = urlSplitStrings[1]
urlSplitStrings.remove(at: 1)
urlSplitStrings.remove(at: 0)
guard let path = urlSplitStrings.joined(separator: "/").encoded else { return nil}
let encodedUrlString = encodeURL(scheme: scheme, host: host, path: path)
return encodedUrlString
}
urlStrings.forEach { urlString in
print(urlString)
guard let url = URL(string: urlString),
let scheme = url.scheme,
let host = url.host,
let encodedPath = url.path.encoded,
let encodedUrlString = encodeURL(scheme: scheme, host: host, path: encodedPath) else {
if let encodedUrlString = encodeWeirdUrlString(urlString) {
encodedUrlStrings.append(encodedUrlString)
}
return
}
encodedUrlStrings.append(encodedUrlString)
}
encodedUrlStrings.count
encodedUrlStrings.forEach { print($0) }
Are there any improvements to make this solution more swifty?
I am trying to setup server using Vapor. As client, I have simple iOS app using NSUrlSession - URLSessionWebSocketTask. My question is... how I can set session.data from iOS app?
iOS App - Connect method
func connect(completion: #escaping ()->() = { }) {
guard webSocketTask == nil else { return }
self.username = "Name"
self.userID = UUID().uuidString
let url = URL(string: "ws://localhost:8080/connect")!
webSocketTask = URLSession.shared.webSocketTask(with: url)
webSocketTask?.receive(completionHandler: onReceive)
webSocketTask?.resume()
}
Vapor:
app.webSocket("connect") { request, ws in
let controller = Controller()
let userName = request.session.data["nickname"] ?? "Unknown user"
let data = request.session.data["data"] ?? "Empty Data"
controller.addUser(userName, with: room, withConnection: ws)
.....
....
...
..
.
You may use NSURLSessionDataTask.
https://developer.apple.com/documentation/foundation/nsurlsessiondatatask
I am integrating sharing options from my app to Snapchat.
I have a dynamic URL obtained in an object and clicking the Snapchat's share button directly opens the app if Snapchat is there on the device and show the text with the link. I am using the below code to share which gives an error on Snapchat. Below is my Code.
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let promoText = "Check out this great new video from \(obj.name ?? ""), I found on talent app"
let shareString = "snapchat://text=\(promoText)&url=\(myURL)"
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: escapedShareString)
UIApplication.shared.openURL(url!)
}
}
I have used this to post video to snapchat. You have option to either post text or a video.
Pod used
pod 'SnapSDK', :subspecs => ['SCSDKCreativeKit']
import SCSDKCreativeKit
var scInstalled = false
override func viewDidLoad() {
super.viewDidLoad()
scInstalled = schemeAvailable(scheme: "snapchat://")
}
func ShowSnapchat(){
if scInstalled {
//shareTextOnSnapchat(obj:videoObj ?? VideoData())
shareFileOnSnapchat(obj:videoObj ?? VideoData())
}else{
downloadSharingAppAlert(appName:"Snapchat")
}
}
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let originalString = "\(myURL)"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
//let url = URL(string: "snapchat://snap?text=\(escapedString!)")
let url = URL(string: "https://www.snapchat.com/send?text=\(escapedString!)")
if UIApplication.shared.canOpenURL(url! as URL)
{
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
}
}
}
func shareFileOnSnapchat(obj:VideoData){
//// SHARE VIDEO
LoadingOverlay.shared.showLoaderView(view: self.view)
let shaUrl = URL(string: obj.output_vid ?? "")
if let myURL:URL = shaUrl{
let snapVideo = SCSDKSnapVideo(videoUrl: myURL)
let snapContent = SCSDKVideoSnapContent(snapVideo: snapVideo)
// Send it over to Snapchat
snapAPI.startSending(snapContent) { (error) in
if let error = error {
print(error.localizedDescription)
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_oopsSomethingWentwrong)
} else {
// success
print("Posted to snapchat")
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_postedToSnapchat)
}
}
}
}
}
func downloadSharingAppAlert(appName:String){
var appStoreURL = "https://apps.apple.com/in/app/snapchat/id447188370"
//Open Appstore for Download
}
Have a Traccar server at http://188.120.235.97:8082/, trying to connect websocket using Swift library Starscream (https://github.com/daltoniam/Starscream).
There is my code:
func connect(_ token: String) {
var urlString = "\(self.serverURL)api/socket"
urlString = urlString.replacingOccurrences(of: "http", with: "ws")
self.socket = WebSocket(url: URL(string: urlString)!, protocols: ["chat"])
guard let socket = self.socket else { return }
socket.headers["Cookie"] = "JSESSIONID=\(token)"
socket.headers["Sec-WebSocket-Key"] = "\(token)"
socket.headers["Sec-WebSocket-Protocol"] = "chat"
socket.headers["Sec-WebSocket-Version"] = "13"
socket.headers["Host"] = self.serverURL
socket.headers["Upgrade"] = "websocket"
socket.headers["Connection"] = "Upgrade"
socket.headers["Origin"] = self.serverURL
socket.headers["Sec-WebSocket-Accept"] = "application/json, text/html"
socket.delegate = self
socket.connect()
print("isConnected: \(socket.isConnected)")
print("socket: \(socket)")
print("headers: \(socket.headers)")
}
Nothing happened, status of websocket is CONNECTING, never OPEN.
Using Fiddler cannot see any GET request also, when calling socket.connect...
Does it work in iOS simulator?
I've some trouble about SSL Pinning in Alamofire. I've examine all the document that I can found but I couldn't manage to handle it. I might get it wrong.
Currently, I am working on an example
https://github.com/antekarin/ios-ssl-pinning
I converted it to swift 3 and updated the pods to the latest version of Alamofire.
To make it clear; the project is use "github.com.cer" certificate, and because I define domain (like below) I expect to get success when I go to "https://github.com" and to get failure when I enter (in example) "https://twitter.com". But in every condition my request return some value and does not block other requests.
self.serverTrustPolicies = [
"github.com": self.serverTrustPolicy!
]
Code:
let githubCert = "github.com"
let corruptedCert = "corrupted"
var urlSession: Foundation.URLSession!
var serverTrustPolicy: ServerTrustPolicy!
var serverTrustPolicies: [String: ServerTrustPolicy]!
var afManager: SessionManager!
var isSimulatingCertificateCorruption = false
override func viewDidLoad() {
super.viewDidLoad()
self.configureAlamoFireSSLPinning()
self.configureURLSession()
self.activityIndicator.hidesWhenStopped = true
}
// MARK: SSL Config
func configureAlamoFireSSLPinning() {
let pathToCert = Bundle.main.path(forResource: githubCert, ofType: "cer")
let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!
self.serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
validateCertificateChain: true,
validateHost: true
)
self.serverTrustPolicies = [
"github.com": self.serverTrustPolicy!
]
self.afManager = SessionManager(
configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: self.serverTrustPolicies)
)
}
// MARK: Button actions
#IBAction func alamoFireRequestHandler(_ sender: UIButton) {
self.activityIndicator.startAnimating()
if let urlText = self.urlTextField.text {
self.afManager.request(urlText).responseString { response in
guard let data = response.data, response.error == nil else {
self.responseTextView.text = response.error.debugDescription
self.responseTextView.textColor = UIColor.red
return
}
self.responseTextView.text = String(data: data, encoding: String.Encoding.utf8)!
self.responseTextView.textColor = UIColor.black
}
}
}