iOSparsing如何通过URL下载文件

我正在使用我的聊天应用程序parsing。 当我上传文件时,我保留了url,并将url发送给其他用户,然后他们可以通过这个URL下载文件。

这是我上传文件的代码:

+ (void)uploadBlob:(NSData *)blob fileName:(NSString *)fileName type:(NSString *)type { if ([self private_checkCloudForbidden]) { return; } if (CHOSEN_SERVER_DATABASE == ServersQuickBlox) { if ([Format isThumbnailWithBlobFileName:fileName]) { type = @"image"; } NSString *qbContentType = @""; if ([type isEqualToString:@"image"]) { qbContentType = @"image/jpg"; } [QBContent TUploadFile:blob fileName:fileName contentType:qbContentType isPublic:YES delegate:[CloudDelegate sharedInstance]]; } else if (CHOSEN_SERVER_DATABASE == ServersParse) { PFFile *file = [PFFile fileWithName:fileName data:blob]; [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) { if (error){ NSLog(@"Error: %@", [[error userInfo] objectForKey:@"error"]); } else { [CloudHandler didUploadBlobWithFileName:file.name blobID:file.url]; } }]; } } 

在CloudHandler didUploadBlobWithFileName方法中,我将把文件的url保存为blobID。 这里是我使用QuickBlox时如何通过blobID / url下载文件:

 + (void)downloadWithBlobId: (NSString *)blobID { if ([self private_checkCloudForbidden]) { return; } if (CHOSEN_SERVER_DATABASE == ServersQuickBlox) { [QBContent TDownloadFileWithBlobID:blobID.integerValue delegate:[CloudDelegate sharedInstance]]; } else if (CHOSEN_SERVER_DATABASE == ServersParse) { //TODO: HOW TO DOWNLOAD FILES? } } 

我没有find通过URL下载文件的API。 (这有点奇怪,如果parsing确实提供无用的url或blobID

编辑:

我不使用“文件”types的属性的原因:

 1. I can't store 'file' on local database. It has to be the blobID or URL. 2. when I send a rich message, I can send along the blobID, so that the receiver does not have to fetch the object first before downloading the binary. 

您应该传输PFObject而不是url。 喜欢这个:

 PFObject *object; //the object you have PFFile *soundFile = object[@"file"]; [soundFile getDataInBackgroundWithBlock:^(NSData *soundData, NSError *error) { if (!error) { [self saveSoundFileToDocuments:soundData fileName:object[@"fileName"]]; } } progressBlock:^(int percentDone) { }]; - (void)saveSoundFileToDocuments:(NSData *)soundData fileName:(NSString *)fileName { NSString *docsDir; NSArray *dirPaths; dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0]; NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:[DataAcesss encryptText:fileName]]]; [soundData writeToFile:databasePath atomically:YES]; } 

这样你可以下载文件并且有文件名。

随UIKit提供的用于从URL检索数据的API是asynchronous的,以便使UI响应。 它使用接口NSURLConnectionDelegate。 您应该实现该接口以便asynchronous接收数据。 首先你从这个URL初始化检索:

 NSURLRequest *theRequest=[NSURLRequest requestWithURL:anUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:CONNECTION_TIMEOUT]; // create the connection with the request // and start loading the data urlConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (urlConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. self.receivedData = [NSMutableData data]; } else { // Inform the user that the connection failed. NSLog(@"Failed to create connection to URL: %@.", anUrl); } 

这里包含这个代码的类被设置为委托,所以这个类应该声明为实现指定的接口:

 @interface MyClass : NSObject <NSURLConnectionDelegate> { } // URLConnection Delegate - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse; 

目前我的实现如下所示:

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // This method is called when the server has determined that it // has enough information to create the NSURLResponse. // It can be called multiple times, for example in the case of a // redirect, so each time we reset the data. // receivedData is an instance variable declared elsewhere. [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Append the new data to receivedData. // receivedData is an instance variable declared elsewhere. [receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // Do error handling here NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); // Now process the received data accumulated in receivedData. } -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { return cachedResponse; } 

这应该让你去。

PFFile对象不包含用于下载的方法,因为它是在iOS SDK的function中构build的。 或者你可以使用AFNetworking作为替代。 我认为下载文件最简单的方法是使用NSData的同步构造函数和GCD一起使用:

 dispatch_async(dispatch_get_global_queue(0), ^(){ NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:file.url]]; dispath_async(dispatch_get_main_queue(), ^(){ // do you main UI thread stuff here }); });