Downloading Files from Kinvey in iOS - ios

I have read documents over kinvey here:
http://devcenter.kinvey.com/ios/guides/files#DownloadingtoCachesDirectory
They have provided sample function as well:
[KCSFileStore downloadData:#"myId" completionBlock:^(NSArray *downloadedResources, NSError *error) {
if (error == nil) {
KCSFile* file = downloadedResources[0];
NSData* fileData = file.data;
id outputObject = nil;
if ([file.mimeType hasPrefix:#"text"]) {
outputObject = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
} else if ([file.mimeType hasPrefix:#"image"]) {
outputObject = [UIImage imageWithData:fileData];
}
NSLog(#"downloaded: %#", outputObject);
} else {
NSLog(#"Got an error: %#", error);
}
} progressBlock:nil];
But when i replaced "myId" with file id it gave me this error:
Error Domain=KCSServerErrorDomain Code=401 "The credentials used to authenticate this request are not authorized to run this operation. Please retry your request with appropriate credentials"
While i can access other collections i have created over kinvey (same user) with same credentials (secret,api_key)
Is there any other requirement before calling this function?
Thanks

I had the same problem. I reached out and got help from the kinvey support team.
I solved the problem by setting the "acl" for each file that I upload. According to the iOS Files guide under upload options: "By default the file will only be available to the creating user.", this was what was causing the problem for me.
I upload files like this now:
let metadata = KCSMetadata()
metadata.setGloballyReadable(true)
let data = UIImagePNGRepresentation(image)
KCSFileStore.uploadData(
data,
options: options: [KCSFileACL : metadata],
completionBlock: {KCSFileUploadCompletionBlock!},
progressBlock: nil)
This allows anyuser to read that specific file. I Use a KCSUser.createAutogeneratedUser() to read the files afterwards.
Yes, you will have access to other collections under the same kinvey app, but the permissions needs to be set for the files collection. So the file you describe as "myId" needs to have the proper permissions set, before it can be downloaded by another user than the user that upload the file.

You must be an active user for calling this function. You just need to make sure you have successfully logged in.

Related

GTLRDriveQuery_FilesCreate (Google REST API)

1.I need to create a folder in google drive.And I use this code to do this(official code from google developers page):
GTLRDrive_File *metadata = [GTLRDrive_File object];
metadata.name = #"Invoices";
metadata.mimeType = #"application/vnd.google-apps.folder";
GTLRDriveQuery_FilesCreate *query = [GTLRDriveQuery_FilesCreate queryWithObject:metadata
uploadParameters:nil];
query.fields = #"id";
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
GTLRDrive_File *file,
NSError *error) {
if (error == nil) {
NSLog(#"File ID %#", file.identifier);
} else {
NSLog(#"An error occurred: %#", error);
}
}];
And the folder creates fine!
The problem is that each time I run the App , the code creates dublicates of the folder in my Google Drive.But I need to create only one folder of that name and kind.
I know its a rookie question, but I cannot figure it out how to do this.And I know that I should compare( GTLRDrive_File *file) identifier (as it is a unique string),but how do I do it?
2.So the question is :How do check if the identifier is already created and compare it ?
I understand that to fulfil my tsk I should check if the Identifier is exists,if not I should create it, and if its doesn't exist do nothing.
The Google Drive API does allow multiple files with duplicate names. File/folder names are not unique, but identifiers are.
What you likely want to do is:
Check if a folder with the same name exists
If not, then create the folder
If it already exists, then use the identifier of the existing folder.
How to check if a folder exists. This is swift, but it's trivial to convert it to ObjC
func getFolderID(name: String, completion: #escaping (String?) -> Void) {
let query = GTLRDriveQuery_FilesList.query()
// Add "and '\(self.user.profile!.email!)' in owners" to only list folders owned by a specific GIDGoogleUser.
query.q = "mimeType = 'application/vnd.google-apps.folder' and name = '\(name)'"
driveService.executeQuery(query) { (_, queryResults, error) in
if let error = error {
fatalError(error.localizedDescription)
}
let fileList = queryResults as! GTLRDrive_FileList
completion(fileList.files?.first?.identifier)
}
}
And then you'd call getFolderID in this manner:
getFolderID(name: "my-folder-name") { (folderID) in
if let folderID = folderID {
print("Found folder with ID: \(folderID)")
} else {
print("Folder does not exist")
}
}
File name search is case insensitive.
The simplest way is to do a files.get of the id. It will return status 200 and the file object if it's there, or 404 not found.

Swift 3 Azure Blob Storage Data (Image, Video) upload with SAS

I'm searching for an useful Swift 3 Azure Blob Storage example which I could use to upload some data(image, video). For now, I can insert records into my Mobile Service database and there I generate a SAS and I get it back to my iOS application. Now I need to know how to upload to Azure Blob Storage with help of that SAS. I successfully implemented the same for Android and it works, but somehow I have troubles to find any useful information for "SWIFT" and how to use the "SAS"!
Any code examples how to upload with SAS in Swift are much appreciated.
Regards,
Adam
For those who have the same problem as I had: This is a working example in Xcode 8 and Swift 3. You have to include the "Azure Storage Client Library" into your project.
//Upload to Azure Blob Storage with help of SAS
func uploadBlobSAS(container: String, sas: String, blockname: String, fromfile: String ){
// If using a SAS token, fill it in here. If using Shared Key access, comment out the following line.
var containerURL = "https://yourblobstorage.blob.core.windows.net/\(container)\(sas)" //here we have to append sas string: + sas
print("containerURL with SAS: \(containerURL) ")
var container : AZSCloudBlobContainer
var error: NSError?
container = AZSCloudBlobContainer(url: NSURL(string: containerURL)! as URL, error: &error)
if ((error) != nil) {
print("Error in creating blob container object. Error code = %ld, error domain = %#, error userinfo = %#", error!.code, error!.domain, error!.userInfo);
}
else {
let blob = container.blockBlobReference(fromName: blockname)
blob.uploadFromFile(withPath: fromfile, completionHandler: {(NSError) -> Void in
NSLog("Ok, uploaded !")
})
}
}

SoundCloud API iOS Fails to upload audio with a HTTP 422 error

I'm trying to put a super basic Soundcloud feature in my app to upload single .wav files using their UI. I followed their guide and I didn't really need anything outside of the bare bones share menu so I assumed this code would work:
NSURL *trackURL = [[NSURL alloc] initWithString:[docsDir stringByAppendingPathComponent:fileToShare]];
SCShareViewController *shareViewController;
shareViewController = [SCShareViewController shareViewControllerWithFileURL:trackURL
completionHandler:^(NSDictionary *trackInfo, NSError *error){
if (SC_CANCELED(error)) {
NSLog(#"Canceled!");
} else if (error) {
NSLog(#"Ooops, something went wrong: %#", [error localizedDescription
]);
} else {
// If you want to do something with the uploaded
// track this is the right place for that.
NSLog(#"Uploaded track: %#", trackInfo);
}
}];
// If your app is a registered foursquare app, you can set the client id and secret.
// The user will then see a place picker where a location can be selected.
// If you don't set them, the user sees a plain plain text filed for the place.
[shareViewController setFoursquareClientID:#"<foursquare client id>"
clientSecret:#"<foursquare client secret>"];
// We can preset the title ...
[shareViewController setTitle:#"Funny sounds"];
// ... and other options like the private flag.
[shareViewController setPrivate:NO];
// Now present the share view controller.
[self presentModalViewController:shareViewController animated:YES];
[trackURL release];
However I get an HTTP 422 error with this appearing in my debug console:
2016-02-29 11:04:47.129 synthQ[801:443840] parameters: {
"track[asset_data]" = "/var/mobile/Containers/Data/Application/EE58E5CA-B30C-44EB-B207-EB3368263319/Documents/bb.wav";
"track[downloadable]" = 1;
"track[post_to][]" = "";
"track[sharing]" = public;
"track[tag_list]" = "\"soundcloud:source=synthQ\"";
"track[title]" = "Funny sounds";
"track[track_type]" = recording;
}
2016-02-29 11:04:47.164 synthQ[801:444011] -[NXOAuth2PostBodyStream open] Stream has been reopened after close
2016-02-29 11:04:47.373 synthQ[801:443840] Upload failed with error: HTTP Error: 422 Error Domain=NXOAuth2HTTPErrorDomain Code=422 "HTTP Error: 422" UserInfo={NSLocalizedDescription=HTTP Error: 422}
Does anyone have any ideas what could be going wrong here?
Thanks!
One of the reason to get HTTP 422 error in SoundCloud is:
If you are trying to upload a file for a first time with a new account, you need to verify your email address to complete your SoundCloud registration in order to upload your files.
There might be other reasons for this error, however for my case it was the case and that solved the problem.
You cannot reference external resources while uploading tracks. You
therefor need to download the track to your computer and then perform
the actual upload to SoundCloud.
Source
Soundcloud file uploading issue HTTP 442
I managed to solve this by using a different constructor that passes the audio file as an NSData object:
shareViewController = [SCShareViewController shareViewControllerWithFileData:[NSData dataWithContentsOfFile:[docsDir stringByAppendingPathComponent:fileToShare]]
completionHandler:^(NSDictionary *trackInfo, NSError *error){
if (SC_CANCELED(error)) {
NSLog(#"Canceled!");
} else if (error) {
NSLog(#"Ooops, something went wrong: %#", [error localizedDescription
]);
} else {
// If you want to do something with the uploaded
// track this is the right place for that.
NSLog(#"Uploaded track: %#", trackInfo);
}
}];

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)

How do I create a test user for a native iOS app?

I'm trying to test my native iOS app and I've been having huge problems with test users. Basically it seems that the normal graph based way of creating test users doesn't work for native apps. When I try I get the following response from the server:
{
"error": {
"message": "(#15) This method is not supported for native apps",
"type": "OAuthException",
"code": 15
}
}
This seems to be supported by various posts on SO and a page on the old FB forums:
http://forum.developers.facebook.net/viewtopic.php?id=93086
People say that the only way to create test users for native apps is to create proper fake accounts on FB, which is against FB terms and conditions. Is this really my only option ? I can't believe the FB devs cannot support test accounts for native apps.
Anyone know of any legitimate way to create native app test users ?
At the top of the developer documentation for test users, a GUI for maintaining test users is also mentioned.
In addition to the Graph API functionality described below for managing test users programmatically, there is also a simple GUI in the Developer App, available on your app's Roles page as shown in the screenshots below. It exposes all of the API functions described in this document.
For some reason I don't understand, the Graph API calls aren't available if your app has an 'App Type' (under Settings -> Advanced) of Native/Desktop. But you can use the GUI instead.
You can create a new facebook test user for your app by calling the below function.
Please user your APP ID (go to this link to get your App's ID:https://developers.facebook.com/apps)
Please go to your app on facebook and get the App secret ID
-(void)createNewUser{
NSString *appID=#"Past your App ID"
NSString *appSecret=#"Past your App secret"
NSDictionary *params = #{
#"true": #"installed",
#"access_token": #"appID|appSecret",
};
NSString *path = [NSString stringWithFormat:#"/appID/accounts/test-users"];
/* make the API call */
[FBRequestConnection startWithGraphPath:path
parameters:params
HTTPMethod:#"POST"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
)
{
if (result && !error)
{
NSLog(#"Test-User created successfully: %#", result);
}
else
{
NSLog(#"Error creating test-user: %#", error);
NSLog(#"Result Error: %#", result);
}
}];
}
Please make sure you don't reveal your App secret ID to anyone and never include it in your app hardcoded like that.
Hope it helps
The following works for me using the Facebook iOS SDK v4.1.0:
// Listed as "App ID": https://developers.facebook.com/apps/
NSString *facebookAppId = #"1234_REPLACE_ME_5678";
// Listed as "App Token": https://developers.facebook.com/tools/accesstoken/
NSString *facebookAppToken = #"ABCD_REPLACE_ME_1234";
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"/%#/accounts/test-users",
facebookAppId]
parameters:#{#"installed" : #"true"}
tokenString:facebookAppToken
version:#"v2.3"
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
NSDictionary *testUser,
NSError *facebookError) {
if (facebookError) {
NSLog(#"Error creating test user: %#", facebookError);
} else {
NSLog(#"access_token=%#", testUser[#"access_token"]);
NSLog(#"email=%#", testUser[#"email"]);
NSLog(#"user_id=%#", testUser[#"id"]);
NSLog(#"login_url=%#", testUser[#"login_url"]);
NSLog(#"password=%#", testUser[#"password"]);
}
}];
When successful, the output is then something like this:
access_token=CACQSQXq3KKYeahRightYouDontGetToLookAtMyAccessTokenspBkJJK16FHUPBTCKIauNO8wZDZD
email=aqhndli_huisen_1430877783#tfbnw.net
user_id=1384478845215781
login_url=https://developers.facebook.com/checkpoint/test-user-login/1384478845215781/
password=1644747383820
Swift4 version.
import FBSDKCoreKit
// App Token can be found here: https://developers.facebook.com/tools/accesstoken/
let appToken = "--EDITED--"
let appID = "--EDITED--"
let parameters = ["access_token": appID + "|" + appToken, "name": "Integration Test"]
let path = "/\(appID)/accounts/test-users"
guard let request = FBSDKGraphRequest(graphPath: path, parameters: parameters, httpMethod: "POST") else {
fatalError()
}
request.start { _, response, error in
if let error = error {
// Handle error.
return
}
if let response = response as? [AnyHashable: Any],
let userID = response["id"] as? String,
let token = response["access_token"] as? String,
let email = response["email"] as? String {
// Handle success response.
} else {
// Handle unexpected response.
}
}
You can use Facebook's Test User API https://developers.facebook.com/docs/test_users/ to create test users, just be sure to use the same App id.
Given a APP_ID and APP_SECRET, the following gives us an APP_ACCESS_TOKEN
curl -vv 'https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials'
then we can use the token to create test users:
curl 'https://graph.facebook.com/APP_ID/accounts/test-users?installed=true&name=NEW_USER_NAME&locale=en_US&permissions=read_stream&method=post&access_token=APP_ACCESS_TOKEN
in the response body to this command will the new users' email and password.

Resources