Search code examples
iosobjective-cnsdocumentdirectorynsoutputstreamafhttprequestoperation

Couldn't save data in given path of document directory by NSOutputStream


How to save downloaded content/data in the given path in document directory by NSOutputStream. If i append file name with DD then it works (ex- DD/contentPath.zip), But if i append a path like DD/hello/contentPath.zip then it doesn't work. Why ? I tried like below -

- (void) downloadCarContents:(NSString *)url forContent:(NSString *)contentPath {

    //NSString *destinationPath = [self.documentDirectory getDownloadContentPath:contentPath];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *op = [manager GET:url
                                   parameters:nil
                                      success:^(AFHTTPRequestOperation *operation, id responseObject) {


                                      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                                          //NSLog(@"Error : %@", error.localizedDescription);
                                      }];

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dest = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"hello/%@.zip", contentPath]];// It doesn't work
    //NSString *dest = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip", contentPath]];// It works

    op.outputStream = [NSOutputStream outputStreamToFileAtPath:dest append:NO];

    [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float percentage = (float) (totalBytesRead * 100) / totalBytesExpectedToRead;
        [self.delegate downloadProgression:percentage];
    }];
}

Solution

  • The API doesn't create the folder for you. Your code needs to ensure it exists before you try to use it. NSFileManager can help with createDirectoryAtPath:withIntermediateDirectories:attributes:error: