Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- - (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
- {
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
- [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
- {
- if (!error)
- {
- completionBlock(YES, data);
- }
- else
- {
- completionBlock(NO, nil);
- }
- }];
- }
- UIImage *image = [UIImage imageWithData:serverData];
- NSData *jpegData = UIImageJPEGRepresentation(image, 0.75f);
- CGDataProviderRef imgProvider = CGDataProviderCreateWithCFData((CFDataRef) data);
- CGImageRef imgRef = CGImageCreateWithJPEGDataProvider(imgProvider, NULL, true, kCGRenderingIntentDefault);
- import Foundation
- import ImageIO
- import MobileCoreServices
- func saveImageData(_ data: Data, to fileUrl: URL) {
- guard let provider = CGDataProvider(data: data as CFData) else {
- print("Could not create data provider from data")
- return
- }
- guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
- print("Could not create cgImage from provider")
- return
- }
- guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
- print("Could not create an image destination from url")
- return
- }
- let options = [
- kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
- kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
- ] as CFDictionary
- CGImageDestinationAddImage(imageDestination, cgImage, options)
- let imageIsWritten = CGImageDestinationFinalize(imageDestination)
- if !imageIsWritten {
- print("Image could not be written")
- }
- }
- let data: Data = …
- let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
- let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
- saveImageData(data, to: fileUrl)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement