大家好,我是swift的新手,我在我的程序中面临一个问题。我已将一些数据保存在' let defaultStudentId = NSUserDefaults.standardUserDefaults()'但每次应用程序停止。 defaultStudentId.objectForKey(" studentId")这个" studentId"来自另一个ViewController ....我需要帮助 这是我的代码和错误.....
import UIKit
class OTPViewController: ViewController {
@IBOutlet weak var OTP_code: UITextField!
let defaultStudentId = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func confirm(sender: AnyObject) {
let std_id = defaultStudentId.objectForKey("studentId")
let sendOTPCode = "StudentId=\(std_id)&CODE=\(self.OTP_code.text)&PartnerID=4B67B239CF3735814C063DB89D750481"
let url = NSURL(string: "http://serviceforonair.examonair.com/AndroidService.asmx/VerifyOTPAndActivateStudent")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = sendOTPCode.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
if error != nil{
print(error)
return
}
do{
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
var message : String!
message = responseString?.stringByReplacingCharactersInRange(NSMakeRange(0, 76), withString: "").stringByReplacingOccurrencesOfString("</string>", withString: "")
print(self.defaultStudentId)
}
catch let jsonException{
print(jsonException)
}
}
task.resume()
}
}
错误 2016-08-15 20:14:10.555 DBMCI [21415:143621] *由于未捕获的异常终止应用程序&#39; NSRangeException&#39;,原因:&#39; - [__ NSCFString replaceCharactersInRange:withString:]:范围或指数超出范围&#39; * 第一次抛出调用堆栈: ( 0 CoreFoundation 0x000000010dcedd85 exceptionPreprocess + 165 1 libobjc.A.dylib 0x0000000110159deb objc_exception_throw + 48 2 CoreFoundation 0x000000010dcedcbd + [NSException raise:format:] + 205 3 CoreFoundation 0x000000010dcb90ad mutateError + 221 4基础0x000000010e7c887c - [NSString stringByReplacingCharactersInRange:withString:] + 142 5 DBMCI 0x000000010d62de96 _TFFC5DBMCI17OTPViewController7confirmFPs9AnyObject_T_U_FTGSqCSo6NSData_GSqCSo13NSURLResponse_GSqCSo7NSError__T_ + 902 6 DBMCI 0x000000010d622c87 _TTRXFo_oGSqCSo6NSData_oGSqCSo13NSURLResponse_oGSqCSo7NSError__dT__XFdCb_dGSqS__dGSqS0__dGSqS1 ___ dT + 103 7 CFNetwork 0x0000000111118b49 75 - [__ NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:] _ block_invoke + 19 8 CFNetwork 0x000000011112b0f2 __49 - [__ NSCFLocalSessionTask _task_onqueue_didFinish] _block_invoke + 302 9基金会0x000000010e82f630 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK + 7 10基金会0x000000010e76a805 - [NSBlockOperation main] + 101 11基金会0x000000010e74d725 - [__ NSOperationInternal _start:] + 646 12基金会0x000000010e74d336 __NSOQSchedule_f + 194 13 libdispatch.dylib 0x000000011197a3eb _dispatch_client_callout + 8 14 libdispatch.dylib 0x000000011196082c _dispatch_queue_drain + 2215 15 libdispatch.dylib 0x000000011195fd4d _dispatch_queue_invoke + 601 16 libdispatch.dylib 0x0000000111962996 _dispatch_root_queue_drain + 1420 17 libdispatch.dylib 0x0000000111962405 _dispatch_worker_thread3 + 111 18 libsystem_pthread.dylib 0x0000000111cb74de _pthread_wqthread + 1129 19 libsystem_pthread.dylib 0x0000000111cb5341 start_wqthread + 13 ) libc ++ abi.dylib:以NSException类型的未捕获异常终止 (lldb)
答案 0 :(得分:0)
基本上
let std_id = defaultStudentId.objectForKey("studentId")
返回一个可选值,因此在字符串插值"StudentId=\(std_id)"
中,您将得到例如"StudentId=Optional(24)"
而不是预期的"StudentId=24"
,这肯定不是您想要的。
假设键studentId
的对象是String
,请用
guard let std_id = defaultStudentId.stringForKey("studentId") else { return }
检查key的值是否存在,并在成功时解除可选值,否则退出该方法。
崩溃的错误消息与行
有关message = responseString?.stringByReplacingCharactersInRange(NSMakeRange(0, 76), withString: "").stringByReplacingOccurrencesOfString("</string>", withString: "")
避免硬编码范围长度,计算它。如果不能,请检查字符串的长度。
答案 1 :(得分:0)
你的responseString可能只是一个空字符串(&#34;&#34;)。因此,当您尝试使用范围替换时,应用程序崩溃。看一下responseString的值,检查字符长度是否大于0和76。
在var message:String声明后添加 print(responseString?.characters.count ,&#34; responseString&#39; s字符长度&#34;)。