removing trimming special characters - ios

I've been trying to trim and remove characters from:
{
"data":
{
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/13254063_1039990606071446_7680951628744860479_n.jpg?oh=e5088fb1a981041f60c9abde6762d892&oe=57C12344"
}
}
and convert it at something like:
https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/13254063_1039990606071446_7680951628744860479_n.jpg?oh=e5088fb1a981041f60c9abde6762d892&oe=57C12344
Here is my code :
let dataStore = backend.persistenceService.of(Users.ofClass())
dataStore.find(
{ ( users : BackendlessCollection!) -> () in
print("Users have been fetched (ASYNC): \(users)")
let page = users.getCurrentPage()
for userx in page {
print(userx.picture)
}
},
error: { ( fault : Fault!) -> () in
print("Server reported an error (ASYNC): \(fault)")
}
)

Seems you are reading from response.
The URL you want and response URL are both same.
So no need to trim it, you can get the URL from the response directly by using valueForKey or objectForKey method.
var URL: String = data.valueForKey("URL") as? String

Related

Xcode, The given data was not valid JSON, Can't read the JSON from API properly

Hello I am creating an app with Xcode and I am having the following problem, I created this API (if you enter the link you'll see the JSON data) https://proyecto-idts6.epizy.com/models/getCategorias.php
If you dont want to enter the link here is how this si how the structure of the JSON looks like:
{
"items":[
{
"categorie":"Fruits",
"id_categorie":"1"
},
{
"categorie":"Animals",
"id_categorie":"2"
},
{
"categorie":"Juices",
"id_categorie":"3"
},
{
"categorie":"Vegetables",
"id_categorie":"4"
},
{
"categorie":"Alcohol",
"id_categorie":"5"
},
{
"categorie":"Desserts",
"id_categorie":"6"
}
]
}
The problem I have is that when I try to decode the data from the API it cant't be decoded properly, I am trying to recreate the same code of this youtube video, but with my API: https://www.youtube.com/watch?v=sqo844saoC4
What I want basically is to print the categories and storage each of them in variables (because i'll need to move the variables between screens)
This is how my code looks like:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://proyecto-idts6.epizy.com/models/getCategorias.php"
getData(from: url)
//Here is where i want to storage the variables from the JSON
}
private func getData(from url: String) {
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("something went wrong")
return
}
do {
let result = try JSONDecoder().decode([ResultItem].self, from: data)
print(result)
}
catch {
print("failed to convert\(error)")
}
})
task.resume()
}
}
struct Response: Codable {
let items: [ResultItem]
}
struct ResultItem: Codable {
let categorie: String
}
My goal is to have variables for example like this: categorie1=("the category 1 called from the JSON"), categorie2=("the category 2 called from the JSON"), categorie3=("the category 3 called from the JSON"),...
The problem is not in the decoding but in the remote API.
Your endpoint (https://proyecto-idts6.epizy.com/models/getCategorias.php) instead of returning a JSON is returning the following HTML
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("f5490e280a5e50f74932909856c3d3a3");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="https://proyecto-idts6.epizy.com/models/getCategorias.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
So you are trying to decode that HTML content, which clearly leads to the error your reported
failed to convertdataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))

Kinvey: Object not saving due to error: Cannot map 'X', a non-existant property

I'm part of the group moving from Parse and checking out Kinvey. However, I can't get objects to save. I get the error:
error : Error Domain=KCSAppDataErrorDomain Code=60102 "Entity does not have property 'NumberOfPlayers' as specified in hostToKinveyPropertyMapping" UserInfo={NSLocalizedRecoverySuggestion=Check the hostToKinveyPropertyMapping for typos and errors., NSLocalizedDescription=Entity does not have property 'NumberOfPlayers' as specified in hostToKinveyPropertyMapping, NSLocalizedFailureReason=Cannot map 'NumberOfPlayers', a non-existant property}
I have followed the guide on their website here:
http://devcenter.kinvey.com/ios/guides/datastore#create
My Code:
class Event: NSObject {
var objectId:String?
var Sport:Int?
var NumberOfPlayers:Int?
var SkillLevel:Int?
var Date:NSDate?
var Time:NSDate?
var Competitive:NSNumber?
override func hostToKinveyPropertyMapping() -> [NSObject : AnyObject]! {
return [
"objectId" : KCSEntityKeyId,
"Sport" : "Sport",
"NumberOfPlayers" : "NumberOfPlayers",
"SkillLevel" : "SkillLevel",
"Date" : "Date",
"Time" : "Time",
"Competitive" : "Competitive",
]
}
}
And the saving:
let event = Event()
event.Sport = 0
event.NumberOfPlayers = playerQuantity
event.SkillLevel = skillLevel
event.Date = date
event.Time = time
event.Competitive = competitive
let collection = KCSCollection(fromString: "Event", ofClass: Event.self)
let store = KCSAppdataStore(collection: collection, options: nil)
// let store = KCSAppdataStore.storeWithOptions([
// KCSStoreKeyCollectionName : "Event",
// KCSStoreKeyCollectionTemplateClass : Event.self
// ])
store.saveObject(event, withCompletionBlock: { (objects, error) -> Void in
if error != nil { print("error : \(error)"); return }
print("saved objects")
}, withProgressBlock: nil)
Neither way of creating the DataStore has worked. They both return the same error.
I have also checked that the AppId and AppSecret are both correct. I can sign up Users and login ok, I just can't save data.
Any ideas?
Any number types should be classified as NSNumbers instead of Ints

