Google Directions Json Error - objective-c

I'm trying to get the directions using google directions but I'm getting this error :
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised
leading character (41)\
Here is the Json
loadDirections('Avenida Paulista', 'Rua Augusta', { 'locale': 'en', travelMode: G_TRAVEL_MODE_WALKING, avoidHighways: false, getPolyline: true, getSteps: true, preserveViewport: false})
Whats is wrong? Whats Unrecognised leading character (41) mean?
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options {
for (int idx = 0; idx < [endPoints count];idx ++)
{
NSString* msg = [NSString stringWithFormat:#"loadDirections('%#', '%#', %#)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
NSLog(#"msg %#",msg);
mstr = [msg retain];
[self performSelector:#selector(loadDirections:) withObject:nil afterDelay:0.5];
}
}
-(void)loadDirections:(NSString *)message
{
[googleMapsAPI stringByEvaluatingJavaScriptFromString:mstr];
}

The JSON is invalid.
{
'locale': 'en',
travelMode: "G_TRAVEL_MODE_WALKING",
avoidHighways: false,
getPolyline: true,
getSteps: true,
preserveViewport: false
}
I think this has something to do with G_TRAVEL_MODE_WALKING, it should be in quotes. The only valid JSON values are as follows
Objects ({})
Arrays ([])
Value
String ("this is a string")
Number 1/-1
true
false
null
JSON Documentation

Make sure that, while initializing the GDirections object, you also pass an actual element as the second parameter.
As stated in the documentation:
The mode of travel, such as driving (default) or walking. Note that if
you specify walking directions, you will need to specify a panel
to hold a warning notice to users.
If you are using the Map-Kit-Route-Directions extensions, you just have to open the api.html file and, at line 16, substitute this
gdir = new GDirections(null, null);
with this
gdir = new GDirections(null, "body");

Related

Kotlin/JS Invalid property id when adding cursor pointer style to span

Here is the code:
h.span {
css {
cursor = Cursor.pointer
}
+"∄"
...
}
When compiled, it produces the following error:
> Task :browser:processDceKotlinJs FAILED
error: at /.../build/js/packages/kjs-browser/kotlin/kjs-browser.js (1193, 185): invalid property id
Examining the location of the error, we see it's at the $receiver_0.cursor line, below, and it indicates the entry default (at position 185):
function RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList) {
return function ($receiver) {
var $receiver_0 = {};
$receiver_0.cursor = (/*union*/{alias: 'alias', allScroll: 'all-scroll', cell: 'cell', colResize: 'col-resize', contextMenu: 'context-menu', copy: 'copy', crosshair: 'crosshair', default: 'default', eResize: 'e-resize', ewResize: 'ew-resize', grab: 'grab', grabbing: 'grabbing', help: 'help', move: 'move', nResize: 'n-resize', neResize: 'ne-resize', neswResize: 'nesw-resize', noDrop: 'no-drop', notAllowed: 'not-allowed', nsResize: 'ns-resize', nwResize: 'nw-resize', nwseResize: 'nwse-resize', pointer: 'pointer', progress: 'progress', rowResize: 'row-resize', sResize: 's-resize', seResize: 'se-resize', swResize: 'sw-resize', text: 'text', verticalText: 'vertical-text', wResize: 'w-resize', wait: 'wait', zoomIn: 'zoom-in', zoomOut: 'zoom-out'}/*union*/).pointer;
$receiver.className = css($receiver_0);
$receiver.unaryPlus_pdl1vz$('\u2204');
$receiver.onClick = preventDefault(RecordList$lambda$lambda$lambda$lambda$lambda$lambda$lambda$lambda(closure$id, closure$updateList));
return Unit;
};
}
By removing the css block that sets the pointer style, the error disappears.
As an interesting side note, the code runs just fine in development mode (browserDevelopmentRun).

How to read file comment field

In OS X Finder there is 'Comment' file property. It can be checked in finder by adding 'Comment' column or edited/checked after right clicking on file or folder and selecting 'Get info'.
How to read this value in swift or objective-c?
I checked already NSURL and none of them seems to be the right ones
Do not use the low-level extended attributes API to read Spotlight metadata. There's a proper Spotlight API for that. (It's called the File Metadata API.) Not only is it a pain in the neck, there's no guarantee that Apple will keep using the same extended attribute to store this information.
Use MDItemCreateWithURL() to create an MDItem for the file. Use MDItemCopyAttribute() with kMDItemFinderComment to obtain the Finder comment for the item.
Putting the pieces together (Ken Thomases reading answer above and writing answer link) you can extend URL with a computed property with a getter and a setter to read/write comments to your files:
update: Xcode 8.2.1 • Swift 3.0.2
extension URL {
var finderComment: String? {
get {
guard isFileURL else { return nil }
return MDItemCopyAttribute(MDItemCreateWithURL(kCFAllocatorDefault, self as CFURL), kMDItemFinderComment) as? String
}
set {
guard isFileURL, let newValue = newValue else { return }
let script = "tell application \"Finder\"\n" +
String(format: "set filePath to \"%#\" as posix file \n", absoluteString) +
String(format: "set comment of (filePath as alias) to \"%#\" \n", newValue) +
"end tell"
guard let appleScript = NSAppleScript(source: script) else { return }
var error: NSDictionary?
appleScript.executeAndReturnError(&error)
if let error = error {
print(error[NSAppleScript.errorAppName] as! String)
print(error[NSAppleScript.errorBriefMessage] as! String)
print(error[NSAppleScript.errorMessage] as! String)
print(error[NSAppleScript.errorNumber] as! NSNumber)
print(error[NSAppleScript.errorRange] as! NSRange)
}
}
}
}
As explained in the various answers to Mac OS X : add a custom meta data field to any file,
Finder comments can be read and set programmatically with getxattr() and setxattr(). They are stored as extended attribute
"com.apple.metadata:kMDItemFinderComment", and the value is a property
list.
This works even for files not indexed by Spotlight, such as those on a network server volume.
From the Objective-C code here
and here I made this simple Swift function
to read the Finder comment (now updated for Swift 4 and later):
func finderComment(url : URL) -> String? {
let XAFinderComment = "com.apple.metadata:kMDItemFinderComment"
let data = url.withUnsafeFileSystemRepresentation { fileSystemPath -> Data? in
// Determine attribute size:
let length = getxattr(fileSystemPath, XAFinderComment, nil, 0, 0, 0)
guard length >= 0 else { return nil }
// Create buffer with required size:
var data = Data(count: length)
// Retrieve attribute:
let result = data.withUnsafeMutableBytes { [count = data.count] in
getxattr(fileSystemPath, XAFinderComment, $0.baseAddress, count, 0, 0)
}
guard result >= 0 else { return nil }
return data
}
// Deserialize to String:
guard let data = data, let comment = try? PropertyListSerialization.propertyList(from: data,
options: [], format: nil) as? String else {
return nil
}
return comment
}
Example usage:
let url = URL(fileURLWithPath: "/path/to/file")
if let comment = finderComment(url: url) {
print(comment)
}
The function returns an optional string which is nil if the file
has no Finder comment, or if anything went wrong while retrieving it.

Writing a URL to an embed-field using PodioKit

I hope to find some help to diving deeper into Podiokit, the ObjC-API to Podio. I try to set a link-field's value to a URL. My first simple try looked like this:
NSDictionary *embedAttributes = [NSDictionary dictionaryWithObject: #"http://www.google.com" forKey: #"url"];
PKTEmbed *embed = [[PKTEmbed alloc] initWithDictionary: embedAttributes];
item[#"linkfield"] = embed;
I found an example using PHP but had no luck to transform it into Objective-C:
$attributes = array( 'url' => 'http://www.infranet.com' );
$embed = PodioEmbed::create( $attributes );
$attribute['embed']['embed\_id'] = $embed->embed\_id;
$attribute['file']['file\_id'] = $embed->files[0]->file\_id;
$this->orgItem->field('organizationlink')->set\_value($attribute);
Maybe someone knows how to get it right, would be fine :-)
[Edit] The PodioKit-Manual just says:
PKTEmbed *link = ...;
item[#"link"] = link;
[Edit 2] The error occurs when I try to save the item. The log says:
Error: Saving file Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: Ungültige Anforderung (400)" UserInfo=0x600000c7ee80 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x6000008358e0> { URL: https://api.podio.com/item/app/_xxxx_/ } { status code: 400, headers {
"Content-Length" = 263;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 27 Sep 2014 19:16:22 GMT";
Server = nginx;
"X-Podio-Request-Id" = yqyl6yku;
"X-Rate-Limit-Limit" = 250;
"X-Rate-Limit-Remaining" = 248;
} }, NSLocalizedDescription=Request failed: Ungültige Anforderung (400), NSErrorFailingURLKey=https://api.podio.com/item/app/_xxxx_/}
Thanks,
Michael / Hamburg
Sebastian at Podio here. You need to first create the PKTEmbed object server side, then use it as the value of the item field. So you would use:
PKTItem *item = ...;
[[PKTEmbed createEmbedForURLString:#"https://www.google.com"] onSuccess:^(PKTEmbed *embed) {
item[#"link-field"] = embed;
} onError:^(NSError *error) {
// Handle error
}];
The server will assign you an embedID and generate a thumbnail for you etc. I will look into adding the ability to simply provide a URL string directly, as I agree that makes a lot of sense.
Hope that helps!

Json get a parameter can't access on it iOS

That's an example
{
"updated":1350213484,
"id":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson",
"title":"Risultati di feed per \"Prova\"",
"self":[
{
"href":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson"
}
],
"items":[
{
"title":"Home Page - La prova del cuoco",
"id":"http://www.laprovadelcuoco.rai.it/",
"updated":1350213485,
"feed":[
{
"href":"http://www.laprovadelcuoco.rai.it/dl/portali/site/page/Page-ffb545b4-9e72-41e5-866f-a465588c43fa-rss.html"
}
],
"alternate":[
{
"href":"http://www.laprovadelcuoco.rai.it/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Diventa un cuoco provetto con “La Prova del Cuoco”: le videoricette in un' applicazione di facile e veloce consultazione per il tuo Iphone. Scopri come acquistare ..."
}
},
{
"title":"Le prove Invalsi di matematica e italiano",
"id":"http://online.scuola.zanichelli.it/quartaprova/",
"updated":1350213486,
"feed":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/feed/"
}
],
"alternate":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Un sito Zanichelli dedicato alle prove Invalsi di italiano e matematica: esercitazioni, consigli, informazioni utili, novità, aggiornamenti e blog d'autore sulle prove ..."
}
},
How can I get the feed URL?
That's what I do
NSString *daParsare=[reader searchFeed:searchText];
NSArray *items = [[daParsare JSONValue] objectForKey:#"items"];
for (NSDictionary *item in items) {
NSString *title = [item objectForKey:#"title"];
NSString *feed = [item valueForKeyPath:#"feed.href"];
}
[tab reloadData];
With the title everything is ok but when I try to access to the feed paramater I get the error...
Assuming your JSON object is named jsonObject, you would simply access the href element. So, in your current object, the URL is in an object named href, which is the first (and in this case, only) element in an array named feed at the top level:
NSString* urlString = jsonObject[#"feed"][0][#"href"];
You should check to make sure that if feed exists, it's not an empty array before you access one of its elements.
NSString *feed = [item valueForKeyPath:#"feed.href"];
is wrong, as feed refers to an array, that again holds a dictionary.
NSString *feed = [[[item objectForKey:#"feed"] objectAtIndex:0] objectForKey:#"href"];
If you are using an modern Xcode, this last line is the same as in Jason Cocos answer.
NSString* feed = item[#"feed"][0][#"href"];
this syntax is called Object Subscription.

Reliably read value of PHP display_errors

In my PHP error handler I want to do something like:
if (ini_get('display_errors') IS ON)) {
// show debug info
} else {
// show just "oops!"
}
I've look through the docs and stuff, but I can't really find out what the possible values for display_errors are (such as "on", 0, "Yes") and what it does for what value.
What should I put in place of the "IS ON" to reliably read this value?
I use the following code:
if (in_array(strtolower(ini_get('display_errors')), ['1', 'yes', 'on', 'true']) {
// is enabled
} else {
// is disabled
}
Or regexp
if (preg_match('/^(1|yes|on|true)$/i', ini_get('display_errors')) {
// is enabled
} else {
// is disabled
}
You can get the string representation of the values through ini_get(), values that display_errors can be set to is either, true\false, 0\1 and On\Off. But when user's set their php.ini it is more common to use 1 or On
if (ini_get('display_errors') == "1") {
// show debug info
}
or to check for ALL cases, you can perform a switch-case
ini_set('display_errors', 1);
switch (ini_get('display_errors')) {
case "1":
case "On":
case "true":
// show debug info
}
If you prefer the equality comparison approach, notice that ini_get returns a String value of 1, if you test the returned value with ini_get using the == with the int value 1, it becomes true. If you use the === it checks if both are equal and of the same type. String is not the same type as int so it would return false.
1 == "1"; // in PHP, this returns true, it doesn't check the type.
1 === "1"; // would be false, this however checks the type.
Using ini_get('display_errors') you can check against values like, TRUE, FALSE, and
even NULL. They will return a boolean value of either 0 which is false and anything other than 0 evaluates to true.
if (2) {
echo "2 is true!"; // echos "2 is true!"
}
I saw your comment about a discrepancy so I decided to test it myself, here is what I used
<?php
ini_set('display_errors', 1);
$verbose = ini_get('display_errors');
echo $verbose; // echo's 1
// just to test its return values.
if ($verbose) {
echo "verbose is true"; // echos "verbose is true"
}
ini_set('display_errors', 0);
$verbose = ini_get('display_errors');
echo $verbose; // echo's 0
if ($verbose) {
echo "verbose is not true"; // does not get evaluated
}
?>
This answer is a bit lengthy, but I hope this is what you need.
Use filter_var
if ( filter_var( ini_get('display_errors'), FILTER_VALIDATE_BOOLEAN) ){
}
And that should catch all of the different ways display_errors could get turned on ("1", "true", "on", "yes", etc.).
I also can't find any official documentation on this, but from what I've experienced, I believe using filter_var with the FILTER_VALIDATE_BOOLEAN flag will cover the full gamut of possible ways an ini setting can be set to true/false.
The default is '1' according to the documentation. However, you might want to check the inverse, that it isn't off:
!= FALSE or !empty()
if (ini_get('display_errors') != FALSE))
{
// show debug info
}
else
{
// show just "oops!"
}
Or as Anthony pointed out, you could just check for 1
if(ini_get('display_errors') == 1))
You might also want to check error_reporting, as it is another common setting that is used to control the displaying of errors, although its meaning is slightly different than display_errors
if(error_reporting() != 0)