NSData stored somewhere

前端 未结 2 546
梦谈多话
梦谈多话 2021-01-23 08:16

recently i created a post: NSData caching routine

But, now i want to be more specific in what i\'m asking.

You see, i have \"carousel\", that is actually a scrol

相关标签:
2条回答
  • 2021-01-23 09:05
    • Firstly you should check the type:
    • Got to this link: I given my answer here: Check type of class an NSData store?

      Hope this helps you.

    0 讨论(0)
  • 2021-01-23 09:15

    If you were to do this yourself, you could create two-tier cache system, using NSCache and local file system. So,

    1. At app startup, instantiate a NSCache object.

    2. When you need to download an image, see if image is in NSCache.

    3. If not, see if image is in NSCachesDirectory folder in file system, if found here, but not in NSCache, make sure to update NSCache accordingly.

    4. If found in neither NSCache nor NSCachesDirectory, request it asynchronously from the network (using NSURLSession) and if you successfully found image, update both NSCache and NSCachesDirectory accordingly.

    5. BTW, upon UIApplicationDidReceiveMemoryWarningNotification, make sure to empty the NSCache.

    That might look something like:

    NSString *filename = [webURL lastPathComponent];
    NSURL *fileURL;
    
    // look in `NSCache`
    
    NSData *data = [self.cache objectForKey:filename];
    
    // if not found, look in `NSCachesDirectory`
    
    if (!data) {
        NSError *error;
        NSURL *cacheFileURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:&error];
        fileURL = [cacheFileURL URLByAppendingPathComponent:filename];
        data = [NSData dataWithContentsOfURL:fileURL];
    
        // if found, update `NSCache`
    
        if (data) {
            [self.cache setObject:data forKey:filename];
        }
    }
    
    // if still not found, retrieve it from the network
    
    if (!data) {
        [[NSURLSession sharedSession] dataTaskWithURL:webURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (error) {
                // handle error
                return;
            }
    
            UIImage *image = [UIImage imageWithData:data];
    
            // if image retrieved successfully, now save it
            if (image) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.cache setObject:data forKey:filename];
                    NSError *fileError;
                    [data writeToURL:fileURL options:NSDataWritingAtomic error:&fileError];
                });
            }
        }];
    }
    

    Having said all of this, I agree with the others that it's worth trying the UIImageView categories found in either SDWebImage and/or AFNetworking. They might do what you need, with far less work.

    0 讨论(0)
提交回复
热议问题