In this method:
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSURL *videoURL = [self videoURLWithData:self.connectionData error:&error];
if (videoURL)
self.moviePlayer.contentURL = videoURL;
else if (self.elFields.count > 0)
[self startVideoInfoRequest];
else
[self finishWithError:error];
}
videoURL is returned as nil and hence, it is going to the error block. Youtube video id that I am using is "5Uls9v1nnss". What seems to be the issue?
the videoURLWithData method which is used to retrieve the videoURL is this :
- (NSURL *) videoURLWithData:(NSData *)data error:(NSError * __autoreleasing *)error
{
NSString *videoQuery = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSStringEncoding queryEncoding = NSUTF8StringEncoding;
NSDictionary *video = DictionaryWithQueryString(videoQuery, queryEncoding);
NSMutableArray *streamQueries = [[video[#"url_encoded_fmt_stream_map"] componentsSeparatedByString:#","] mutableCopy];
[streamQueries addObjectsFromArray:[video[#"adaptive_fmts"] componentsSeparatedByString:#","]];
NSMutableDictionary *streamURLs = [NSMutableDictionary new];
for (NSString *streamQuery in streamQueries)
{
NSDictionary *stream = DictionaryWithQueryString(streamQuery, queryEncoding);
NSString *type = stream[#"type"];
NSString *urlString = stream[#"url"];
if (urlString && [AVURLAsset isPlayableExtendedMIMEType:type])
{
NSURL *streamURL = [NSURL URLWithString:urlString];
NSString *signature = stream[#"sig"];
if (signature)
streamURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#&signature=%#", urlString, signature]];
if ([[DictionaryWithQueryString(streamURL.query, queryEncoding) allKeys] containsObject:#"signature"])
streamURLs[#([stream[#"itag"] integerValue])] = streamURL;
}
}
for (NSNumber *videoQuality in self.preferredVideoQualities)
{
NSURL *streamURL = streamURLs[videoQuality];
if (streamURL)
{
NSString *title = video[#"title"];
NSString *thumbnailSmall = video[#"thumbnail_url"];
NSString *thumbnailMedium = video[#"iurlsd"];
NSString *thumbnailLarge = video[#"iurlmaxres"];
NSMutableDictionary *userInfo = [NSMutableDictionary new];
if (title)
userInfo[XCDMetadataKeyTitle] = title;
if (thumbnailSmall)
userInfo[XCDMetadataKeySmallThumbnailURL] = [NSURL URLWithString:thumbnailSmall];
if (thumbnailMedium)
userInfo[XCDMetadataKeyMediumThumbnailURL] = [NSURL URLWithString:thumbnailMedium];
if (thumbnailLarge)
userInfo[XCDMetadataKeyLargeThumbnailURL] = [NSURL URLWithString:thumbnailLarge];
[[NSNotificationCenter defaultCenter] postNotificationName:XCDYouTubeVideoPlayerViewControllerDidReceiveMetadataNotification object:self userInfo:userInfo];
return streamURL;
}
}
if (error)
{
NSMutableDictionary *userInfo = [#{ NSURLErrorKey: self.connection.originalRequest.URL } mutableCopy];
NSString *reason = video[#"reason"];
if (reason)
{
reason = [reason stringByReplacingOccurrencesOfString:#"<br\\s*/?>" withString:#" " options:NSRegularExpressionSearch range:NSMakeRange(0, reason.length)];
NSRange range;
while ((range = [reason rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
reason = [reason stringByReplacingCharactersInRange:range withString:#""];
userInfo[NSLocalizedDescriptionKey] = reason;
}
NSInteger code = [video[#"errorcode"] integerValue];
*error = [NSError errorWithDomain:XCDYouTubeVideoErrorDomain code:code userInfo:userInfo];
}
return nil;
}
You should use the latest version (2.0.2 as of writing) of XCDYouTubeKit, the successor of XCDYouTubeVideoPlayerViewController. The video 5Uls9v1nnss should play fine.
Related
When i got my server response and trying to save that in plist, but plist file is not creating.
I have logged file path and dictionary contents but all these have data still plist not creating
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self sideMenu:#"ML"];
return YES;
}
this will call following method
-(void)sideMenu:(NSString *)title{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"data=%#&deviceid=e8ef8c98262185ec",title];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:SIDE_MENU]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
NSArray *myArray = [responseString componentsSeparatedByString:#"<!DOC"];
//NSLog(#"%#",myArray);
if (myArray != nil || [myArray count] > 0) {
NSData *data = [[[myArray objectAtIndex:0]stringByReplacingOccurrencesOfString:#"\n" withString:#""] dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self sideMenuFile:title :json];
}
}
-(NSString *)sideMenuFile:(NSString *)titleName :(NSDictionary *)dict{
NSString *filePath;
MyManager *sharedManager =[MyManager sharedManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([titleName isEqualToString:#"ML"])
{ sharedManager.sideMenu = [[NSDictionary alloc]init];
sharedManager.sideMenu = dict;
filePath = [documentsDirectory stringByAppendingPathComponent:#"ML.plist"];
}else if ([titleName isEqualToString:#"HM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"HM.plist"];
}else if ([titleName isEqualToString:#"PDC"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"PDC.plist"];
}else if ([titleName isEqualToString:#"SM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"SM.plist"];
}else if ([titleName isEqualToString:#"GL"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}else if ([titleName isEqualToString:#"CU"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"CU.plist"];
}else if ([titleName isEqualToString:#"BR"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}
NSLog(#"%#",filePath); //printing path
[dict writeToFile:filePath atomically:YES];
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *plistName = #"GL";
NSString *finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName]];
NSDictionary *dictww=[[NSDictionary alloc]initWithContentsOfFile:finalPath];
NSLog(#"dict%#",dictww); //printing nill
return filePath;
}
JSON file structure
{
sigallery = {
rows = (
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/1.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 1;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
},
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/2.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 2;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
}
)
}
}
Your code makes a number of non-optimal assumptions.
1)
Whenever you write out a file, you should always check for any error condition if it's available. NSDictionary's writeTo... methods do return Booleans whether the file has been written out or not, so you could do:
NSLog(#"%#",filePath); //printing path
BOOL success = [dict writeToFile:filePath atomically:YES];
if (success == false)
{
NSLog(#"did not successfully write dictionary to path %#", filePath);
} else {
// ... do everything else in here
}
2)
You write out files wih the format titleName + GL | PDC | SM.plist but when you try to read things back in, there is no titleName as part of the finalPath, so nothing lines up here.
3)
Also, why do you assume basePath is valid (it looks like it could be nil)?
I'm using the camfind api, I post a request where I send the api an image and get a token, and then I can use the token to get what the image is, but this takes two steps, a post and a get request. I want to combine them, so the get request auto fires right when the server responds to the post request. Here is the code :
I specify a value for the token at the top
NSString *tokenValue;
the request method, here an image is selected and sent to the server, the server sends a token response back in this request
- (void *) requestMethod: (UIImage *)imageToConvert{
NSString *temp = #"saved";
NSLog(#"%#", temp);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [paths objectAtIndex:0];
NSString *imagePath = [documentDirectoryPath stringByAppendingPathComponent:#"tmp_image.jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
NSData *imageData = UIImageJPEGRepresentation(imageToConvert , 1.0);
[imageData writeToURL:imageURL atomically:YES];
// NSString *base64image = [NSString stringWithFormat:#"%#",[imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
NSString *base64image = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
// These code snippets use an open-source library.
// NSString *baseboy = [base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSURL *urlimage_request = [NSURL URLWithString:[base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *headers = #{#"X-Mashape-Key": #"********"};
NSDictionary *parameters = #{#"focus[x]": #"480", #"focus[y]": #"640", #"image_request[altitude]": #"27.912109375", #"image_request[image]": imageURL, #"image_request[language]": #"en", #"image_request[latitude]": #"35.8714220766008", #"image_request[locale]": #"en_US", #"image_request[longitude]": #"14.3583203002251"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
[request setUrl:#"https://camfind.p.mashape.com/image_requests"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSString *token = response.description;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
for(NSString *key in [json allValues])
{
tokenValue = [json valueForKey: #"token" ];
NSString *two = [json valueForKey: #"token" ]; // assuming the value is indeed a string
NSLog(#"Token :%#", two);
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, two];
// NSString *responseURL = [one stringByAppendingString:two];
NSLog(#"response URL %#", responseString);
// UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
// [request setUrl:responseString];
// [request setHeaders:headers];
// }] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
// NSInteger code = response.code;
// NSDictionary *responseHeaders = response.headers;
// UNIJsonNode *body = response.body;
// NSData *rawBody = response.rawBody;
// NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
// options:kNilOptions
// error:nil];
// NSLog(#"Response status: %ld\n%#", (long) response.code, json);
//
//
// // NSLog(#"didfinishLoadingbody%#",rawBody);
// // NSLog(#"didfinishLoadingbody%#",body);
// //
// // NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// // NSLog(#"didfinishLoading tok%#",token);
// }];
}
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
// NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
the response method below uses the token from the request above to print out what the image is
- (void *) responseMethod {
// These code snippets use an open-source library.
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, tokenValue];
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:responseString];
[request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
rest of the vc other stuff
-(void)loadView {
[super loadView];
}
- (void)viewDidLoad{
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
}
I don't know how to make the response method fire right away when the server replies, I don't know objc, im using this in a swift project
#end
so I've been given a task of using a flickr API created by a lecturer, and we have to use it to populate a tableview of a particular user. I'm able to count the number of elements etc, but I can't figure out for the life of me how to actually call the image/photo element of the pair?
This is the code:
- (NSArray *) photosForUser: (NSString *) friendUserName
{
NSString *request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=%#", friendUserName];
NSDictionary *result = [self fetch: request];
NSString *nsid = [result valueForKeyPath: #"user.nsid"];
request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=%ld&has_geo=1&user_id=%#&extras=original_format,tags,description,geo,date_upload,owner_name,place_url", (long) self.maximumResults, nsid];
result = [self fetch: request];
return [result valueForKeyPath: #"photos.photo"];
}
What is used to fetch the data:
- (NSDictionary *) fetch: (NSString *) request
{
self.apiKey = #"26225f243655b6eeec8c15d736b58b9a";
NSLog(#"self.APIKey = %#", self.apiKey);
NSString *query = [[NSString stringWithFormat: #"%#&api_key=%#&format=json&nojsoncallback=1", request, self.apiKey]
stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *queryURL = [NSURL URLWithString: query];
NSData *responseData = [NSData dataWithContentsOfURL: queryURL];
if (!responseData)
return nil;
NSError *error = nil;
NSDictionary *jsonContent = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
if (!jsonContent)
NSLog(#"Could not fetch '%#': %#", request, error);
return jsonContent;
}
Can anyone give me any pointers on how I can actually call the image?
Much appreciated.
edit: this is an NSLog output of what's in the JSON array received from the flickr API.
latestPhotos (
{
accuracy = 16;
context = 0;
dateupload = 1397679575;
description = {
"_content" = "<a href=\"https://www.flickr.com/photos/tanjabarnes/\">
};
farm = 3;
"geo_is_contact" = 0;
"geo_is_family" = 0;
"geo_is_friend" = 0;
"geo_is_public" = 1;
id = 13902059464;
isfamily = 0;
isfriend = 0;
ispublic = 1;
latitude = "34.062214";
longitude = "-118.35862";
owner = "66956608#N06";
ownername = Flickr;
"place_id" = "I78_uSpTWrhPjaINgQ";
secret = cc17afe1b3;
server = 2928;
tags = "panorama losangeles beverlyhills tanjabarnes";
title = blahlbah
woeid = 28288701;
}
)
You need to construct the URL of the image using the ids in your JSON array. Like this:
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
So in your example:
http://farm3.staticflickr.com/2928/13902059464_cc17afe1b3.jpg
Here's how you get to your images:
NSArray *photos = [self photosForUser:friendUserName];
for(NSDictionary *dictionary in photos) {
NSString *farmId = [dictionary objectForKey:#"farm"];
NSString *serverId = [dictionary objectForKey:#"server"];
NSString *photoId = [dictionary objectForKey:#"id"];
NSString *secret = [dictionary objectForKey:#"secret"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg", farmId, serverId, photoId, secret]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
// Do something with your image here
}
Reference: https://www.flickr.com/services/api/misc.urls.html
In my iOS app I'm using the weather APIs of worldweatheronline.com but I get a random "EXC_BAD_ACCESS" error oh this row (not always but sometimes) :
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
Here is my code:
- (void)showWeatherFor:(CLLocation *)newLocation
{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=%f,%f&format=json&num_of_days=5&key=ydvgep8jn5m846upd8kb2qp6", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myRequestString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *JsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:JsonString error:&error];
NSDictionary *data = [theDictionary objectForKey:#"data"];
NSArray *currentDictionary = [data objectForKey:#"current_condition"];
NSDictionary *temp = [currentDictionary objectAtIndex:0];
if ([temp objectForKey:#"temp_C"] == nil || [temp objectForKey:#"temp_F"] == nil)
{
return;
termometro.alpha = 0;
}
else
{
if (temp != nil)
{
if ([mainDelegate.gradi isEqualToString: #"°C"])
{
NSNumber *tempC = [temp objectForKey:#"temp_C"];
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
mainDelegate.temperature = [[temp objectForKey:#"temp_C"]intValue];
}
else
{
NSNumber *tempF = [temp objectForKey:#"temp_F"];
temperature.text = [NSString stringWithFormat:#"%# °F", tempF];
mainDelegate.temperature = [[temp objectForKey:#"temp_F"]intValue];
}
termometro.alpha = 1;
}
}
}
I'm trying to preview a downloaded file to system and the program crashes when performing the method called previewController:previewItemAtIndex:. From what I assumed is that is releasing the previewcontroller before it is displayed, but this error does not occur when the file is already in the documents folder. It only happens when trying to open the file right after it has been downloaded.
Here is the code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSUInteger count = [listSessionsST count];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Signature *object = [listSessionsST objectAtIndex:row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UILabel *lblInComplete = (UILabel*)[cell viewWithTag:4];
UIImageView *imgCheck = (UIImageView*)[cell viewWithTag:3];
//Sets the File Name
self.File = [[[NSString stringWithFormat:#"%#_%#.%#",object.FileName,object.ModDate,object.Extension]
componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: #""];
//Shows the loading screen while the file is being downloaded
[DejalBezelActivityView activityViewForView:self.view withLabel:#"Downloading" width:0 LoadingType:#"Full"];
[DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
//Calls the method that will begin downloading the file
[self performSelector:#selector(startDownload:) withObject:object.Location afterDelay:0.2];
}
- (void)startDownload:(NSString *)strLocation{
NSString *filePath = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),self.File];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExists)
{
[DejalBezelActivityView removeViewAnimated:YES];
//QuickLook APIs directly to preview the document
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
[[self navigationController] pushViewController:previewController animated:YES];
[previewController release];
}
else
{
NSDictionary *dictionary = [Signature downloadFile:self.File Path:strLocation];
if ([dictionary valueForKey:#"Error"] == nil)
{
//If no error has occurred while downloading then preview the file.
//QuickLook APIs directly to preview the document
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
[[self navigationController] pushViewController:previewController animated:YES];
[previewController release];
[DejalBezelActivityView removeViewAnimated:YES];
}
else
{
//If an error occurred while downloading then display message to user.
[DejalBezelActivityView removeViewAnimated:YES];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#""
message:[dictionary valueForKey:#"Response"]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
// Returns the number of items that the preview controller should preview
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{
return 1;
}
// returns the item that the preview controller should preview
- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
NSString *path = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),self.File];
return [NSURL fileURLWithPath:path];
}
The method that downloads the file and saves it to the tmp folder
---------------------------------------------------------------
+ (NSDictionary *)downloadFile:(NSString *)strFile Path:(NSString *)strPath{
float freeSpace = 0.0f;
NSError *error = nil;
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[NSString stringWithFormat:#"%#/tmp", NSHomeDirectory()]
error: &error];
if (dictionary)
{
NSNumber *fileSystemFreeSizeInBytes = [dictionary objectForKey: NSFileSystemFreeSize];
freeSpace = [fileSystemFreeSizeInBytes floatValue];
}
else
{
//Handle error
NSLog(#"Error;%#",error);
return [NSDictionary dictionaryWithObjectsAndKeys:#"An error has occurred while downloading the file.",#"Response",#"Y",#"Error", nil];
}
if (freeSpace > 0.0f)
{
NSDictionary *dict = nil;
BOOL blnHasErroroccurred = NO;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *encoded = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)strPath,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]%",
kCFStringEncodingUTF8 );
NSString *strURL = [NSString stringWithFormat:#"%#/DataTransfer/DownloadFile?EMP_ID=%#&FilePath=%#",
appDelegate.ServerAddress,
appDelegate.UserId,
encoded];
[encoded release];
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* resultError = nil;
NSData* dataResult = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&resultError];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200)
{
#try
{
if (dataResult.length < freeSpace)
{
//Get the tmp directory
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString *fileName = [NSString stringWithFormat:#"%#/tmp/%#", NSHomeDirectory(),strFile];
//Write the data to using the tmp directory
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataResult attributes:nil];
if(filecreationSuccess == YES)
{
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"",#"Response",nil,#"Error", nil];
}
else
{
blnHasErroroccurred = YES;
}
}
}
#catch (NSException *exception)
{
blnHasErroroccurred = YES;
}
}
else
{
blnHasErroroccurred = YES;
}
if(blnHasErroroccurred == YES)
{
dict = [NSDictionary dictionaryWithObjectsAndKeys:#"An error has occurred while downloading the file.", #"Response", #"Yes",#"Error",nil];
}
[dataResult release];
return dict;
}
else
{
return [NSDictionary dictionaryWithObjectsAndKeys:#"Not enough disk space to download file.",#"Response",#"Y",#"Error", nil];
}
}