I have JSON method which fetch data. Everything works on emulator even if I load app from Xcode to iPhone, but when I upload app for testing to Testflight it doesn't work (data doesn't appear) here is my fetch method:
private func fetchSchools(){
let requestURL: NSURL = NSURL(string: "http://somelink.com/json.txt")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everything is fine, file downloaded successfully.")
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String: AnyObject]
if let JSONSchools = json["skoly"] as? [[String: AnyObject]]{
for school in JSONSchools {
if let name = school["nazev"] as? String {
if let city = school["mesto"] as? String {
if let id = school["id"] as? String {
self.schools.append(School.init(name: name, city: city, id: id))
}
}
}
}
self.fetchFinished = true
}
} catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
Thanks for help
I solved the problem. It wasn't in JSON method. I had to:
Select project in the Project Navigator pane
Select project's settings under the "PROJECT" tree
Click "Build Settings" tab
Search for "Optimization Level"
Set release for None [-O0]
Related
I use the function below to verify receipts. As you can see, I used sandbox URL because I test the reciepts before I submit them to the store. What I want to learn is this: before I submit, what should I write in the storeUrl section? How can I access that URL or find it? According to my research, I need to put my server address or something, but the product that I want to submit is non-consumable so I do not have any server for that.
func verifyReciept (transaction : SKPaymentTransaction?) {
let recieptURL = Bundle.main.appStoreReceiptURL!
if let reciept = NSData(contentsOf: recieptURL){
let requestContents = ["receipt-data" : reciept.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0))]
do {
let requestData = try JSONSerialization.data(withJSONObject: requestContents, options: JSONSerialization.WritingOptions(rawValue : 0))
let storeURL = NSURL(string: "https:/sandbox.itunes.apple.com/verifyReceipt")
let request = NSMutableURLRequest(url: storeURL! as URL)
request.httpMethod = "Post"
request.httpBody = requestData
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { (responseData: Data?, response : URLResponse?, error : Error?) -> Void in
do {
let json = try JSONSerialization.jsonObject(with: responseData!, options: .mutableLeaves) as! NSDictionary
print(json)
if(json.object(forKey: "status") as! NSNumber) == 0 {
let receipt_dict = json["receipt"] as! NSDictionary
if let purchases = receipt_dict["in_app"] as? NSArray {
self.validatePurchaseArray(purchases: purchases)
}
if transaction != nil {
SKPaymentQueue.default().finishTransaction(transaction!)
}
}
else {
print(json.object(forKey: "status") as! NSNumber)
}
}
catch{
print(error)
}
})
task.resume()
} catch {
print(error)
}
}
else {
print("No Reciept")
}
}
You should replace that with the prod URL for verifying receipts:
"https://buy.itunes.apple.com/verifyReceipt"
The thing you are talking about involving you server is an additional measure you can take. For the server side verification, you need to send the receipt to your server and then run this same function from your server.
Am a newbie in swift, am trying to post a new feed on user's wall like facebook, but my api response is displaying nil in console, and it works fine in web, any help is appreciated, Thanks.
#IBAction func upload(_ sender: AnyObject) {
let user = UserManager.getLoggedInUser()!
let request = NSMutableURLRequest(url:NSURL(string: "http://www.MYAPI")!as URL)
let session = URLSession.shared
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let PostUtctime = DateFormatter()
PostUtctime.dateFormat = "YYYY-MM-dd'To'HH:mm:ss"
let str: String = PostUtctime.string(from: Date())
print("Date = \(str)")
let guidMemberID = user.userID
print(guidMemberID)
let paramToSend = "{\"guidMemberID\":\"\(user.userID)\", \"ImageString\": \", \"strAboutFeed\":\"\(textView.text)\", \"PostUtctime\": \"\(PostUtctime)\"}"
API normally responds after the above line execution saying its posted successfully or there's been an error
print(textView.text as Any)
request.httpBody = (paramToSend as AnyObject) as? Data
session.dataTask(with: request as URLRequest,completionHandler: {
(data, response, error) -> Void in
guard let _:Data = data
else {
print(response as Any)
return
}
var json: [String:AnyObject]
do {
json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary as! [String : AnyObject]
print(json)
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseDataDictionary: Dictionary<String,AnyObject> = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! Dictionary<String,AnyObject>
print(responseDataDictionary)
}
catch {
print("Error: \(error.localizedDescription)")
}
}).resume()
}
}
This is, if there's an error part of the code, Thank you for the time.
I am getting stuck with HTTP request.it did not show any error.compiler reads the first two lines and skip the code to "task.resume()".i am fetching data with same code on other view controller but it creats problem here
func getCustomers()
{
let url = NSURL(string: "myURL.com")
let task = URLSession.shared.dataTask(with: url! as URL) {
(data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
print("error: \(String(describing: error))")
return
}
do
{
self.getcustomersArray = [GetCustomers]()
//JSON Parsing
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
{
let results = json["Result"] as? [[String : Any]]
let getCustomersObject:GetCustomers = GetCustomers()
for result in results!
{
getCustomersObject.ActivityPrefix = (result["ActivityPrefix"] as? String)!
getCustomersObject.CustomerID = (result["CustomerID"] as? String)!
getCustomersObject.CustomerName = (result["CustomerName"] as? String)!
getCustomersObject.TFMCustomerID = (result["TFMCustomerID"] as? String)!
getCustomersObject.ShortName = (result["ShortName"] as? String)!
getCustomersObject.UserRights = (result["UserRights"] as? Int)!
self.totalCustomers += self.totalCustomers
}
self.customerName = getCustomersObject.CustomerName
}
}//end Do
catch
{
}
}
task.resume()
}
Using Block GET/POST/PUT/DELETE:
let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error)
} else {
print(httpResponse)
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
I think you dont mention line
request.httpMethod = "GET"
Hi my question is related to json object. i have this link "http://ip-api.com/json" and this link gives the details of your IP Address. i only need to print IP Address from this json file in swift 3. i am very new might be my question is basic but i need some help to sort out my project. so for i have done like below.
let requestURL: NSURL = NSURL(string: "http://ip-api.com/json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
if let stations = json["city"] as? [[String: AnyObject]] {
for station in stations {
if let name = station["regionName"] as? String {
self.names.append(name)
print("this is query\(name)")
}
else{
print ("no ip address is found")
}
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
many thanks in advance.
The IP address is the value for key query on the top level of the JSON
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let query = json["query"] as? String {
print(query)
}
In Swift 3 the type of a JSON dictionary is [String:Any]
PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL (and URLRequest)
let requestURL = URL(string: "http://ip-api.com/json")!
...
let task = session.dataTask(with: requestURL) {
let url1 = "https://jsonplaceholder.typicode.com/posts"
var request = URLRequest(url: URL(string: url1)!)
request.httpMethod = "GET"
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request, completionHandler: {(data,response,error) -> Void in
if let error = error {
print(error)
return
}
if let data = data {
OperationQueue.main.addOperation({ () -> Void in
self.tableView.reloadData()
})
}
})
task.resume()
With or without http method, response data is empty. What am I doing wrong? WiFi works fine. Maybe problem on my simulator settings?
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
let posts = json as? [[String: Any]] ?? []
print(posts)
for post in posts{
let product = Product()
product.userId = post["userId"] as! Int
product.id = post["id"] as! Int
product.title = post["title"] as! String
product.body = post["body"] as! String
self.products.append(product)
}
} catch let error as NSError {
print(error)
}
}).resume()
Yeah thanks, but your code is not works too, i mean say data is empty, nothing to be parsed. WiFi on my emulator works fine maybe problem on my xcode8?
Made some changes in your code.
let url = NSURL(string: "https://jsonplaceholder.typicode.com/posts")
NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest.init(URL: url!), completionHandler: {(data, response, error) in
guard let data = data where error == nil else { return }
do {
let posts = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
print(posts)
} catch let error as NSError {
print(error)
}
}).resume()
Output :
Here your all 100 post display