403 Error with Afnetworking.

Discussion in 'Mac Programming' started by DavidBlack, Mar 26, 2014.

  1. DavidBlack macrumors 6502a

    DavidBlack

    Joined:
    Jan 27, 2013
    Location:
    Somewhere In Apple's HQ ;)
    #1
    Can anyone here help me with this 403 error my beta testers are getting? I will show you my download code to see if anyone can help me. Any help will be appreciated :)
    Also, it's weird that I am not getting these errors myself.

    Code:
    [savePanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
    
                if (result == NSOKButton) {
                    // See download has a backslash
                    NSString *sentence = [savePanel nameFieldStringValue];
                    NSString *word = @"/";
                    if ([sentence rangeOfString:word].location != NSNotFound)
                        NSLog(@"Download title does has forward slash, inserting a 'space' instead.");
                    NSString *OfficalDownloadSString = sentence;
                    NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:@"/"];
                    OfficalDownloadSString = [[OfficalDownloadSString componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: @" "];
    
                        //Downloading has began we can show hidden things in the popoever
                        [self.revealOutlet setHidden:NO];
                        [self.revealOutlet setEnabled:YES];
                        [self.revealOutlet setHidden:NO];
                        [self.videoImage setHidden:NO];
                        [self.stopDownloadsOutlet setHidden:NO];
                        [self.videoTitleLabel setHidden:NO];
                        [self.downloadProgressIndicator setHidden:NO];
                        [self.downloadProgressLabel setHidden:NO];
    
                        [self.downloadButton setTitle: @"Stop"];
    
                        //Background Thread
    
                    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urldownload]];
                       __strong AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] self];
                        universalRequest = operation;
    
                     //copy the reference but now in a weak flag
    
                        __weak AFHTTPRequestOperation *weakOperation = operation;
                        NSArray *paths = [[NSArray alloc] initWithObjects:[savePanel directoryURL], nil];
                        NSURL *path = [[paths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",OfficalDownloadSString]];
                        operation.outputStream = [NSOutputStream outputStreamWithURL:path append:NO];
                        operation.downloadSpeedMeasure.active = YES;
                        universalDownloadURL = path;
    
                    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
                    securityPolicy.allowInvalidCertificates = YES;
                    operation.securityPolicy = securityPolicy;
    
                    AFSecurityPolicy *securityPolicy1 = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
                    securityPolicy1.allowInvalidCertificates = YES;
                    weakOperation.securityPolicy = securityPolicy1;
    
                        [weakOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                            NSLog(@"Successfully downloaded file to %@", path);
    
                            //set the downloading bool to no
                            downloadingFlag = NO;
                            [self.downloadButton setTitle:@"Download"];
    
                            //Set the downloadProgressLabel to complete
                            [self.downloadProgressLabel setStringValue:@"Download complete."];
    
                            //set downloadProgressIndicator TO Indeterminate
                            [self.downloadProgressIndicator setIndeterminate:YES];
    
                            //Hide the cancel download button beacuse the user can't cancel a completed download
                            [self.stopDownloadsOutlet setHidden:YES];
    
                            NSUserNotification *notification = [[NSUserNotification alloc] init];
    
                            //Set the title of the notification
                            [notification setTitle:NSLocalizedString(@"Download Complete", nil)];
                            //Set the text of the notification
                            [notification setInformativeText:[NSString stringWithFormat:@"The video: %@.mp4 has successfully finsihed downloading",[savePanel nameFieldStringValue]]];
                            //Set the sound, this can be either nil for no sound, NSUserNotificationDefaultSoundName for the default sound (tri-tone) and a string of a .caf file that is in the bundle (filname and extension)
                            [notification setSoundName:NSUserNotificationDefaultSoundName];
    
                            //Get the default notification center
                            NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
                            //Scheldule our NSUserNotification
                            [center scheduleNotification:notification];
                            [center setDelegate:self];
    
                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                            NSLog(@"Error: %@", error);
                            if (erroroccuredbecauseofUserStoppingDownload) {
                                // DO nothing because the user stopped the download not a real error
                            } else{
                            //An error has happened
                            //Hide the cancel download button beacuse the user can't cancel a failed download
                            [self.stopDownloadsOutlet setHidden:YES];
                            [NSApp presentError:error];
                            [self.downloadProgressIndicator setIndeterminate:YES];
    
                            [self.downloadProgressIndicator startAnimation:sender];
    
                            //Set the label to show that there was an error.
                            [self.downloadProgressLabel setStringValue:@"An error occurred"];
    
                            //Take off the reveal button
                            [self.revealOutlet setHidden:YES];
    
                                [self.downloadButton setTitle:@"Retry"];
                            }
                        }];
                             //UI Updates
                        [weakOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                        __unused NSString *label = [NSString stringWithFormat:@"Downloaded %lld of %lld bytes",
                                               totalBytesRead,
                                               totalBytesExpectedToRead];
    
                            [self.downloadProgressIndicator setDoubleValue:(long)totalBytesRead / (double)totalBytesExpectedToRead*100];
    
                            //BETA FEATURE ADD PROGRESS TO DOCK
                            NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0.0f, 0.0f, 80.0f, 20.0f)];
                            [progressIndicator setStyle:NSProgressIndicatorBarStyle];
                            [progressIndicator setIndeterminate:NO];
                            [[[NSApplication sharedApplication] dockTile] setContentView:progressIndicator];
                            [progressIndicator setDoubleValue:(long)totalBytesRead / (double)totalBytesExpectedToRead*100];
                            [[[NSApplication sharedApplication] dockTile] display];
    
                            //Method for converting bytes to mb,gb or kb
    
                            double GBs = (double)(totalBytesRead) / (double)(1024 * 1024 * 1024);
                            double MBs = (double)(totalBytesRead) / (double)(1024 * 1024);
                            double KBs = (double)(totalBytesRead) / (double)(1024);
    
                            if(GBs >= 1.0)
                            {
    
                                NSString *humanReadableSpeed = operation.downloadSpeedMeasure.humanReadableSpeed;
    
                                double GBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024 * 1024);
                                double MBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024);
                                double KBSExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024);
                                if (GBExpectedtoRead >= 1.0) {
                                    // GB Range
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fGB of %.1fGB (%@) - %@",MBs,GBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                } else if (MBExpectedtoRead >= 1.0){
                                    //MB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fGB of %.1fMB (%@) - %@",MBs,MBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
    
                                else if (KBSExpectedtoRead >= 1.0){
                                    //KB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fGB of %.1fKB (%@) - %@",MBs,KBSExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
                            }
                            else if(MBs >= 1.0)
                            {
    
                                NSString *humanReadableSpeed = operation.downloadSpeedMeasure.humanReadableSpeed;
    
                                double GBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024 * 1024);
                                double MBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024);
                                double KBSExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024);
                                if (GBExpectedtoRead >= 1.0) {
                                    // GB Range
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fMB of %.1fGB (%@) - %@",MBs,GBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                } else if (MBExpectedtoRead >= 1.0){
                                    //MB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fMB of %.1fMB (%@) - %@",MBs,MBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
    
                                else if (KBSExpectedtoRead >= 1.0){
                                    //KB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fMB of %.1fKB (%@) - %@",MBs,KBSExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
    
                            }
                            else if (KBs >= 1.0)
                            {
    
                                NSString *humanReadableSpeed = operation.downloadSpeedMeasure.humanReadableSpeed;
    
                                double GBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024 * 1024);
                                double MBExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024 * 1024);
                                double KBSExpectedtoRead = (double)(totalBytesExpectedToRead) / (double)(1024);
                                if (GBExpectedtoRead >= 1.0) {
                                    // Since the filesize esimated to be in the GB range we update the Last value e.g %.1f  GB the same applys for all methods below
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fKB of %.1fGB (%@) - %@",KBs,GBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                } else if (MBExpectedtoRead >= 1.0){
                                    //MB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fKB of %.1f MB (%@) - %@",KBs,MBExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
    
                                else if (KBSExpectedtoRead >= 1.0){
                                    //KB
                                    NSString *humanReadableRemaingTime = [operation.downloadSpeedMeasure humanReadableRemainingTimeOfTotalSize:totalBytesExpectedToRead numberOfCompletedBytes:totalBytesRead];
                                    [self.downloadProgressLabel setStringValue:[NSString stringWithFormat:@"%.1fKB of %.1fKB (%@) - %@",KBs,KBSExpectedtoRead,humanReadableSpeed,humanReadableRemaingTime]];
                                }
    
                            }
    
                        }];
    
                        [operation start];
    
                        //Open the popover
                        [self.popover showRelativeToRect:[popoverTriggerButton bounds] ofView:popoverTriggerButton preferredEdge:NSMaxYEdge];
                        //Set the video tile to the title from the savePanel
                        [self.videoTitleLabel setStringValue:[NSString stringWithFormat:@"%@.mp4",[savePanel nameFieldStringValue]]];
    
                    } else if (result == NSCancelButton){
                        downloadingFlag = NO;
                        [self.downloadButton setTitle:@"Download"];
                        [self.universalRequest cancel];
                        // set back to 0.0
                        [self.downloadProgressIndicator setDoubleValue:0.0];
    
                        //Then set label to download cancel
                        [self.downloadProgressLabel setStringValue:@"Download cancel."];
    
                        erroroccuredbecauseofUserStoppingDownload = YES;
                    }
            }];
          }];
    
                }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"Error: %@", error);
                    NSRunAlertPanel(@"Invalid URL", @"Unable to find any YouTube video with the URL you provided.", @"OK", nil, nil);
                    [self.downloadButton setTitle:@"Retry"];
                    downloadingFlag = NO;
    
                }];
    }
     
  2. JohnsonK macrumors regular

    Joined:
    Mar 6, 2014
    #2
    http error 403 means forbidden, not a problem with the code
     
  3. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #3
    Google for "error 403". There's even a page on Wikipedia!

    A web server may return a 403 Forbidden HTTP status code in response to a request from a client for a web page or resource to indicate that the server can be reached and understood the request, but refuses to take any further action. Status code 403 responses are the result of the web server being configured to deny access, for some reason, to the requested resource by the client.


    No problem with your program. The user asked the server for a website, and the server said "No, you can't have it. I understood exactly what you are asking for, but no, you can't get it. Don't bother asking again". Nothing you can do about it.

    Note that this is different from 401 which tells you that you have no authentication. You need to try the request with a username and password or similar. (Because servers don't want to give out information to people without username and password, it could be that you get a different error when you supply username and password. )
     

Share This Page