Using Bing Translator Api in Xcode using swift - ios

I am using FGTranslator(https://github.com/gpolak/FGTranslator) to access bing translator api with swift
but the problem is that FGTranslator is written in objective c and I am using swift but according to Apple we can do it. I successfully added these classes in my project with bridging header and I also installed AFNetworking with Pod Setup. Now I can successfully compile my program without an error.
override func viewDidLoad() {
super.viewDidLoad()
let BING_CLIENT_ID = "some ID"
let BING_CLIENT_SECRET = "some Secret";
let inputText = "Bonjour"
var fr = "fr"
var to = "en"
var translator :FGTranslator = FGTranslator(bingAzureClientId: BING_CLIENT_ID, secret: BING_CLIENT_SECRET)
translator.translateText(inputText, completion:nil)
}
At the last line where translator.translateText is called completion is required which I am giving nil. Can anybody help me to get translation done. I am a newbie programmer

Related

how to pass values to a web view which is loading a react native app

i am new to react native and very familiar to iOS with swift language.My requirement is in an iOS existing app there will be a web view which is loading a react native app ,here i want to use some values of iOS app in react native.
for example , in iOS app there will be an authorization code ,this auth code i want to use in react native app which is loading in UIWebview.
override func viewDidLoad() {
super.viewDidLoad()
loadReactNativeApp()
}
func loadReactNativeApp(){
let link = "https://staging.abcdefg.com:1442/appname_web/"
let finalUrl:URL!
finalUrl = URL(string: link)
let urlRequest = URLRequest.init(url: finalUrl!)
webview.load(urlRequest)
}
I don't have idea how could we pass the values to react native app.Can any one help me to solve my problem would be great.Thankyou
You have to use the injectedJavaScript prop from WebView.
Eg:
First declare a jsCode variable:
const amount = 2
const jscode = `
if (document.getElementById('txtAmount') == null) {
// field not existing, deal with the error
} else {
document.getElementById('txtAmount').value = '${amount}';
}
`
Please notice the " ` " character. Used to put variables in strings.
Then use it like so:
<WebViewBridge
injectedJavaScript={jsCode}

Is it possible to integrate Google translation in iOS App programmatically (Swift 4)?

I have to translate the data coming from API in my app. For which I need to integrate Google Translate or something that can translate the data that is coming from backend.
How do I start coding this?
There is no specific SDK for the iOS platform for Google translation.
However, you could achieve it by "manually" requesting the translation API(s). For more information, check the Google Cloud Translation API Documentation.
Furthermore: Using ROGoogleTranslate, might save some time, therefore you would be able to do it like this:
var params = ROGoogleTranslateParams(source: "en",
target: "de",
text: "The sentence to be translated")
let translator = ROGoogleTranslate(with: "API Key here")
translator.translate(params: params) { (result) in
print("Translation: \(result)")
}
You can use google Translator URL to translate text inside your Application.
Follow the example.
let selected_language = "en"
let target_language = "hi"
let YourString = "hello"
let GoogleUrl = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + selected_language + "&tl=" + target_language + "&dt=t&dt=t&q=" + YourString
After creating the GoogleUrl perform a Get Request from this URL using urlSession or Alamofire this url will return you json responce of translated text.

Firebase Read to Swift NSArray / or String Swift 3.0

I am working on a project that reads from a Dictionary .plist that is located in the documents directory. I am currently migrating to Firebase. I have the "Write" working to -> Firebase. I also have the "Read" from <- Firebase working. The challenge that I am having is re-formatting the data the way I need it, in order to run it through my RegEx filter. I am not sure what to use to do this, a Parser or what... Just need some direction on the best way to pull the values out from the Firebase data that I read. I have spent about 10 hours trying different ways of formatting the Firebase data, but constantly get errors telling me that I can't change "Any" to "String" or "Any" to "Array". If you have not noticed, I am not a seasoned coder...
I am using Swift 3.0
This is the code that I have. (Note: I have the Firebase SDK installed and this code is just in the viewDidLoad func. for now). Also, I am using an NSObject Class that is outside of my viewDidLoad() for Post.
Thank you
var posts = [Post]()
class Post: NSObject {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//This is the code that reads from FireBase
let ref = Database.database().reference().child("List").queryOrderedByValue()
ref.observe(.value, with: { snapshot in
print(snapshot.value ?? "can't print Values")//snapshot.value is what prints out to the console
self.posts = []
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let post = Post()
post.setValuesForKeys(postDict)
self.posts.append(post)
}
}
}
})
}
The output of the code in the viewDidLoad() produces this output to the console
{"-KmUr43ZPycmz7G3IBlA" = "Adding something";
"-KmUr6M3F6HSEIAMbaVa" = "This is my next one";
"-KmUr8xe2vDtLMZn84kP" = "Emoji";
"-KmWaviTHnzD_EBatRU8" = "next definition";
"-KmYMTqVXHhanJkkId4r" = "Rich is Cool";}
I would like to pull out the values of the above output two different ways
and that is as an Array / NSMutableArray, and a String / NSMutableString
This is what I would like the Array to look like
["Adding something", "This is my next one", Emoji", "next definition", "Rich is Cool"]
This is what I would like the String to look like
Adding something, This is my next one, Emoji, next definition, Rich is Cool
Thank you so much for taking a look at this

Swift framework for iOS and macOS

currently i'm developing an app for my graduation project. The problem is, that it's not just one app, it consists of an iOS app that is made for the users and a macOS app for the "Owner". In the mac App the owner can create a file that should then be red in the iOS app.
Until now I have made a script that has all the necessary variables to transport the information, it can serialise and deserialise a file and assign it to the UI. Everything worked fine as long as I was working on the macOS app, the files can be created, deserialised and so on, however when I tried to go to the iOS app, I copied the exact same script that serves as the dataModel into the project and when I tried to deserialise a file created in the macOS file the app crashed and gave me an error saying:
cannot decode object of class (ExcursionCreator.ExcursionDataModel)
for key (root); the class may be defined in source code or a library
that is not linked'
I investigated on the error and found out that i cannot just copy the script from one project to the other, so I found a source that said that I should create a framework with just this file, however i haven't found any useful topics that talk about frameworks for cross platform.
So my question in a few words is, is it true that I have to create a framework for this purpose and if so how would I do it so it works on macOS as well on iOS. Any other advice would also be greatly appreciated. Thanks in advance Jorge. :)
Update
As asked by danielv here is my code where I store the information, it also conforms to the NSCoding protocol so i can serialise and deserialise it:
import Foundation
class ExcursionDataModel: NSObject, NSCoding {
var title: String
var imagesData = [Data]()
var thumbnailImageData: Data?
var shortText = String()
var completeText = String()
var difficulty: String = "Hard"
var duration: String = "Long"
var isFavourite: Bool = false
var type: excursionType = .other
enum excursionType: String {
case biking
case rafting
case other
}
static let possibleDifficulties = ["Hard", "Medium", "Easy"]
static let possibleDurations = ["Long", "Medium", "Short"]
init (title: String) {
self.title = title
}
override init() {
self.title = "Title"
}
struct PropertyKey {
static let titleKey = "title"
static let imagesKey = "images"
static let thumbnailImageKey = "thumbnailImage"
static let shortTextKey = "shortText"
static let completeTextKey = "completeText"
static let difficultyKey = "difficulty"
static let durationKey = "duration"
static let isFavouriteKey = "isFavourite"
static let typeKey = "type"
}
//MARK: - NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(title, forKey: PropertyKey.titleKey)
aCoder.encode(imagesData, forKey: PropertyKey.imagesKey)
aCoder.encode(thumbnailImageData, forKey: PropertyKey.thumbnailImageKey)
aCoder.encode(shortText, forKey: PropertyKey.shortTextKey)
aCoder.encode(completeText, forKey: PropertyKey.completeTextKey)
aCoder.encode(difficulty, forKey: PropertyKey.difficultyKey)
aCoder.encode(duration, forKey: PropertyKey.durationKey)
aCoder.encode(isFavourite, forKey: PropertyKey.isFavouriteKey)
aCoder.encode(type.rawValue, forKey: PropertyKey.typeKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let title = aDecoder.decodeObject(forKey: PropertyKey.titleKey) as! String
self.init(title: title)
self.imagesData = aDecoder.decodeObject(forKey: PropertyKey.imagesKey) as! [Data]
self.thumbnailImageData = aDecoder.decodeObject(forKey: PropertyKey.thumbnailImageKey) as? Data
self.shortText = aDecoder.decodeObject(forKey: PropertyKey.shortTextKey) as! String
self.completeText = aDecoder.decodeObject(forKey: PropertyKey.completeTextKey) as! String
self.difficulty = aDecoder.decodeObject(forKey: PropertyKey.difficultyKey) as! String
self.duration = aDecoder.decodeObject(forKey: PropertyKey.durationKey) as! String
self.isFavourite = aDecoder.decodeObject(forKey: PropertyKey.isFavouriteKey) as! Bool
self.type = excursionType(rawValue: aDecoder.decodeObject(forKey: PropertyKey.typeKey) as! String)!
}
}
From NSCoder documentation:
NSCoder operates on objects, scalars, C arrays, structures, and
strings, and on pointers to these types. It does not handle types
whose implementation varies across platforms, such as union, void *,
function pointers, and long chains of pointers. A coder object stores
object type information along with the data, so an object decoded from
a stream of bytes is normally of the same class as the object that was
originally encoded into the stream.
The class that you encoded in your MacOS app is ExcursionCreator.ExcursionDataModel. Your iOS app, however, probably has different module name, so even if you include the exact same swift class in your iOS app, the actual namespaced class name would be different, e.g ExcursionIOSApp.ExcursionDataModel.
NSCoder has no idea these are the same classes, when it tries to decode the ExcursionDataModel it doesn't find it, so you get the error.
Your options are:
Option #1
Use an open portable format for your serializations. JSON is a popular choice but there are others. This has a benefit of reusability in platforms outside of Apple's ecosystem, if you later decide to port your app to, say, Android.
There is a foundation JSON serialization support in MacOS/iOS and many open source projects that offer better/additional JSON support.
Option #2
Use a different class that shares same implementation and name across platform. For example, you could use NSDictionary as your data structure. Just be sure that everything you put there is compliant with the restrictions required by NSCoder
Option #3
Put your data class in a framework. This will force the class to have the same name when used from both projects.
To create a framework, choose a MacOS framework project when creating a new projects. Add your ExcursionDataModel to this framework.
Note that you will need to compile this framework for each platform separately. So once you have it for MacOS you will need to add additional target for it in xcode to compile it for iOS.
Then include your framework's project in each of you apps. Make sure to remove the class from your app's sources.
Check Apple's Framework Programming Guide,
Personally, I'd go with option #1 and use open and popular format and stay away from Apple's proprietary serialization.

Swift iOS - OSC Library

Anyone knows a OSC Swift Library to integrate inside an iOS App?
I am experimenting with this however, I am finding hard to make it work with swift.
I have added in my project a bridge-header file, the project load but cannot convert code into swift.
I want to convert the objective-C code below into swift however I cannot find the property "messageWithAddressPattern" when I try the conversion:
- (IBAction)sendSliderMessage:(UISlider *)sender {
F53OSCMessage *message = [F53OSCMessage messageWithAddressPattern:#"/slider" arguments:#[[NSNumber numberWithFloat:sender.value]]];
[self.oscClient sendPacket:message toHost:SENDHOST onPort:SENDPORT];
}
I'm successfully using MetatoneOSC without any issue in a Swift app.
Here's some working code for sending a message:
let oscClient = F53OSCClient.init()
oscClient.host = "127.0.0.1"
oscClient.port = 3000
let message = F53OSCMessage(addressPattern: "/hello", arguments: [0, 1, 2])
oscClient.sendPacket(message)
print("Sent '\(message)' to \(oscClient.host):\(oscClient.port)")

Resources