2016-08-15 87 views
0

大家好,我是新手,我在我的程序中面臨一個問題。我已經在'保存了一些數據,讓defaultStudentId = NSUserDefaults.standardUserDefaults()',但每次應用程序停止。 defaultStudentId.objectForKey( 「studentId」)這個 「studentId」 從另一個視圖控制器來了....我需要幫助 這裏是我的代碼和錯誤.....swift中的NSRangeException

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] *由於未捕獲異常'NSRangeException',原因:' - [__ NSCFString replaceCharactersInRange:withString:]:範圍或索引超出範圍' *第一次拋出調用堆棧: ( 0 CoreFoundation 0x000000010dcedd85 exceptionPreprocess + 165 1 libobjc.A.dylib 0x0000000110159deb objc_exception_throw + 48 2的CoreFoundation 0x000000010dcedcbd + [NSException提高:格式:] + 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:請求:uploadFile:bodyData:完成:] _ block_invoke + 1 9 8 CFNetwork的0x000000011112b0f2 __49 - [__ NSCFLocalSessionTask _task_onqueue_didFinish] _block_invoke + 302 9基金會0x000000010e82f630 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK + 7 10基金會0x000000010e76a805 - [NSBlockOperation主] + 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 _dis patch_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

基本上

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 } 

它檢查是否存在對鍵的值和以其他方式解開上成功的可選值離開該方法的行。

崩潰的錯誤消息與線

message = responseString?.stringByReplacingCharactersInRange(NSMakeRange(0, 76), withString: "").stringByReplacingOccurrencesOfString("</string>", withString: "") 

避免硬編碼的範圍內的長度,計算它。如果不能,請檢查字符串的長度。

0

你的responseString可能是一個空字符串(「」)。所以當你嘗試用一個範圍代替應用程序崩潰。看看responseString的價值,檢查字符長度大於0和76

添加此打印了var消息後(?responseString .characters.count,「responseString的字符長度」):字符串聲明。