jsqmessageviewcontroller图片上传和显示在屏幕上很慢触摸没有反应

Jsqmessageviewcontroller image upload and show on the screen is very slow touch is not responding

每当我滚动我的聊天页面时,它需要很长时间才能获取图像,有时它没有响应,有人可以帮助我解决这个问题。

每当我滚动我的聊天页面时,它需要很长时间来获取图像,有时它没有响应,有人可以帮助我解决这个问题。

- (id<JSQMessageData>)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath {



        JSQMessage *messageForRow;


        NSString * chart = [[DataArray objectAtIndex:indexPath.row] objectForKey:@"Message"];
        NSString * imageurl = [[DataArray objectAtIndex:indexPath.row] objectForKey:@"media"];


        if (chart == nil)
        {
            NSURL *imageURL = [NSURL URLWithString:imageurl];


            NSData *imageData = [NSData dataWithContentsOfURL:imageURL];


            UIImage *image1 = [UIImage imageWithData:imageData];


            JSQPhotoMediaItem *item = [[JSQPhotoMediaItem alloc] initWithImage:image1];
            messageForRow = [[JSQMessage alloc] initWithSenderId:[[DataArray objectAtIndex:indexPath.row] objectForKey:@"UserId"] senderDisplayName:[[DataArray objectAtIndex:indexPath.row] objectForKey:@"Name"] date:[NSDate distantPast] media:item] ;


        }
        else
        {
        messageForRow = [[JSQMessage alloc] initWithSenderId:[[DataArray objectAtIndex:indexPath.row] objectForKey:@"UserId"] senderDisplayName:[[DataArray objectAtIndex:indexPath.row] objectForKey:@"Name"] date:[NSDate distantPast] text: [[DataArray objectAtIndex:indexPath.row] objectForKey:@"Message"]] ;
        }




        return messageForRow;


    }

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{




    img = [info valueForKey:UIImagePickerControllerOriginalImage];


    NSDate *currentDate = [[NSDate alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    NSString *localDateString = [dateFormatter stringFromDate:currentDate];
    NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:@"." withString:@""]stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *cleanedString2 = [cleanedString stringByAppendingFormat:@"%d",1];
    NSString *finalUniqueImageNAme = [cleanedString2 stringByAppendingString:@".jpg"];



    NSData *imageData = UIImageJPEGRepresentation(img, 90);
    NSString *urlString = @"http://192.168.1.92/Abdul/IOS/Chat/upload/upload_file.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"Successfully uploaded");




    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(conn)
    {
        NSLog(@"Connection Successful");
         [self dismissModalViewControllerAnimated:true];
    }
    else
    {
        NSLog(@"Connection could not be made");
    }

      });
    });
    [self dismissModalViewControllerAnimated:true];
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    webdata =[[NSMutableData alloc]init];

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [webdata appendData:data];

}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{


    NSLog(@"%@",error);

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  //   NSString *responseString = [[NSString alloc]initWithData:webdata encoding:NSUTF8StringEncoding];

    dic=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
    //  NSLog( @"Success %@",dic);

     res = [dic objectForKey:@"url"];

    NSLog(@"%@",res);
    NSString * sta = [dic objectForKey:@"Success"];
    if (![sta isEqualToString:@"1"])
    {
        return ;

    }


    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM

    NSString * date = [dateFormatter stringFromDate:[NSDate date]];


    NSString *urlstr1=[@"https://popping-torch-4696.firebaseio.com/" stringByAppendingString:recvStr];

    Firebase *myRootRef = [[Firebase alloc] initWithUrl:urlstr1];

    NSString *dateStr=[NSString stringWithFormat:@"%@",date];

    [[myRootRef childByAutoId ] setValue:@{@"UserId" : str1,@"Name":str2,@"media":res , @"date":dateStr,}];

    [myRootRef observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

        [self.collectionView reloadData];
    }];


}

看来你是在主线程下载图片。更改代码以在后台线程中异步下载它们,然后在主线程中更新单元格。

请检查以下链接:

How to Asynchronously Download and Cache Images without Relying on Third-Party Libraries

Building Concurrent User Interfaces on iOS

如果您不想自己编写代码,您可以使用以下一些库:https://github.com/Alamofire/Alamofire, https://github.com/onevcat/Kingfisher, http://asyncdisplaykit.org/