Reputation: 47
I read this about the URL Loading System:
Can't figure out what class use and how to use it.
Upvotes: 0
Views: 1041
Reputation: 2468
I suggest using a third party framework like Alamofire The native Swift networking is rather complicated, especially for beginners, because Swift is type-safe language and a JSON object can have nesting etc. that can only be seen after actually fetching of the object.
The good thing is that Alamofire can be easily installed with CocoaPods and it is actively being developed. Here is an example of a request made with Alamofire's 4.0 version for Swift 3 to fetch a JSON object from a url called yourUrl:
Alamofire.request("https://yourUrl").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let json = response.result.value {
print("JSON: \(json)")
// do something with json here
}
}
You can then use another third party framework like SwiftyJSON to parse the JSON you retrieve - especially if it has a complicated structure. But sadly there is no update in sight for Swift 3 so I guess we have to wait and see how this pans out.
EDIT: There is an unofficial Swift 3 branch for SwiftyJSON, which can be installed with cocoapods (it works for me on iOS10/Swift 3):
pod 'SwiftyJSON', git: 'https://github.com/BaiduHiDeviOS/SwiftyJSON.git', branch: 'swift3'
Upvotes: 2
Reputation: 427
Use following function to load URL.
fun loadURL()->void{
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var dataTask: NSURLSessionDataTask?
let url = NSURL(string: "URL TO LOAD")//Add url string here
dataTask = defaultSession.dataTaskWithURL(url!) {
data, response, error in
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
print(data);
//Process data here..
}
}
}
dataTask?.resume()
}
You can use build in NSJSonSerialization class to convert NSdata into NSDictionary and then parse Dictionary to extract values.Your parsing logic will be added //Process data here.. in place of this comment in above code base.
Upvotes: 0