为了账号安全,请及时绑定邮箱和手机立即绑定

使用iOS Swift的NSURLConnection

使用iOS Swift的NSURLConnection

ITMISS 2019-12-09 11:24:19
我正在尝试按照本教程并使用Swift和来连接到JSON api NSURLConnection。我可以看到它正在击中url,但connectionDidFinishLoading似乎没有触发。import UIKitclass Remote: NSObject {    var host = "http://localhost:3000"    var query = String()    var data: NSMutableData = NSMutableData()    func connect(query:NSString) {        self.query = query        var url = self.document()        var conn = NSURLConnection(request: url, delegate: self, startImmediately: true)    }    func endpoint() -> NSURL {        var query = self.host + self.query        return NSURL(string: query)    }    func document() -> NSURLRequest {        return NSURLRequest( URL: self.endpoint() )    }    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {        // Recieved a new request, clear out the data object        self.data = NSMutableData()    }    func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {        // Append the recieved chunk of data to our data object        self.data.appendData(conData)    }    func connectionDidFinishLoading(connection: NSURLConnection!) {        // Request complete, self.data should now hold the resulting info        // Convert the retrieved data in to an object through JSON deserialization        var err: NSError        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(self.data, options:    NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary        println(jsonResult.count)    }}// Excecute the codevar remote = Remote()remote.connect("/apis")此时,我只是想查看返回的数据。我确定一旦可以正常运行,便想将其挂接到视图控制器中。这样做是否有问题,并导致问题?
查看完整描述

3 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

检查以下代码:


1. SynchronousRequest


斯威夫特1.2


    let urlPath: String = "YOUR_URL_HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request1: NSURLRequest = NSURLRequest(URL: url)

    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil

    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!

    var err: NSError

    println(response)

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary

    println("Synchronous\(jsonResult)")

迅捷2.0 +


let urlPath: String = "YOUR_URL_HERE"

    let url: NSURL = NSURL(string: urlPath)!

    let request1: NSURLRequest = NSURLRequest(URL: url)

    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil



    do{


        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)


            print(response)

            do {

                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {

                    print("Synchronous\(jsonResult)")

                }

            } catch let error as NSError {

                print(error.localizedDescription)

            }




    }catch let error as NSError

    {

         print(error.localizedDescription)

    }

2. AsynchonousRequest


斯威夫特1.2


let urlPath: String = "YOUR_URL_HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request1: NSURLRequest = NSURLRequest(URL: url)

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        println("Asynchronous\(jsonResult)")

       })

迅捷2.0 +


let urlPath: String = "YOUR_URL_HERE"

    let url: NSURL = NSURL(string: urlPath)!

    let request1: NSURLRequest = NSURLRequest(URL: url)

    let queue:NSOperationQueue = NSOperationQueue()


    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in


        do {

            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                print("ASynchronous\(jsonResult)")

            }

        } catch let error as NSError {

            print(error.localizedDescription)

        }



    })

3.照常URL连接


斯威夫特1.2


    var dataVal = NSMutableData()

    let urlPath: String = "YOUR URL HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request: NSURLRequest = NSURLRequest(URL: url)

    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!

    connection.start()

然后


 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){

    self.dataVal?.appendData(data)

}



func connectionDidFinishLoading(connection: NSURLConnection!)

{

    var error: NSErrorPointer=nil


    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary


    println(jsonResult)




}

迅捷2.0 +


   var dataVal = NSMutableData()

    let urlPath: String = "YOUR URL HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request: NSURLRequest = NSURLRequest(URL: url)

    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!

    connection.start()

然后


func connection(connection: NSURLConnection!, didReceiveData data: NSData!){

    dataVal.appendData(data)

}



func connectionDidFinishLoading(connection: NSURLConnection!)

{


    do {

        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {

            print(jsonResult)

        }

    } catch let error as NSError {

        print(error.localizedDescription)

    }


}

4.异步POST请求


斯威夫特1.2


    let urlPath: String = "YOUR URL HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)


    request1.HTTPMethod = "POST"

     var stringPost="deviceToken=123456" // Key and Value


    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)


    request1.timeoutInterval = 60

    request1.HTTPBody=data

    request1.HTTPShouldHandleCookies=false


    let queue:NSOperationQueue = NSOperationQueue()


     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in



        var err: NSError


        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        println("AsSynchronous\(jsonResult)")



        })

迅捷2.0 +


let urlPath: String = "YOUR URL HERE"

    let url: NSURL = NSURL(string: urlPath)!

    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)


    request1.HTTPMethod = "POST"

    let stringPost="deviceToken=123456" // Key and Value


    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)


    request1.timeoutInterval = 60

    request1.HTTPBody=data

    request1.HTTPShouldHandleCookies=false


    let queue:NSOperationQueue = NSOperationQueue()


    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in


        do {

            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                print("ASynchronous\(jsonResult)")

            }

        } catch let error as NSError {

            print(error.localizedDescription)

        }



    })

5.异步GET请求


斯威夫特1.2


    let urlPath: String = "YOUR URL HERE"

    var url: NSURL = NSURL(string: urlPath)!

    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)


    request1.HTTPMethod = "GET"

    request1.timeoutInterval = 60

    let queue:NSOperationQueue = NSOperationQueue()


     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in



        var err: NSError


        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        println("AsSynchronous\(jsonResult)")



        })

迅捷2.0 +


let urlPath: String = "YOUR URL HERE"

    let url: NSURL = NSURL(string: urlPath)!

    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)


    request1.HTTPMethod = "GET"

    let queue:NSOperationQueue = NSOperationQueue()


    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in


        do {

            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                print("ASynchronous\(jsonResult)")

            }

        } catch let error as NSError {

            print(error.localizedDescription)

        }



    })

6.图片(文件)上传


迅捷2.0 +


  let mainURL = "YOUR_URL_HERE"


    let url = NSURL(string: mainURL)

    let request = NSMutableURLRequest(URL: url!)

    let boundary = "78876565564454554547676"

    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")



    request.HTTPMethod = "POST" // POST OR PUT What you want

    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)


    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)






    var body = NSMutableData()


    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    // Append your parameters


    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)



    // Append your Image/File Data


    var imageNameval = "HELLO.jpg"


    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData(imageData!)

    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    request.HTTPBody = body





    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in


        if error != nil {


            //handle error



        }

        else {





            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!

            print("Response:\(outputString)")



        }

    }

    dataTask.resume()

7. GET,POST,Etc Swift 3.0及更高版本


let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,

    cachePolicy: .useProtocolCachePolicy,

    timeoutInterval:60)

request.httpMethod = "POST" // POST ,GET, PUT What you want 


let session = URLSession.shared




  let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in


do {

            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {

                print("ASynchronous\(jsonResult)")

            }

        } catch let error as NSError {

            print(error.localizedDescription)

        }


    }

    dataTask.resume()


查看完整回答
反对 回复 2019-12-09
  • 3 回答
  • 0 关注
  • 733 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信