如何防止共享扩展中出现内存警告

问题描述 投票:0回答:1

我正在实现一个共享扩展,该扩展在图像处理完成之前就消失了。

2018-02-22 15:11:20.327673-0500 ContentShare[9491:649748] [core] SheetViewController didReceiveMemoryWarning
2018-02-22 15:11:20.367087-0500 ContentShare[9491:649748] [core] SheetViewController didReceiveMemoryWarning
Program ended with exit code: 0

我还没有创建任何名为

SheetViewController
的东西,更令人沮丧的是,我已经消除了任何内存密集型操作,并且当我调整大小和压缩要共享的图像时在控制台中看到了这一点。我什至还没有开始将图像上传到服务器的过程。

  • 我应该如何处理图像以将其放到服务器上?
  • 我将用户会话数据存储在共享 NSUserDefaults 中,以检查用户是否具有有效登录。因为整个 NSUserDefaults 都加载到内存中,所以这是传递此身份验证数据的有效方法吗?
  • 初始化另一个文件进行图像处理和上传是否正确?
  • AFNetworking 是否可以使用,或者使用超出 用于处理/上传的推荐内存量?
  • 是否有明确的最佳实践来处理共享项目?苹果的文档看起来相当稀疏。

ShareViewController.m 已选择邮政编码:

- (void)didSelectPost {
    // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

    NSExtensionItem *inputItem = self.extensionContext.inputItems.firstObject;

    NSExtensionItem *outputItem = [inputItem copy];
    outputItem.attributedContentText = [[NSAttributedString alloc] initWithString:self.contentText attributes:nil];
    // Complete this implementation by setting the appropriate value on the output item.

    [self.extensionContext.inputItems enumerateObjectsUsingBlock:^(NSExtensionItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {

        [item.attachments enumerateObjectsUsingBlock:^(NSItemProvider * _Nonnull itemProvider, NSUInteger idx, BOOL * _Nonnull stop) {

            NSString *extension = nil;
            NSString *identifier = nil;
            MESSAGE_TYPE type = TEXT;
            if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
                extension = @".jpg";
                identifier = (NSString *)kUTTypeImage;
                type = PHOTO;
            } else if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeAudio]) {
                extension = @".mp3";
                identifier = (NSString *)kUTTypeAudio;
                type = AUDIO;
            } else if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeVideo]) {
                extension = @".mp4";
                identifier = (NSString *)kUTTypeVideo;
                type = VID;
            } else if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeData]) {
                extension = @".data";
                identifier = (NSString *)kUTTypeData;
                type = DOWNLOAD;
            }
            if (identifier != nil) {
                [itemProvider loadItemForTypeIdentifier:identifier
                                                options:nil
                                      completionHandler:^(id<NSSecureCoding>  _Nullable item, NSError * _Null_unspecified error) {
                                          if ([(NSObject *)item isKindOfClass:[NSURL class]])
                                          {
                                              if ([(NSURL *)item isFileURL] == YES) {
                                                  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                                      NSLog(@"PROCESS ON BACKGROUND THREAD");
                                                      MyWebServices *services = [[MyWebServices alloc] init];
                                                      [services processSharedItemWithReceiver:self.receiver
                                                                                      message:self.contentText
                                                                                   andContent:item
                                                                          withCompletionBlock:^(NSMutableArray *resultsArray) {
                                                                              NSLog(@"RESULTS ARRAY: %@", resultsArray);
                                                                              NSLog(@"IN COMPLETION BLOCK TO CLOSE SHARE UI");

                                                                          }];
                                                  });
                                                  [self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];

                                              }
                                          }
                                      }];
            }

        }];
    }];
}

MyWebServices.m 代码

- (void)processSharedItemWithReceiver:(NSString*)receiver
                              message:(NSString*)contentMessage
                           andContent:(id<NSSecureCoding>)item
                  withCompletionBlock:(void (^)(NSMutableArray *resultsArray))completion{
    NSData *data = [NSData dataWithContentsOfURL:(NSURL *)item];
    NSString *fname = [(NSURL *)item lastPathComponent];
    NSString *mimeType = [self mimeTypeForData:[NSData dataWithContentsOfURL:(NSURL *)item]];
    NSLog(@"SENDING FILE: %@  WITH FILETYPE: %@", fname, mimeType);

    //Compress and rotate image so that it is in correct pixel orientation because not all EXIF is respected
    NSData *compressedImg = [self compressJPEGImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:(NSURL *)item]]];
    //Convert compressed image into base64 data to POST to server
    //NSString *base64String = [compressedImg base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    if(data){

       /* [self setUserShareMessageToUser:receiver withMessage:contentMessage postFileContent:base64String fileType:mimeType fileName:fname  CompletionBlock:^(NSMutableArray *resultsArray) {
            NSLog(@"IN COMPLETION BLOCK: %@", resultsArray);
            if(completion) {
                //[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                completion([resultsArray[0] valueForKey:@"CONTENT"]);
            }

        }]; */
        NSMutableArray *arr = [NSMutableArray arrayWithObjects:fname, mimeType, nil];
        completion(arr);
    }
}

-(NSString *)mimeTypeForData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];

    switch (c) {
        case 0xFF:
            return @"image/jpeg";
            break;
        case 0x89:
            return @"image/png";
            break;
        case 0x47:
            return @"image/gif";
            break;
        case 0x49:
        case 0x4D:
            return @"image/tiff";
            break;
        case 0x25:
            return @"application/pdf";
            break;
        case 0xD0:
            return @"application/vnd";
            break;
        case 0x46:
            return @"text/plain";
            break;
        default:
            return @"application/octet-stream";
    }
    return nil;
}

-(NSData *)compressJPEGImage:(UIImage*)image{
    UIImageOrientation o = image.imageOrientation;
    float degreesOfRotation = 0.0;
    NSLog(@"IMAGE ORIENTATION: %li", o);
    //UIImageOrientationUp,            // default orientation
    //UIImageOrientationDown,          // 180 deg rotation
    //UIImageOrientationLeft,          // 90 deg CCW
    //UIImageOrientationRight,         // 90 deg CW
    switch (o) {
        case UIImageOrientationDown:
            degreesOfRotation = 180.0;
            break;
        case UIImageOrientationLeft:
            degreesOfRotation = 270.0;
            break;
        case UIImageOrientationRight:
            degreesOfRotation = 90.0;
            break;

        default:
            //UIImageOrientationUp -- Default
            break;
    }

    CGRect rect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    //Compress Image
    NSData *imageData = UIImageJPEGRepresentation(img, .8);
    UIGraphicsEndImageContext();

    //Rotate Image
    UIImage *rotatedImg = [[UIImage imageWithData:imageData] imageRotatedByDegrees:degreesOfRotation];
    NSData *rotatedImageData = UIImageJPEGRepresentation(rotatedImg, 1.0);

    return rotatedImageData;
}
ios uiimage afnetworking ios8-share-extension
1个回答
0
投票

请遵循我下面关于内存处理以及在 ios 共享扩展中管理内存的最佳方法的答案。

https://stackoverflow.com/a/76995754/1542369

© www.soinside.com 2019 - 2024. All rights reserved.