Using Google Places API with MonoTouch? - ios

I know it's possible to use the Google Places API with MonoTouch, but I'm having trouble getting it to work. I have the properly formated URL with my API key and all, but could someone please provide me with some example code of how to get and use the response from the request url?
(ex: https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AddYourOwnKeyHere)

I ended up using the code below, it gives me a JsonArray of JsonObjects that I can iterate through and use. For this example it's for a places textsearch not a standard places search.
HttpWebRequest url = (HttpWebRequest)WebRequest.Create("https://maps.googleapis.com/maps/api/place/textsearch/json? query=Sushi&sensor=false&type=restaurant&key=YOUR_KEY_HERE");
HttpWebResponse temp = (HttpWebResponse)url.GetResponse ();
JsonValue jval = JsonObject.Load (temp.GetResponseStream ());
JsonObject jobj = (JsonObject)jval;
var resultJson = jobj["results"];
foreach (JsonObject jentry in resultJson)
{
//Do stuff with the jentry
}

Related

GTLRDrive_File object missing modifiedTime and createdTime properties

I'm working with the Google API Client for REST Swift SDK, and I'm trying to parse out modifiedTime and createdTime from the API response containing GTLRDrive_File objects.
But they don't appear to be there? Here's an example of the payload I'm getting from po file:
GTLRDrive_File 0x60c00084eb20: {
mimeType:"audio/mpeg"
id:"1xt8eqYit3tOrZUeuG9V7_dsq60Iq9xVC"
kind:"drive#file"
name:"Lobo_Loco_-_15_-_Save_the_Bees_ID_817 (2).mp3"
}
What's going on? I wouldn't expect these properties to be optional?
Here's the code I'm using to loop after querying:
if let files = result.files as? [GTLRDrive_File] {
for file in files {
print(file.modifiedTime, file.createdTime)
}
}
(And of course both are nil).
How can I get modified/created dates from a GTLRDrive_File?
Provided the request (file.list, etc) was successful createdTime, modifiedTime which can be found in the Drive File Resource, can be accessed by first accessing 'files' object.
So if you go to Try-it:
Use files(createdTime) as parameter in the 'field' property and it will return those fields. (Use files.list as sample).
In the iOS SDK, simply:
let query = GTLRDriveQuery_FilesList.query()
query.fields = "files(createdTime,modifiedTime)"
will work.

Dealing with DataResponse<Any> in Xcode 8 (Swift)

I am a newbie to iOS and I am using alamofire. When i call the API the result is successfully getting printed to console as shown
What I want is, to only extract the message from this response and present it to user. How to do it?
I have searched for this but I found content related to converting string to JSON object or JSON object to JSON string. But my response is of type DataResponse<Any> and I don't know exactly how to deal with it.
P.s I am using Xcode 8, Swift 3.
You can try something like this:
if let object = response.result.value as? [String:Any], let message = object["message"] as? String {
print(message) // "User has been successfully registrered"
}
As Rashwan L Answer is perfect !!
Still I am suggesting A better way to do it using ObjectMapper
It is very easy to access each property easily
First You need to Download SwiftyJSONAccelerator application in your system which let you convert your JSON Response to Class or struct whatever you need.
From
https://github.com/insanoid/SwiftyJSONAccelerator
And Create Class for your JSON, And Select ObjectMapper if you are not using SwiftyJosn from drop down Where there are three options.
Drag and drop all generated class file to your XCode make sure you select Copy Item if needed Check box Selected
How to use ?
import ObjectMapper
WebServices().getMyWSResponse(success: { (response) in
guard let res = response as? [String:Any], let obect = Mapper<MYGeneratedModelClass>().map(JSON: res) else {
return
}
//Here you get obect , You can access object.message
}, error: { (error) in
})
}
Note: WebServices().getMyWSResponse is My Class to call ws you don't need to worry about that
Hope it is helpful to you

parse string and send as Json in swift

I have real big problem finding the right code which helps me to parse String to JSON and then send to external server. I'm using xCode 6.1, so some ways of parsing won't work for me, like SwiftyJSON.
On internet i only can find the way to send String , but not JSON, or if i found something it won't work.
I'm beginner in iOS and it would really help me if someone can explain me how to do it.
Thank you a lot.
If you have JSON String convert to NSData object.Check the data object before sending to an external server if data is valid JSON format or not by using NSJSONSerialization.I am giving sample code to how can check JSON Data valid or not.
suppose you String is like this,
let jsonString = "{\"device\":\"iPhone 6\",\"OS\":\"iOS 9\",\"name\":\"Apple\"}"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
do {
let responseData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if responseData != nil { // valid JSON
//Now pass data object to server
}
} catch {
NSLog("ERROR when parse JSON")
}

NSURLSession CreateUploadTask failure with xamarin iOS

I am trying to upload an object to my WebAPI using the NSURLSession to perform this in the background. My Web API is operational - my problem is that the client code gets to the CreateUploadTask() method and then just throws an exception. It is a null exception and there is nothing in the Output window either. So there is literally nothing to indicate what the problem is. The code I use to initiate is here;
private NSUrlSessionConfiguration configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration ("com.SimpleBackgroundTransfer.BackgroundSession");
private NSUrlSession session;
public void SendBackgroundMessage(AppMessage m)
{
session = NSUrlSession.FromConfiguration(configuration, new UploadDelegate(), new NSOperationQueue());
NSUrl uploadHandleUrl = NSUrl.FromString(Constants.ApiUrl + "api/AppMessage/Send");
NSMutableUrlRequest request = new NSMutableUrlRequest(uploadHandleUrl);
request.HttpMethod = "POST";
request["Content-Type"] = "application/json";
var keys = new object[] { "Authorization" };
var objects = new object[] { _accessToken };
var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys);
request.Headers = dictionary;
string json = JsonConvert.SerializeObject(m);
var body = NSData.FromString(json);
var uploadTask = session.CreateUploadTask(request, body);
uploadTask.Resume();
}
I suspect it is something to do with the way I am serializing to json and creating the NSData object. Any pointers on this would be greatly appriciated!
EDIT: Ok so if i remove the body parameter the upload task creates fine. It is something to do with the way I am composing the json.
This was resolved by saving the json string to disk first. Then using it in the upload task, like this;
string json = JsonConvert.SerializeObject(m);
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, m.AppMessageId.ToString());
File.WriteAllText(filename, json);
var uploadTask = session.CreateUploadTask(request, NSUrl.FromFilename(filename));
You can configure XS debugger to stop on all exceptions. Quote from forums:
Use the "Run -> New Breakpoint" menu, or the "New Breakpoint" button
in the Breakpoint Pad, and set the new breakpoint to break "When an
exception ins thrown".
Once it hit that exception-breakpoint the NullReferenceException, like most .NET exceptions, should give you extra details including the stack trace which should include the line number where it occurred.

sending accessToken to server using swift ios

I am trying to use facebook ios login sdk. I get the access Token using below code. Now i want to send this token to a server so that server can validate this token by making a call to facebook server.
I am using the below code to get the accessToken , i am using swift in ios 8.
var accessToken = FBSession.activeSession().accessTokenData
When i am trying to send this token to server getting an error saying that type of accessToken is not convertible to NSString.
Please help me where i am wrong.
First, make sure that you have an open session. I use this approach in my AppDelegate:
FBSession.openActiveSessionWithAllowLoginUI(false)
Second, you can get accessToken as a string from accessTokenData:
var myToken = FBSession.activeSession().accessTokenData.accessToken
From there, you can send it to your server however you want. I tried a couple request wrappers until I settled on Net. Getting your token to your server is pretty easy if you have a library like Net so that you don't have to handle the low level network request interfaces:
func doLogin() -> Void {
let net = Net(baseUrlString: "http://myhost.com/")
let url = "auth/facebook_access_token"
let params = ["access_token": myToken]
net.GET(url, params: params, successHandler: { responseData in
let result = responseData.json(error: nil)
// Do something with whatever you got back
NSLog("result \(result)")
}, failureHandler: { error in
NSLog("Error")
})
}
Good luck! I hope I was able to help!

Resources