GCDAsyncsocket uses the asynchronous serial sub-thread to stop executing the for loop halfway through. The code is as follows. The process is to click the send button to return to the main page, and then execute the following code asynchronously to upload the image;
- (void)sendAction{
dispatch_queue_t queue = dispatch_queue_create("uploadImage", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
for (int i =0; i < 10; i++) {
NSLog(@"async ------------ %@", [NSThread currentThread]);
//第一张图的资源
PHAsset *asset = self.sendImageArray[i];
NSString *fileType;
NSString *fileName;
if (asset.mediaType == PHAssetMediaTypeImage) {
fileType = @"jpg";
NSData *data = [NSData dataWithContentsOfFile:filePath[i]];
[self upLoadImageData:data type:@"jpg" name:fileName];
} else if(asset.mediaType == PHAssetMediaTypeVideo) {
fileType = @"mp4";
NSData *data = [NSData dataWithContentsOfFile:filePath[i]];
[self uploadMp4Data:data type:fileType name:fileName];
}
}
});
}
- (void)upLoadImageData:(NSData*)data type:(NSString *)fileType name:(NSString *)fileName{
dataNameMutStr = [NSMutableString stringWithFormat:@"ios_%@_%@.jpg\n", @"图片",fileName];
NSData *dataName = [dataNameMutStr dataUsingEncoding:NSUTF8StringEncoding];
[self sendSocket:dataName data:data];
}
- (void)sendSocket:(NSData *)dataName data:(NSData *)datas{
[self createClientTcpSocket];//发图片
[_asyncsocket writeData:datas withTimeout:-1 tag:0];
}
The information is not complete and it is difficult to judge the reason, but in this case, the for loop should be put inside
Also, a lock should be added when accessing resources
The code and logs are incomplete and I can’t see why. Guess two reasons:
In fact, it still works, but you can’t catch the status due to debugging issues
It was really interrupted. The specific reason needs to be investigated in depth. However, it is recommended that you use queue as a reference and hold it for a long time, not as a local variable. If it is a local variable, what is the point of making a serial queue?