GTLRDrive_File object missing modifiedTime and createdTime properties - ios

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.

Related

How to access a specific field from Cloud FireStore Firebase in Swift

Here is my data structure:
I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.
There is no API that fetches just a single field from a document with any of the web or mobile client SDKs. Entire documents are always fetched when you use getDocument(). This implies that there is also no way to use security rules to protect a single field in a document differently than the others.
If you are trying to minimize the amount of data that comes across the wire, you can put that lone field in its own document in a subcollection of the main doc, and you can request that one document individually.
See also this thread of discussion.
It is possible with server SDKs using methods like select(), but you would obviously need to be writing code on a backend and calling that from your client app.
This is actually quite simple and very much achievable using the built in firebase api.
let docRef = db.collection("users").document(name)
docRef.getDocument(source: .cache) { (document, error) in
if let document = document {
let property = document.get(field)
} else {
print("Document does not exist in cache")
}
}
There is actually a way, use this sample code provided by Firebase itself
let docRef = db.collection("cities").document("SF")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let property = document.get('fieldname')
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
I guess I'm late but after some extensive research, there is a way in which we can fetch specific fields from firestore. We can use the select keyword, your query would be somthing like (I'm using a collection for a generalized approach):
const result = await firebase.database().collection('Users').select('name').get();
Where we can access the result.docs to further retrieved the returned filtered result. Thanks!
//this is code for javascript
var docRef = db.collection("users").doc("ID");
docRef.get().then(function(doc) {
if (doc.exists) {
//gives full object of user
console.log("Document data:", doc.data());
//gives specific field
var name=doc.get('name');
console.log(name);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});

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

How do I store private app data on Google Drive with my iOS app?

I have an iOS app that has a local database. I'd like to back that up for users who choose to sign in with Google. The web (https://developers.google.com/drive/web/appdata) and android (https://developers.google.com/drive/android/appfolder) have guides on how to do this, but I can't find a similar one for iOS. Does it exist?
If you already have code to upload a file to the user's Drive account, it is very easy to switch to uploading into the private app folder instead. When making the Files.insert call, the file will be added to all of the folders listed in the parents[] array. (If this array is empty, by default the file is added to the root folder.) To upload the file into the private app data folder, simply set the parents[] array to appfolder. You have to do this at the same time as uploading the file, because once it has been uploaded the file can't be moved between the user's drive and your app's private data folder.
(Note: you may need to use the regular REST API to do this, because Google's Drive API for iOS docs do not show any methods for actually uploading a new file to Drive.)
Check this how this is working for me in swift 4.2 and above:
let googleDrive: GTLRDrive_File = GTLRDrive_File()
googleDrive.name = "name.json"
googleDrive.parents = ["appDataFolder"]
let uploadParam: GTLRUploadParameters = GTLRUploadParameters(data: data, mimeType: "application/json")
uploadParameters.shouldUploadWithSingleRequest = true;
let queryDrive: GTLRDriveQuery_FilesCreate = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParam)
queryDrive.fields = "id"
self.service.executeQuery(queryDrive) { (result, response, error) in
if let file = response as? GTLRDrive_File {
if (error == nil) {
print(file.identifier)
/// your code here
} else {
// handle error part
}
}
else {
//handle exception part
}
}
"data" the json data you get this like below
let param = [["key": "value"], ["key": "value"], ["key": "value"]]
let data = try JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)

Checking metadata of Amazon S3 file using iOS AWS SDK in Swift

I am using the AWS iOS SDK v2, and Swift 1.2.
I am storing my app's app.json file on S3 and want to check it at launch to see if it's been updated since the last run. According to research, simply doing a HEAD request on the object should return the "Last-Modified" attribute which can then be compared to the previous.
The problem is that doing a HEAD request on an Object doesn't really seem to be well documented. I've got the following:
var metaDataRequest = AWSS3HeadObjectRequest()
metaDataRequest.bucket = S3BucketName
metaDataRequest.key = S3AppJSONKey
This seems like a decent start, however I cannot find a way to execute the request. The AWSS3TransferManager has a download() method, but the method requires an AWSS3TransferManagerDownloadRequest type, which an AWSS3HeadObjectRequest cannot be cast as.
Not sure where to go from here, short of just doing the request outside of the SDK. I did, however, want to leverage as much of the SDK as possible, so if this is possible I would love to know how.
You need to use AWSS3 (instead of AWSS3TransferManager) to call - headObject:.
You need to call headobject method of AWSS3
var request = AWSS3HeadObjectRequest()
request.bucket = "flkasdhflhad"
request.key = "hfsdahfjkhadjkshf"
request.ifModifiedSince = NSDate()
var s3 = AWSS3.defaultS3()
s3.headObject(request) { ( output1 : AWSS3HeadObjectOutput?, error : NSError?) -> Void in
print( output1?.description())
}
if your object is modified from specified date then it will return u the object otherwise it will return u the status code 304.
You can use following Swift 2.2 method to check if file exist or not
func checkIfFileExist() {
let s3 = AWSS3.defaultS3()
let headObjectsRequest = AWSS3HeadObjectRequest()
headObjectsRequest.bucket = "YourBucketName" //Don't add "/" at end of your bucket Name
headObjectsRequest.key = "YourFileNameYouWantToCheckFor" //Don't add "/" in start of file name
s3.headObject(headObjectsRequest).continueWithBlock { (task) -> AnyObject! in
if let error = task.error {
print("Error to find file: \(error)")
} else {
print("fileExist")
}
}
}
Note: Example to set bucket and key
suppose you have bucket named "ABC" and than folder named "XYZ" and than inside "XYZ" you have file "abc123"
than write
headObjectsRequest.bucket = "ABC/XYZ"
and
headObjectsRequest.key = "abc123"
and if you want to check for the entire folder
than use
headObjectsRequest.bucket = "ABC/XYZ"
and
headObjectsRequest.key = ""
Thanks Mohsin

Using Google Places API with MonoTouch?

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
}

Resources