简体   繁体   中英

iOS - writeToFile from NSData completion handler

I am getting bytes of a file from a webservice, my goal is to get these bytes, put them into NSData and then write into a file, once the writeToFile is 100% complete, I would then display the file (its a PDF, can be up to 6 pages) in QLPreviewController.

I am able to get the bytes from the webservice and put them into NSData like so:

NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:@"%@",encodedUrlStr]];

        NSData *data;

        for (NSDictionary *dict in byteArray) {
            NSString *base64 = dict[@"data"];
            data = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
        }

Now I am trying to write the file like so:

if (data)
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];

            filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,PDFFile];

            [data writeToFile:filePath atomically:YES];

        }

Now what I am trying to do is have some sort of completion handler so nothing else happens until the file is completely written. What would be the best way to do this?

I am also starting to look into NSFileHandle, would that be a better solution?

No need to worry about completion if this runs in main queue it's serial , but it's better to save in background queue and read content to verify and present in main Queue

  DispatchQueue.global(qos: .background).async {
        print("This is run on the background queue")

        if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
        {
            NSLog(@"not exists");

            NSData *fileContents = [@"" dataUsingEncoding:NSUTF8StringEncoding];
            [[NSFileManager defaultManager] createFileAtPath:filePath
                                                    contents:fileContents
                                                  attributes:nil];

        }
        else
        {
             NSLog(@"exists");

        }


        NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        [myHandle seekToEndOfFile];


        NSString*strTowrite=[NSString stringWithFormat:@"%@ || %@ --- %@ \r\n",dt,acion,name];

        [myHandle writeabilityHandler];

        [myHandle writeData:[strTowrite dataUsingEncoding:NSUTF8StringEncoding]];


    DispatchQueue.main.async {
        NSString*content=[[NSString alloc] initWithContentsOfFile:filePath
                                                         encoding:NSUTF8StringEncoding
                                                            error:&error];
         if(content)
        {


            NSLog(@"content is : %@ Err : %@",content,error);

            // [self sendfile];


        }
        else
        {

            NSLog(@"Failed to store the file. Error = %@", error);

        }
     }
    }

use NSFilePresenter to monitor for changes to the file and use a NSFileCoordinator to write to it

in mock code:

NSFilePresenter *p = [NSFilePresenter presenterWithFile:f];
[p signupForChangeNotificationsOrSetDelegateOrWhatever....];

//write 
NSFileCoordinator *c = [NSFileCoordinator coordinatorWithPresenter:p];
[c coordinate writeData....]

... called back by p cause we changed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM