gpt4 book ai didi

ios - 在没有互联网连接的情况下上传图片时如何防止应用崩溃

转载 作者:行者123 更新时间:2023-12-01 17:39:52 26 4
gpt4 key购买 nike

我有 objective-c 代码:

NSString * url = [NSString stringWithFormat:@"http://tragicclothing.co.uk/Retort/imageupload.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSMutableData *body = [[NSMutableData alloc]init];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: audio/basic\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:_imageDataToSend];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

//Send the Request
NSData* returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: nil error: nil];
//serialize to JSON
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];

//parsing JSON
bool success = [result[@"success"] boolValue];
if(success){
NSLog(@"Success=%@",result[@"msg"]);
}else{
NSLog(@"Fail=%@",result[@"msg"]);
}

当连接到互联网时,它可以正常工作,但如果不是,我会收到错误消息:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“数据参数为nil”

最佳答案

您必须在执行网络请求之前检查连接性。

一旦有了downloaded并导入了Reachbility.mReachbility.h文件

创建一个辅助函数:

-(BOOL)IsConnected{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];

return !(networkStatus == NotReachable);
}

然后用
if([self IsConnected]){
//connected!
//upload your image
}
else{
//not connected to internet!
}

非常重要

如果您的项目没有使用arc
  • 转到目标>
  • 构建阶段>
  • 双击可达性文件
  • 添加-fno-objc-arc
  • 关于ios - 在没有互联网连接的情况下上传图片时如何防止应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23280765/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com