Pinterest SDK how to get a PDKPin's link?

It seems that there is a dictionary value I can place in the GET call that corresponds to a property on PDKPin that I can call in my success block to unpack the value, i.e. "url" = PDKPin.url "note" = PDKPin.decriptionText, however I can't find a corresponding property for "link" which is available per the documentation https://developers.pinterest.com/docs/api/pins/?
PDKClient.sharedInstance().getAuthenticatedUserPinsWithFields(Set(["url", "note", "link"]), success:
{ (responseObject :PDKResponseObject!) -> Void in
print("success /(pdk)")
let currentResponseObject = responseObject
let pins = currentResponseObject.pins
self.pinArray = pins()
for pin in self.pinArray {
if let pinAsPDKPin = pin as? PDKPin {
print(pinAsPDKPin.descriptionText)
if let safeURL = pinAsPDKPin.url {
print(safeURL)
}
let link = pinAsPDKPin.link //no such property on PDKPin
}
}
}) { (err :NSError!) -> Void in
print("error NSError: \(err)")
}
It looks kinda weird, but as per the implementation, the 'link' property(from the API) is used as 'url'(in the SDK). Check out the code here : https://github.com/pinterest/ios-pdk/blob/master/Pod/Classes/PDKPin.m#L38
So, if all that you care about is the 'link' from the API, then just access 'url' in the SDK(in PDKPin object).

Getting back nil from Google Translate using Swift and Alamofire

I am trying to use Alamofire to use the Google Translate api.
Here is the code I am trying to use:
let textToTranslate = "你好"
let parameters = ["key":"MY_PRIVATE_IOS_APP_KEY","q":"\(textToTranslate)",
"source":"zh-CN","target":"en"]
Alamofire.request(.GET, "https://www.googleapis.com/language/translate/v2/languages", parameters:parameters)
.responseJSON
{ (_, _, JSON, _) -> Void in
let translatedText: String? = JSON?.valueForKeyPath("data") as String?
println(translatedText)
}
The console keeps printing nil.
Also, in the Google Translate API Usage Report it says I have "Client Errors".
This is the kind of output I get when I try this in the browser:
{
"data": {
"translations": [
{
"translatedText": "hello"
}
]
}
}
What am I missing or doing wrong?
The URL that you should GET is:
https://www.googleapis.com/language/translate/v2?parameters
On your code I see the URL:
https://www.googleapis.com/language/translate/v2/languages?parameters

How can I get the Swift/Xcode console to show Chinese characters instead of unicode?

I am using this code:
import SwiftHTTP
var request = HTTPTask()
var params = ["text": "这是中文测试"]
request.requestSerializer.headers["X-Mashape-Key"] = "jhzbBPIPLImsh26lfMU4Inpx7kUPp1lzNbijsncZYowlZdAfAD"
request.responseSerializer = JSONResponseSerializer()
request.POST("https://textanalysis.p.mashape.com/segmenter", parameters: params, success: {(response: HTTPResponse) in if let json: AnyObject = response.responseObject { println("\(json)") } },failure: {(error: NSError, response: HTTPResponse?) in println("\(error)") })
The Xcode console shows this as a response:
{
result = "\U8fd9 \U662f \U4e2d\U6587 \U6d4b\U8bd5";
}
Is it possible to get the console to show the following?:
{
result = "这 是 中文 分词 测试"
}
If so, what do I need to do to make it happen?
Thanks.
Instead of
println(json)
use
println((json as NSDictionary)["result"]!)
This will print the correct Chinese result.
Reason: the first print will call the debug description for NSDictionary which escapes not only Chinese chars.
Your function actually prints the response object, or more accurately a description thereof. The response object is a dictionary and the unicode characters are encoded with \Uxxxx in their descriptions.
See question: NSJSONSerialization and Unicode, won't play nicely together
To access the result string, you could do the following:
if let json: AnyObject = response.responseObject {
println("\(json)") // your initial println statement
if let jsond = json as? Dictionary<String,AnyObject> {
if let result = jsond["result"] as? String {
println("result = \(result)")
}
}
}
The second println statement will print the actual string and this code actually yields:
{
result = "\U8fd9 \U662f \U4e2d\U6587 \U6d4b\U8bd5";
}
result = 这 是 中文 测试

Resources