How to download file from dropbox using Dropbox Sync API iOS SDK - iphone

I am using Dropbox Sync API sdk it display all folder and file but we can not download file
i am using this code:
DBFilesystem *filesystem;
DBFile *file = [_filesystem openFile:info.path error:nil];
NSData *imagedata=[file readData:nil];
[fileMan createFileAtPath:Image_filePath contents:**data** attributes:nil];
NSLog(#"flao=%d",[file writeData:imagedata error:nil]);
// it return 1
I am getting NSData but i can't store in document directory.
I check below links but no success
Dropbox Sync API iOS copy files to app documents
Data syncing with DropBox API and iOS
Please Help me.

Dropbox takes time to cache a file, you can set up a block to monitor when the cache is completed:
__block MyViewController *me = self;
[self.dropboxFile addObserver:self block:^() { [me monitorDropboxFile:#"Sync"]; }];
inside the observer:
- (void)monitorDropboxFile:(NSString *)caller
{
if (self.dropboxFile.status.cached) {
; // Good to go, the file is cached
} else {
; // download in progress
}
}
Or, there is a simpler way, use readHandle:
(DBFile *)file;
// ...
DBError *dbError;
NSFileHandle *fileHandle = [file readHandle:&dbError];
As documented in the Dropbox API header:
/** Returns a read-only file handle for the file. If the file is not
cached then the method will block until the file is downloaded.
#return A file handle if the file can be read, or nil if an error
occurred. */
The file handle is ready when returned. However, you might like to put readHandle in a background thread if the app has to be responsive during file download.

Related

FileSystemException: Cannot open file, path = 'storage/emulated/0/DCIM/docs/myPdf.pdf' (OS Error: Operation not permitted, errno = 1)

I am trying to create a pdf document and write my data in that file. The data is a list of int or uint type. Able to do the same for images but not pdf or doc file. All permissions are given and it works for images. My code is below -
Future <File> createDocFile(Uint8List fileData, String type) async
{
File file = new File(".pdf");
if(await PermissionHandler.checkPermission(Permission.storage)!=true){
Url.toastShow("Storage permission not found.");
await Permission.storage.request();
}
else {
await file.writeAsBytes(fileData);
print("PDF SAVED IN DEVICE");
Url.toastShow("PDF saved in device",Colors.green);
}
}
Whenever you create a new file the device can't automatically find it. You'd have to manually tell the device to refresh for the files. Before you'd have to refresh all the files in the device for it to get updated which was very inefficient, but now you could just send the path of the file that you want to get updated. You can use the media_scanner plugin to do so.
Or If you wanna do it yourself with kotlin then here's the code,
private fun broadcastFileUpdate(path: String){
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(File(path))))
}

not able to download file with size more than 63kb using UnityWebRequest

i am try to download asset bundle from an url but the request keep on cancelling after downloading 63kb. Can anyone explain to me why this may be happening?
My Code :
public IEnumerator DL()
{
string downloadlink = "https://drive.google.com/file/d/1OGyrB4-MQfo-HVom9ENvV4dn312_wL4Q/view?usp=sharing";
string filepath = Application.persistentDataPath + "/electroplatingNN";
//Download
UnityWebRequest dlreq = new UnityWebRequest(downloadlink);
dlreq.downloadHandler = new DownloadHandlerFile(filepath);
dlreq.timeout = 15;
UnityWebRequestAsyncOperation op = dlreq.SendWebRequest();
while (!op.isDone)
{
//here you can see download progress
Debug.Log(dlreq.downloadedBytes / 1000 + "KB");
yield return null;
}
if (dlreq.isNetworkError || dlreq.isHttpError)
{
Debug.Log(dlreq.error);
}
else
{
Debug.Log("download success");
}
dlreq.Dispose();
yield return null;
}
As already mentioned in the comments the issue is not in the UnityWebrequest but rather Google Drive doesn't simply download your file as you expect.
Instead the data you download is actually only the web page which would allow you to download it. If I simply open your file in a browser I get a page looking like this
where I now could download your file.
There are packages like this or this which implement the necessary stuff for actually download files from Google Drive API in Unity.

Download and use of target dataset with Vuforia

I'm downloading a specific targets.xml file and I want to access this file to use with the Vuforia SDK. The file is downloaded to the Documents Directory of the app as follow:
if fileManager.fileExists(atPath: destinationURLForFile.path){
}
else{
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
}catch{
print("An error occurred while moving file to destination url")
}
}
Now I want to access this file to use with Vuforia. I know this should be done by using STORAGE_ABSOLUTE in the load function.
// Load the data set from the app's resources location
if (!dataSet->load([dataFile cStringUsingEncoding:NSASCIIStringEncoding], Vuforia::
STORAGE_ABSOLUTE)) {
NSLog(#"ERROR: failed to load data set");
objectTracker->destroyDataSet(dataSet);
dataSet = NULL;
ret = NO;
} else {
// Activate the data set
if (objectTracker->activateDataSet(dataSet)) {
NSLog(#"INFO: successfully activated data set");
}
else {
NSLog(#"ERROR: failed to activate data set");
ret = NO;
}
}
But I get the error beneath, I named the xml file, 'targets'. Maybe you guys know something I forgot?
2017-01-31 20:12:39.262178 VidPlayback[243:5487] ERROR/AR(243)
2017-01-32 20:12:39: Failed to load dataset 'targets.xml'.
2017-01-31 20:12:39.262191 VidPlayback[243:5487] ERROR: failed to load data set
Edit: fixed it!
Used this link: https://developer.vuforia.com/forum/qcar-api/remote-dataset-ios-sdk
Change the default code in the loadAndActivateImageTrackerDataSet function:
if (!dataSet->load([dataFile cStringUsingEncoding:NSASCIIStringEncoding], Vuforia::
STORAGE_ABSOLUTE))
with this:
NSString *fullPath = [NSString stringWithFormat:#"%#/Documents/%#", NSHomeDirectory(), dataFile];
// Load the data set from the app's resources location
if (!dataSet->load([fullPath cStringUsingEncoding:NSASCIIStringEncoding], Vuforia::STORAGE_ABSOLUTE)){

Accessing GTLPlusActivity properties

I have integrated the Google Plus iOS SDK v1.2.1 into my iOS app. After authentication I am trying to fetch the user's activity feed. My code is the following:
GTLServicePlus* plusService = [[GTLServicePlus alloc] init];
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
plusService.retryEnabled = YES;
GTLQueryPlus *query = [GTLQueryPlus queryForActivitiesListWithUserId:#"me" collection:kGTLPlusCollectionPublic];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusActivityFeed *data,
NSError *error) {
for (GTLPlusActivity *activity in data.items) {
// ITERATE THROUGH THE ACTIVITIES
NSString *publishedDate = activity.published; <---- ERROR
// "PROPERTY 'published' CANNOT BE FOUND
// IN FORWARD CLASS OBJECT "GTLPLusActivity""
// WHY ARE THE VARIABLES SUCH AS published, placeName,
// title, actor etc NOT ACCESSIBLE
}
}];
I am able to successfully retrieve the posts of the user. The GTLPlusActivity class has many properties as shown in the image:
Whenever I try to access the properties using the "." operator such as "activity.actor" in the for loop, it gives the error "Property 'actor' cannot be found in forward class object 'GTLPlusActivity'". Why am I unable to access the properties? I need to display them in a UITableView.
EDIT: Code Snapshot. Error clearly displayed in Red.
Firstly, check the error condition and make sure the error code is nil. I have tried your code, and it works correctly on my end, so most likely, there is a problem with the response you are getting back. Generally activity.actor will return a GTLPlusActivityActor.
Try something like:
if (error) {
NSLog(#"Status: Error: %#", error);
}
else
<Do stuff>
EDIT: Also, our iOS quick-start is a great resource for seeing how we handle certain parts of the code. The ListMoments bit is pretty similar to dealing with Activities.
https://developers.google.com/+/quickstart/ios
EDIT 2: Also, make sure you have all of the right imports. Try
#import "GTLPlusActivity.h"
or
#import "GTLPlus.h"

How to use Three20 framework to upload multiple images and handle JSON response?

So I have an iPhone application that needs to:
Post several strings and up to 5 images (stored in memory) to a RoR web application
Parse the JSON returned that will include several strings and an array of URLs (each representing the location of where the uploaded images can be found on the website).
QUESTIONS:
Can this be done with Three20 (would be nice since I'm using it for other things)? And if so, how?
If it can't be done with Three20 ... how would it be accomplished using ASIHttpRequest? Or maybe something baked into the SDK if that is a better option?
Thanks much
Unfortunately there isn't a whole lot of tutorials and good documentation for three20 out there on the web ... so here is how I finally got things working:
- (void) sendToWebsite {
NSString* url = [[NSString stringWithFormat:kRequestURLPath, self.entityId] stringByAppendingString:#".json"] ;
// Prep. the request
TTURLRequest* request = [TTURLRequest requestWithURL: url delegate: self];
request.httpMethod = #"POST";
request.cachePolicy = TTURLRequestCachePolicyNoCache;
// Response will be JSON ... BUT WHY DO I NEED TO DO THIS HERE???
request.response = [[[TTURLJSONResponse alloc] init] autorelease];
// Set a header value
[request setValue:[[UIDevice currentDevice] uniqueIdentifier] forHTTPHeaderField:#"Device-UID"];
// Post a string
[request.parameters setObject:self.entity_title forKey:#"entity_title"];
// Post some images
for (int i = 0; i < [self.photos count]; i++) {
// IS IT POSSIBLE TO ADD A PARAM NAME SO I CAN LOOK FOR THE SAME NAME
// IN THE WEB APPLICATION REGARDLESS OF FILENAME???
[request addFile:UIImagePNGRepresentation([self.winnerImages objectAtIndex:i])
mimeType:#"image/png"
fileName:[NSString stringWithFormat:#"photo_%i.png", i]];
}
// You rails guys will know what this is for
[request.parameters setObject:#"put" forKey:#"_method"];
// Send the request
[request sendSynchronously];
}
Things I still don't understand (or find problematic):
For a posted file, how can I include both a param name AND a filename?
What is the purpose of setting request.response = to whatever? I don't get that.
Answering #2:
You need to supply the handler for the response before you send your request, the TTURLJSONResponse is not the actual response, but it's responsible for handling the response. This is where you'd process the response for your strings and array of URLs.
It's really a protocol called TTURLResponse that defines the following method for implementation:
/**
* Processes the data from a successful request and determines if it is valid.
*
* If the data is not valid, return an error. The data will not be cached if there is an error.
*
* #param request The request this response is bound to.
* #param response The response object, useful for getting the status code.
* #param data The data received from the TTURLRequest.
* #return NSError if there was an error parsing the data. nil otherwise.
*
* #required
*/
- (NSError*)request:(TTURLRequest*)request
processResponse:(NSHTTPURLResponse*)response
data:(id)data;
You chose TTURLJSONResponse as your handler, which is a straight-forward implementation to look at for help on writing your own.